Skip to content

The agent that grows with you

feat: /loop — recurring in-session wakeups (Claude Code parity)

teknium1f79440e0f4bb
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.py
index b62b8c8ad41..aeffedb678b 100644
--- a/agent/conversation_compression.py
+++ b/agent/conversation_compression.py
@@ -3404,6 +3404,14 @@ def compress_context(
migrate_heartbeat_to_session(old_session_id, agent.session_id)
except Exception as _hb_err:
logger.debug("Could not migrate heartbeat on compression: %s", _hb_err)
+ # Same boundary hazard for a persistent /loop — carry it
+ # onto the continuation session so the recurring wakeups
+ # survive compression.
+ try:
+ from hermes_cli.loops import migrate_loop_to_session
+ migrate_loop_to_session(old_session_id, agent.session_id, reason="compression")
+ except Exception as _loop_err:
+ logger.debug("Could not migrate loop on compression: %s", _loop_err)
# Carry the title across the compression boundary unchanged.
#
# This used to renumber ("Fix X" → "Fix X #2") on every
diff --git a/apps/desktop/src/lib/desktop-slash-commands.ts b/apps/desktop/src/lib/desktop-slash-commands.ts
index 0f026720144..495479899d6 100644
--- a/apps/desktop/src/lib/desktop-slash-commands.ts
+++ b/apps/desktop/src/lib/desktop-slash-commands.ts
@@ -266,6 +266,13 @@ const DESKTOP_COMMAND_SPECS: readonly DesktopCommandSpec[] = [
surface: exec(),
argumentMode: 'mixed'
},
+ {
+ name: '/loop',
+ description: 'Re-run a prompt on a recurring interval in this session',
+ aliases: ['/proactive'],
+ surface: exec(),
+ argumentMode: 'mixed'
+ },
{
name: '/personality',
description: 'Switch personality for this session',
diff --git a/cli.py b/cli.py
index 5ccf42d9393..8fe7720d2b4 100644
--- a/cli.py
+++ b/cli.py
@@ -11166,6 +11166,8 @@ class HermesCLI(CLIAgentSetupMixin, CLICommandsMixin, CLIBillingMixin):
self._handle_heartbeat_command(cmd_original)
elif canonical == "refine":
self._handle_refine_command(cmd_original)
+ elif canonical == "loop":
+ self._handle_loop_command(cmd_original)
elif canonical == "moa":
# /moa is one-shot sugar only: run a single prompt through the
# default MoA preset, then restore the prior model. To *switch* to a
@@ -11510,6 +11512,149 @@ class HermesCLI(CLIAgentSetupMixin, CLICommandsMixin, CLIBillingMixin):
threading.Thread(target=_loop, daemon=True, name="heartbeat-watchdog").start()
+ # ────────────────────────────────────────────────────────────────
+ # /loop — recurring in-session wakeups (Claude Code /loop parity)
+ # ────────────────────────────────────────────────────────────────
+ def _get_loop_manager(self):
+ """Return the LoopManager bound to the current session_id.
+
+ Cached on ``self._loop_manager`` and rebound lazily when
+ ``session_id`` changes (mirrors ``_get_goal_manager``).
+ """
+ try:
+ from hermes_cli.loops import LoopManager
+ except Exception as exc:
+ logging.debug("loop manager unavailable: %s", exc)
+ return None
+
+ sid = getattr(self, "session_id", None) or ""
+ if not sid:
+ return None
+
+ existing = getattr(self, "_loop_manager", None)
+ if existing is not None and getattr(existing, "session_id", None) == sid:
+ return existing
+
+ mgr = LoopManager(session_id=sid)
+ self._loop_manager = mgr
+ return mgr
+
+ def _maybe_fire_loop_tick(self) -> None:
+ """Idle hook run from process_loop: fire a due /loop wakeup.
+
+ Only runs while the agent is idle and nothing is queued — a real
+ user message always wins the idle boundary. An active (non-parked)
+ /goal also wins: its judge-driven continuations own the idle
+ boundary, so the loop defers to the next poll.
+ """
+ mgr = self._get_loop_manager()
+ if mgr is None or not mgr.is_due():
+ return
+ # The idle poll runs at ~10 Hz; once a tick is due but deferred
+ # (queued input / active goal), every poll would otherwise hit the
+ # DB via goal_blocks_loop_tick. Throttle the deferred re-check.
+ now = time.time()
+ if now - getattr(self, "_last_loop_tick_check", 0.0) < 2.0:
+ return
+ self._last_loop_tick_check = now
+ # Real user input (or anything else queued) takes priority; the
+ # loop stays due and fires at the next idle poll.
+ try:
+ if not self._pending_input.empty():
+ return
+ except Exception:
+ return
+ try:
+ from hermes_cli.loops import goal_blocks_loop_tick
+
+ if goal_blocks_loop_tick(mgr.session_id):
+ return
+ except Exception:
+ pass
+
+ wakeup = mgr.fire_tick()
+ if not wakeup:
+ return
+ try:
+ state = mgr.state
+ tick_no = state.ticks_fired if state else "?"
+ _cprint(f" {_DIM}↻ /loop wakeup #{tick_no} firing…{_RST}")
+ self._pending_input.put(wakeup)
+ except Exception as exc:
+ logging.debug("loop tick injection failed: %s", exc)
+ try:
+ mgr.abandon_tick()
+ except Exception:
+ pass
+ return
+ # A slash-command loop (e.g. `/loop 10m /recap`) is dispatched via
+ # process_command, which never reaches the post-turn chat() finally
+ # block — so the tick would never complete and the loop would wedge
+ # on awaiting_response. Slash ticks have no model reply to evaluate;
+ # complete them immediately (caps and scheduling still apply).
+ if wakeup.lstrip().startswith("/"):
+ try:
+ decision = mgr.complete_tick("")
+ msg = decision.get("message") or ""
+ if msg:
+ _cprint(f" {msg}")
+ except Exception:
+ pass
+
+ def _maybe_complete_loop_tick_after_turn(self) -> None:
+ """Post-turn hook: evaluate a finished /loop wakeup turn.
+
+ No-op unless the turn that just ended was a loop wakeup
+ (``awaiting_response`` set by ``fire_tick``). Detects the
+ LOOP_COMPLETE marker, judges --until, applies caps, and schedules
+ the next tick. Mirrors _maybe_continue_goal_after_turn's shape.
+ """
+ mgr = self._get_loop_manager()
+ if mgr is None:
+ return
+ state = mgr.state
+ if state is None or not state.awaiting_response:
+ return
+
+ # A user-interrupted wakeup turn pauses the loop (recoverable via
+ # /loop resume) — same contract as the goal loop's Ctrl+C handling.
+ if getattr(self, "_last_turn_interrupted", False):
+ try:
+ mgr.pause(reason="user-interrupted (Ctrl+C)")
+ except Exception:
+ pass
+ _cprint(
+ f" {_DIM}⏸ Loop paused — wakeup turn was interrupted. "
+ f"Use /loop resume to continue, or /loop stop to end it.{_RST}"
+ )
+ return
+
+ last_response = ""
+ try:
+ hist = self.conversation_history or []
+ for msg in reversed(hist):
+ if msg.get("role") == "assistant":
+ content = msg.get("content", "")
+ if isinstance(content, list):
+ parts = [
+ p.get("text", "")
+ for p in content
+ if isinstance(p, dict) and p.get("type") in {"text", "output_text"}
+ ]
+ last_response = "\n".join(t for t in parts if t)
+ else:
+ last_response = str(content or "")
+ break
+ except Exception:
+ last_response = ""
+
+ decision = mgr.complete_tick(last_response)
+ msg = decision.get("message") or ""
+ if msg:
+ _cprint(f" {msg}")
+ elif decision.get("status") == "active" and mgr.state is not None:
+ _cprint(f" {_DIM}↻ Loop: {mgr.state.remaining_label()}.{_RST}")
+
def _owns_process_notification(self, event: dict) -> bool:
@@ -18281,6 +18426,12 @@ class HermesCLI(CLIAgentSetupMixin, CLICommandsMixin, CLIBillingMixin):
self._drain_process_notifications("cli-idle")
except Exception:
pass
+ # Fire a due /loop wakeup while idle (defers to
+ # queued user input and active /goal loops).
+ try:
+ self._maybe_fire_loop_tick()
+ except Exception:
+ pass
continue
# Voice-transcribed messages arrive wrapped in a sentinel
@@ -18451,6 +18602,14 @@ class HermesCLI(CLIAgentSetupMixin, CLICommandsMixin, CLIBillingMixin):
except Exception as _goal_exc:
logging.debug("goal continuation hook failed: %s", _goal_exc)
+ # /loop tick completion: if the turn that just ended
+ # was a loop wakeup, evaluate it (LOOP_COMPLETE marker,
+ # --until judge, caps) and schedule the next tick.
+ try:
+ self._maybe_complete_loop_tick_after_turn()
+ except Exception as _loop_exc:
+ logging.debug("loop completion hook failed: %s", _loop_exc)
+
# Continuous voice: auto-restart recording after agent responds.
# Dispatch to a daemon thread so play_beep (sd.wait) and
# AudioRecorder.start (lock acquire) never block process_loop —
diff --git a/gateway/run.py b/gateway/run.py
index 3092fd31c5a..af607198ba8 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -12525,6 +12525,11 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew
# idle case where the subagent finishes with no agent turn running.
self._spawn_supervised(self._async_delegation_watcher, "async_delegation_watcher")
+ # Start background /loop wakeup watcher — scans persisted loops
+ # (SessionDB loop:* rows) and injects due wakeup prompts into their
+ # originating chats while the session is idle.
+ self._spawn_supervised(self._loop_wakeup_watcher, "loop_wakeup_watcher")
+
# Start the scale-to-zero idle watcher ONLY when this instance is opted
# in (the NAS "Labs" HERMES_SCALE_TO_ZERO stamp), messaging is
# relay-only/absent, and a wakeUrl is registered (decisions.md D1/D11/
@@ -15316,6 +15321,7 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew
"steer": self._busy_steer_command,
"egress": self._busy_egress_command,
"goal": self._busy_goal_command,
+ "loop": self._busy_loop_command,
}.get(handler_key)
if special is not None:
return await special(event, quick_key, source)
@@ -15546,6 +15552,15 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew
return await self._handle_goal_command(event)
return "Agent is running — use /goal status / pause / clear / wait mid-run, or /stop before setting a new goal."
+ async def _busy_loop_command(self, event: MessageEvent, quick_key: str, source):
+ # /loop mirrors /goal: control verbs are safe mid-run (state
+ # only — read at the next idle boundary); setting a new loop
+ # mid-run is rejected so we don't race the current turn.
+ _loop_arg = (event.get_command_args() or "").strip().lower()
+ if not _loop_arg or _loop_arg in {"status", "pause", "resume", "stop", "clear", "cancel", "help", "--help", "-h"}:
+ return await self._handle_loop_command(event)
+ return "Agent is running — use /loop status / pause / stop mid-run, or /stop before setting a new loop."
+
async def _handle_message(self, event: MessageEvent) -> Optional[str]:
"""
Handle an incoming message from any platform.
@@ -16715,6 +16730,9 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew
if canonical == "goal":
return await self._handle_goal_command(event)
+ if canonical == "loop":
+ return await self._handle_loop_command(event)
+
if canonical == "heartbeat":
return await self._handle_heartbeat_command(event)
if canonical == "refine":
@@ -17100,6 +17118,14 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew
source=source,
final_response=_final_text,
)
+ # /loop tick completion: if this turn was a loop
+ # wakeup, evaluate it (LOOP_COMPLETE marker, --until
+ # judge, caps) and schedule the next tick.
+ await self._post_turn_loop_completion(
+ session_entry=session_entry,
+ source=source,
+ final_response=_final_text,
+ )
except Exception as _goal_exc:
logger.debug("goal continuation hook failed: %s", _goal_exc)
return _agent_result
@@ -20658,6 +20684,148 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew
+ async def _post_turn_loop_completion(
+ self,
+ *,
+ session_entry: Any,
+ source: Any,
+ final_response: str,
+ ) -> None:
+ """Complete a /loop wakeup tick after a gateway turn.
+
+ No-op unless the session has a loop whose tick is in flight
+ (``awaiting_response`` — set when the wakeup was injected). Applies
+ the LOOP_COMPLETE marker / --until judge / caps and schedules the
+ next tick; the idle wakeup watcher fires it when due.
+ """
+ try:
+ from hermes_cli.loops import LoopManager
+ except Exception as exc:
+ logger.debug("loop completion: loops module unavailable: %s", exc)
+ return
+
+ sid = getattr(session_entry, "session_id", None) or ""
+ if not sid:
+ return
+
+ mgr = LoopManager(session_id=sid)
+ state = mgr.state
+ if state is None or not state.awaiting_response:
+ return
+
+ # The --until judge is a sync aux-LLM call — keep it off the event loop.
+ decision = await asyncio.get_running_loop().run_in_executor(
+ None, mgr.complete_tick, final_response or ""
+ )
+ msg = decision.get("message") or ""
+ if msg and source is not None:
+ await self._defer_goal_status_notice_after_delivery(source, msg)
+
+ async def _loop_wakeup_watcher(self, interval: float = 15.0) -> None:
+ """Fire due /loop wakeups for idle gateway sessions.
+
+ The gateway has no per-session scheduler thread, so a coarse ticker
+ scans persisted loops (SessionDB ``loop:*`` rows) and injects the
+ wakeup prompt into each due session's chat via the same synthetic-
+ message path used by watch notifications. Deferrals:
+
+ - session currently running an agent turn → skip (stays due; the
+ adapter FIFO would race the live turn otherwise)
+ - active non-parked /goal on the session → skip (goal owns the
+ idle boundary)
+ - no routing metadata on the loop → skip with a one-time warning
+ (CLI/TUI loops carry no route and are driven by their own surfaces)
+ """
+ await asyncio.sleep(5) # let platforms finish connecting
+ warned_no_route: set = set()
+ while self._running:
+ try:
+ from hermes_cli.loops import (
+ LoopManager,
+ goal_blocks_loop_tick,
+ list_active_loops,
+ )
+
+ now = time.time()
+ for sid, state in list_active_loops():
+ if state.awaiting_response or now < state.next_due_at:
+ continue
+ route = state.route or {}
+ platform_name = route.get("platform", "")
+ chat_id = route.get("chat_id", "")
+ if not platform_name or not chat_id:
+ # CLI / TUI-owned loop — their own schedulers drive it.
+ continue
+ adapter = None
+ for p, a in self.adapters.items():
+ if p.value == platform_name:
+ adapter = a
+ break
+ if adapter is None:
+ if sid not in warned_no_route:
+ warned_no_route.add(sid)
+ logger.debug(
+ "loop wakeup: no adapter for platform %r (session %s)",
+ platform_name, sid,
+ )
+ continue
+
+ # Build the source + session key to check business.
+ evt_stub = {
+ "session_key": "",
+ "platform": platform_name,
+ "chat_id": chat_id,
+ "chat_type": route.get("chat_type", ""),
+ "thread_id": route.get("thread_id", ""),
+ "user_id": route.get("user_id", ""),
+ "user_name": route.get("user_name", ""),
+ }
+ source = self._build_process_event_source(evt_stub)
+ if source is None:
+ continue
+ try:
+ session_key = self._session_key_for_source(source)
+ except Exception:
+ session_key = None
+ if session_key and session_key in self._running_agents:
+ continue # busy — stays due, next scan retries
+ if goal_blocks_loop_tick(sid):
+ continue
+
+ mgr = LoopManager(session_id=sid)
+ if not mgr.is_due(now):
+ continue
+ wakeup = mgr.fire_tick()
+ if not wakeup:
+ continue
+ try:
+ synth_event = MessageEvent(
+ text=wakeup,
+ message_type=MessageType.TEXT,
+ source=source,
+ internal=True,
+ )
+ logger.info(
+ "loop wakeup #%s — injecting for %s chat=%s thread=%s",
+ mgr.state.ticks_fired if mgr.state else "?",
+ platform_name, source.chat_id, source.thread_id,
+ )
+ await adapter.handle_message(synth_event)
+ # Slash-command loops dispatch through the command
+ # path and never hit the post-turn completion hook —
+ # complete the tick immediately (caps + scheduling).
+ if wakeup.lstrip().startswith("/"):
+ mgr.complete_tick("")
+ except Exception as exc:
+ logger.warning("loop wakeup injection failed for %s: %s", sid, exc)
+ try:
+ mgr.abandon_tick()
+ except Exception:
+ pass
+ except Exception as exc:
+ logger.debug("loop wakeup watcher error: %s", exc)
+ await asyncio.sleep(interval)
+
@staticmethod
def _get_guild_id(event: MessageEvent) -> Optional[int]:
"""Extract Discord guild_id from the raw message object."""
diff --git a/gateway/slash_commands.py b/gateway/slash_commands.py
index 52d8fc78b3e..6b87f59751c 100644
--- a/gateway/slash_commands.py
+++ b/gateway/slash_commands.py
@@ -2982,6 +2982,76 @@ class GatewaySlashCommandsMixin:
idx = len(mgr.state.subgoals) if mgr.state else 0
return f"✓ Added subgoal {idx}: {text}"
+ async def _get_loop_manager_for_event(self, event: "MessageEvent"):
+ """Return a LoopManager bound to the session for this gateway event.
+
+ Returns ``(manager, session_entry)`` or ``(None, None)`` when the
+ loops module or session can't be loaded. Mirrors
+ ``_get_goal_manager_for_event``.
+ """
+ try:
+ from hermes_cli.loops import LoopManager
+ except Exception as exc:
+ logger.debug("loop manager unavailable: %s", exc)
+ return None, None
+ try:
+ session_entry = await self.async_session_store.get_or_create_session(event.source)
+ except Exception:
+ return None, None
+ sid = getattr(session_entry, "session_id", None) or ""
+ if not sid:
+ return None, None
+ return LoopManager(session_id=sid), session_entry
+
+ async def _handle_loop_command(self, event: "MessageEvent") -> str:
+ """Handle /loop for gateway platforms — recurring in-session wakeups.
+
+ Mirrors the CLI handler via the shared ``dispatch_loop_command``.
+ New loops capture the event's routing (platform/chat/thread) so the
+ gateway's idle loop-wakeup watcher can inject ticks back into this
+ chat even after a restart.
+ """
+ try:
+ from hermes_cli.loops import dispatch_loop_command, goal_blocks_loop_tick
+ except Exception as exc:
+ logger.debug("loops module unavailable: %s", exc)
+ return "Loops unavailable."
+
+ mgr, _session_entry = await self._get_loop_manager_for_event(event)
+ if mgr is None:
+ return "Loops unavailable (no active session)."
+
+ route: dict = {}
+ try:
+ src = event.source
+ if src is not None:
+ platform = getattr(src, "platform", "")
+ route = {
+ "platform": platform.value if hasattr(platform, "value") else str(platform or ""),
+ "chat_id": str(getattr(src, "chat_id", "") or ""),
+ "chat_type": str(getattr(src, "chat_type", "") or ""),
+ "thread_id": str(getattr(src, "thread_id", "") or ""),
+ "user_id": str(getattr(src, "user_id", "") or ""),
+ "user_name": str(getattr(src, "user_name", "") or ""),
+ }
+ route = {k: v for k, v in route.items() if v}
+ except Exception:
+ route = {}
+
+ args = (event.get_command_args() or "").strip()
+ result = dispatch_loop_command(mgr, args, route=route)
+ output = result.get("output") or ""
+ if result.get("created"):
+ try:
+ if goal_blocks_loop_tick(mgr.session_id):
+ output += (
+ "\nNote: an active /goal is driving this session — loop "
+ "wakeups defer until the goal finishes, pauses, or parks."
+ )
+ except Exception:
+ pass
+ return output
+
async def _handle_undo_command(self, event: MessageEvent) -> str:
"""Handle /undo [N] — back up N user turns (default 1), soft-deleting
the truncated rows on disk and echoing the backed-up message text so
diff --git a/hermes_cli/cli_commands_mixin.py b/hermes_cli/cli_commands_mixin.py
index 612ebbb6455..4349db8926d 100644
--- a/hermes_cli/cli_commands_mixin.py
+++ b/hermes_cli/cli_commands_mixin.py
@@ -2807,6 +2807,39 @@ class CLICommandsMixin:
except Exception:
pass
+ def _handle_loop_command(self, cmd: str) -> None:
+ """Dispatch /loop — recurring in-session wakeups (Claude Code parity).
+
+ Forms:
+ /loop [interval] <prompt> [--times N] [--until <cond>] start a loop
+ /loop status | pause | resume | stop controls
+ """
+ from cli import _DIM, _RST, _cprint
+ parts = (cmd or "").strip().split(None, 1)
+ arg = parts[1].strip() if len(parts) > 1 else ""
+
+ mgr = self._get_loop_manager()
+ if mgr is None:
+ _cprint(f" {_DIM}Loops unavailable (no active session).{_RST}")
+ return
+
+ from hermes_cli.loops import dispatch_loop_command
+
+ result = dispatch_loop_command(mgr, arg)
+ for line in (result.get("output") or "").splitlines():
+ _cprint(f" {line}")
+ if result.get("created"):
+ try:
+ from hermes_cli.loops import goal_blocks_loop_tick
+
+ if goal_blocks_loop_tick(mgr.session_id):
+ _cprint(
+ f" {_DIM}Note: an active /goal is driving this session — "
+ f"loop wakeups defer until the goal finishes, pauses, or parks.{_RST}"
+ )
+ except Exception:
+ pass
+
def _handle_subgoal_command(self, cmd: str) -> None:
"""Dispatch /subgoal subcommands.
diff --git a/hermes_cli/commands.py b/hermes_cli/commands.py
index 1f9e70e4308..a0c94bbe47e 100644
--- a/hermes_cli/commands.py
+++ b/hermes_cli/commands.py
@@ -168,6 +168,10 @@ COMMAND_REGISTRY: list[CommandDef] = [
busy_policy="dispatch"),
CommandDef("refine", "Review this conversation now and save lessons to memory/skills", "Session",
args_hint="[focus instructions]"),
+ CommandDef("loop", "Re-run a prompt on a recurring interval in this session", "Session",
+ aliases=("proactive",),
+ args_hint="[interval] <prompt> [--times N] [--until <condition>] | status | pause | resume | stop",
+ busy_policy="dispatch", busy_handler="loop"),
CommandDef("moa", "Run one prompt through the default Mixture of Agents preset, then restore your model", "Session",
args_hint="<prompt>", busy_policy="reject", busy_handler="moa"),
CommandDef("subgoal", "Add or manage extra criteria on the active goal", "Session",
@@ -1277,7 +1281,12 @@ _SLACK_PRIORITY_ALIASES = ("btw", "bg")
# native slash.
# - pause: global emergency stop; reached via /hermes pause [off] on
# Slack. Added at the 50-cap — a native slot would clamp /platform.
-_SLACK_VIA_HERMES_ONLY = frozenset({"topup", "moa", "debug", "egress", "init", "version", "diff", "update", "heartbeat", "refine", "pause"})
+# - whoami: one-off identity lookup; reached via /hermes whoami on Slack.
+# Demoted when /loop claimed a native slot (loop is a recurring
+# interactive surface; whoami is a rare debug lookup) — without this
+# entry /loop tips the registry past the 50-cap and silently clamps
+# /platform, breaking Telegram parity.
+_SLACK_VIA_HERMES_ONLY = frozenset({"topup", "moa", "debug", "egress", "init", "version", "diff", "update", "heartbeat", "refine", "pause", "whoami"})
def _sanitize_slack_name(raw: str) -> str:
diff --git a/hermes_cli/config.py b/hermes_cli/config.py
index 2a85d38b05f..a5319c9170d 100644
--- a/hermes_cli/config.py
+++ b/hermes_cli/config.py
@@ -4942,6 +4942,7 @@ _OPEN_DICT_TOP_LEVEL_KEYS = frozenset({
"server_actions",
"secrets",
"goals",
+ "loops",
})
# Top-level keys whose sub-keys are partially schema-defined (e.g. on a
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py
index 8bc7f574034..af79d158a9f 100644
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@ -1846,6 +1846,24 @@ DEFAULT_CONFIG = {
"max_turns": 20,
},
+
+ # Loops — /loop recurring in-session wakeups (Claude Code parity).
+ # A loop re-runs a prompt (or slash command) on a cadence inside the
+ # live session. Fixed-interval mode fires on the user's clock;
+ # self-paced mode (no interval given) starts at the floor and backs
+ # off exponentially while the agent's replies stop changing.
+ "loops": {
+ # Smallest fixed interval accepted (seconds). Tighter cadences are
+ # raised to this floor — each tick is a full agent turn.
+ "min_interval_seconds": 30,
+ # Backstop tick budget: the loop auto-pauses after this many
+ # wakeups unless the user set --times. 0 = unlimited.
+ "max_ticks": 100,
+ # Self-paced cadence bounds (seconds).
+ "self_paced_floor_seconds": 60,
+ "self_paced_ceiling_seconds": 900,
+ },
+
# Mixture of Agents — named presets used by /moa. A preset is an execution
# mode around the main model, not a provider/model itself: references +
# aggregator synthesize private guidance before each main-model iteration.
diff --git a/hermes_cli/loops.py b/hermes_cli/loops.py
new file mode 100644
index 00000000000..f496907c2d0
--- /dev/null
+++ b/hermes_cli/loops.py
@@ -0,0 +1,970 @@
+"""Recurring in-session wakeups — the /loop command (Claude Code parity).
+
+``/loop [interval] <prompt>`` re-runs a prompt (or a slash command) on a
+recurring cadence INSIDE the current session. Each tick is a real agent
+turn: the wakeup prompt is injected through the exact same input path as
+a typed user message, so the agent always sees current state (latest CI
+result, newest queue depth, the file as it is now).
+
+Two cadence modes, mirroring Claude Code's ``/loop``:
+
+- **Fixed interval** — ``/loop 5m check the deploy`` fires every 5 minutes.
+- **Self-paced** — ``/loop keep refining the failing test until green``
+ (no interval token) lets the loop set its own rhythm: it starts fast and
+ backs off exponentially while the agent's replies stop changing, then
+ snaps back to the floor as soon as a reply differs. Zero extra LLM cost —
+ change detection is a local digest comparison.
+
+Stop conditions (any of):
+
+- 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.
+- ``--until <condition>`` — an evidence-based stop judged by the same
+ auxiliary judge that powers /goal (fail-open: a broken judge never
+ wedges the loop; the tick budget is the backstop).
+- ``/loop stop`` / ``/loop clear`` — user control.
+- ``loops.max_ticks`` config backstop (default 100, 0 = unlimited).
+
+Design notes / invariants (same contract as ``hermes_cli/goals.py``):
+
+- A wakeup is just a normal user-role message appended via the surface's
+ ordinary input path. No system-prompt mutation, no toolset swap —
+ prompt caching stays intact and role alternation is preserved.
+- Wakeups only fire while the session is IDLE. A real user message always
+ wins; the tick just re-arms and fires at the next idle boundary.
+- State is persisted in SessionDB's ``state_meta`` table keyed by
+ ``loop:<session_id>`` so ``/resume`` picks the loop back up.
+- /goal mixing: an active /goal takes priority. When the goal loop has a
+ continuation queued (or the goal judge is mid-flight), the /loop tick
+ defers to the next interval instead of racing a second synthetic turn.
+ Goal-continuation turns never count as loop ticks and vice versa.
+- This module has zero hard dependency on ``cli.HermesCLI``, the gateway
+ runner, or the TUI gateway — all three drive the same ``LoopManager``.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import logging
+import re
+import time
+from dataclasses import dataclass, field, asdict
+from typing import Any, Dict, List, Optional, Tuple
+
+logger = 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).
+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.
+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.
+DEFAULT_SELF_PACED_FLOOR_SECONDS = 60
+DEFAULT_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.
+LOOP_COMPLETE_MARKER = "LOOP_COMPLETE"
+
+# Matches the marker on its own line (possibly with surrounding whitespace
+# or trailing punctuation the model added despite instructions).
+_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
+)
+
+
+WAKEUP_PROMPT_TEMPLATE = (
+ "[/loop wakeup #{tick}{cadence}]\n"
+ "Recurring task: {prompt}\n\n"
+ "This is an automatic wakeup from the /loop the user set. Perform the "
+ "task now against the CURRENT state (re-check files, processes, or "
+ "services fresh — do not assume anything from earlier iterations still "
+ "holds). Report concisely what you found or did this iteration.\n"
+ "If the task is now complete, no longer applicable, or the thing you "
+ "were watching has finished, say so and end your reply with "
+ f"{LOOP_COMPLETE_MARKER} on its own line — that stops the loop."
+)
+
+WAKEUP_PROMPT_WITH_UNTIL_TEMPLATE = (
+ "[/loop wakeup #{tick}{cadence}]\n"
+ "Recurring task: {prompt}\n\n"
+ "Stop condition: {until}\n\n"
+ "This is an automatic wakeup from the /loop the user set. Perform the "
+ "task now against the CURRENT state (re-check files, processes, or "
+ "services fresh — do not assume anything from earlier iterations still "
+ "holds). Report concisely what you found or did this iteration, and "
+ "show concrete evidence of the stop condition's status.\n"
+ "If the stop condition is met, or the task is no longer applicable, say "
+ f"so and end your reply with {LOOP_COMPLETE_MARKER} on its own line — "
+ "that stops the loop."
+)
+
+
+# ──────────────────────────────────────────────────────────────────────
+# Interval parsing
+# ──────────────────────────────────────────────────────────────────────
+
+
+def parse_interval_token(token: str) -> Optional[int]:
+ """Parse a compact interval token (``30s``/``5m``/``2h``/``1h30m``).
+
+ Returns total seconds, or None when the token is not an interval.
+ A bare number is NOT an interval (too easy to collide with prompt
+ text like ``/loop 3 things to check``) — units are required.
+ """
+ if not token:
+ return None
+ m = _INTERVAL_TOKEN_RE.match(token.strip())
+ if not m:
+ return None
+ h, mnt, s = (int(g) if g else 0 for g in m.groups())
+ total = h * 3600 + mnt * 60 + s
+ return total if total > 0 else None
+
+
+def parse_loop_args(text: str) -> Dict[str, Any]:
+ """Parse the argument string of ``/loop [interval] <prompt> [flags]``.
+
+ Recognized shapes::
+
+ /loop 5m check the deploy status
+ /loop every 10m /babysit-prs
+ /loop keep fixing the failing test until the suite passes
+ /loop 2m poll CI --times 30
+ /loop 5m watch the queue --until queue depth reaches zero
+
+ 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).
+ """
+ raw = (text or "").strip()
+ result: Dict[str, Any] = {
+ "interval_seconds": None,
+ "prompt": "",
+ "times": 0,
+ "until": "",
+ "error": None,
+ }
+ if not raw:
+ 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).
+ times = 0
+ until = ""
+
+ m_times = re.search(r"\s--times\s+(\S+)", raw)
+ if m_times:
+ try:
+ times = int(m_times.group(1))
+ if times < 1:
+ raise ValueError
+ except ValueError:
+ result["error"] = f"--times expects a positive integer, got {m_times.group(1)!r}"
+ return result
+ raw = (raw[: m_times.start()] + raw[m_times.end():]).strip()
+
+ m_until = re.search(r"\s--until\s+(.+)$", raw, re.DOTALL)
+ if m_until:
+ until = m_until.group(1).strip()
+ raw = raw[: m_until.start()].strip()
+
+ # Leading "every" sugar: /loop every 5m <prompt>
+ tokens = raw.split(None, 1)
+ if tokens and tokens[0].lower() == "every" and len(tokens) > 1:
+ raw = tokens[1]
+ tokens = raw.split(None, 1)
+
+ interval: Optional[int] = None
+ if tokens:
+ maybe = parse_interval_token(tokens[0])
+ if maybe is not None:
+ interval = maybe
+ raw = tokens[1].strip() if len(tokens) > 1 else ""
+
+ if not raw:
+ result["error"] = "missing prompt (usage: /loop [interval] <prompt>)"
+ return result
+
+ result["interval_seconds"] = interval
+ result["prompt"] = raw
+ result["times"] = times
+ result["until"] = until
+ return result
+
+
+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)
+ m, s = divmod(rem, 60)
+ parts = []
+ if h:
+ parts.append(f"{h}h")
+ if m:
+ parts.append(f"{m}m")
+ if s or not parts:
+ parts.append(f"{s}s")
+ return "".join(parts)
+
+
+# ──────────────────────────────────────────────────────────────────────
+# Config
+# ──────────────────────────────────────────────────────────────────────
+
+
+def _loops_config() -> Dict[str, Any]:
+ """Read the ``loops:`` config section (cached load_config underneath)."""
+ try:
+ from hermes_cli.config import load_config
+
+ cfg = load_config() or {}
+ section = cfg.get("loops") or {}
+ return section if isinstance(section, dict) else {}
+ except Exception:
+ return {}
+
+
+def min_interval_seconds() -> int:
+ try:
+ value = int(_loops_config().get("min_interval_seconds", DEFAULT_MIN_INTERVAL_SECONDS))
+ return max(5, value)
+ except Exception:
+ return DEFAULT_MIN_INTERVAL_SECONDS
+
+
+def max_ticks_default() -> int:
+ try:
+ value = int(_loops_config().get("max_ticks", DEFAULT_MAX_TICKS))
+ return max(0, value)
+ except Exception:
+ return DEFAULT_MAX_TICKS
+
+
+def self_paced_floor_seconds() -> int:
+ try:
+ value = int(_loops_config().get("self_paced_floor_seconds", DEFAULT_SELF_PACED_FLOOR_SECONDS))
+ return max(10, value)
+ except Exception:
+ return DEFAULT_SELF_PACED_FLOOR_SECONDS
+
+
+def self_paced_ceiling_seconds() -> int:
+ floor = self_paced_floor_seconds()
+ try:
+ value = int(_loops_config().get("self_paced_ceiling_seconds", DEFAULT_SELF_PACED_CEILING_SECONDS))
+ return max(floor, value)
+ except Exception:
+ return max(floor, DEFAULT_SELF_PACED_CEILING_SECONDS)
+
+
+# ──────────────────────────────────────────────────────────────────────
+# Dataclass
+# ──────────────────────────────────────────────────────────────────────
+
+
+@dataclass
+class LoopState:
+ """Serializable /loop state stored per session."""
+
+ prompt: str
+ status: str = "active" # active | paused | done | cleared
+ mode: str = "interval" # interval | self_paced
+ interval_seconds: float = 0.0 # fixed cadence (mode == "interval")
+ current_delay: float = 0.0 # live cadence (self-paced backoff)
+ times: int = 0 # user cap (--times N); 0 = none
+ until: str = "" # judged stop condition; "" = none
+ max_ticks: int = DEFAULT_MAX_TICKS # config backstop; 0 = unlimited
+ ticks_fired: int = 0
+ created_at: float = 0.0
+ last_fired_at: float = 0.0
+ next_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.
+ awaiting_response: bool = False
+ # Self-paced change detection: digest of the previous wakeup's reply.
+ last_response_digest: str = ""
+ paused_reason: Optional[str] = None
+ last_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.
+ route: Dict[str, str] = field(default_factory=dict)
+
+ def to_json(self) -> str:
+ return json.dumps(asdict(self), ensure_ascii=False)
+
+ @classmethod
+ def from_json(cls, raw: str) -> "LoopState":
+ data = json.loads(raw)
+ route = data.get("route")
+ return cls(
+ prompt=data.get("prompt", ""),
+ status=data.get("status", "active"),
+ mode=data.get("mode", "interval"),
+ interval_seconds=float(data.get("interval_seconds", 0.0) or 0.0),
+ current_delay=float(data.get("current_delay", 0.0) or 0.0),
+ times=int(data.get("times", 0) or 0),
+ until=str(data.get("until", "") or ""),
+ max_ticks=int(data.get("max_ticks", DEFAULT_MAX_TICKS) or 0),
+ ticks_fired=int(data.get("ticks_fired", 0) or 0),
+ created_at=float(data.get("created_at", 0.0) or 0.0),
+ last_fired_at=float(data.get("last_fired_at", 0.0) or 0.0),
+ next_due_at=float(data.get("next_due_at", 0.0) or 0.0),
+ awaiting_response=bool(data.get("awaiting_response", False)),
+ last_response_digest=str(data.get("last_response_digest", "") or ""),
+ paused_reason=data.get("paused_reason"),
+ last_stop_reason=data.get("last_stop_reason"),
+ route=route if isinstance(route, dict) else {},
+ )
+
+ # --- helpers -------------------------------------------------------
+
+ def cadence_label(self) -> str:
+ if self.mode == "self_paced":
+ live = f", currently {format_interval(self.current_delay)}" if self.current_delay else ""
+ return f"self-paced{live}"
+ return f"every {format_interval(self.interval_seconds)}"
+
+ def remaining_label(self) -> str:
+ 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)}"
+
+
+# ──────────────────────────────────────────────────────────────────────
+# Persistence (SessionDB state_meta)
+# ──────────────────────────────────────────────────────────────────────
+
+_META_PREFIX = "loop:"
+
+
+def _meta_key(session_id: str) -> str:
+ return f"{_META_PREFIX}{session_id}"
+
+
+_DB_CACHE: Dict[str, Any] = {}
+
+
+def _get_session_db() -> Optional[Any]:
+ """One SessionDB per HERMES_HOME (same pattern as goals._get_session_db)."""
+ try:
+ from hermes_constants import get_hermes_home
+ from hermes_state import SessionDB
+
+ home = str(get_hermes_home())
+ except Exception as exc: # pragma: no cover
+ logger.debug("LoopManager: SessionDB bootstrap failed (%s)", exc)
+ return None
+
+ cached = _DB_CACHE.get(home)
+ if cached is not None:
+ return cached
+ try:
+ db = SessionDB()
+ except Exception as exc: # pragma: no cover
+ logger.debug("LoopManager: SessionDB() raised (%s)", exc)
+ return None
+ _DB_CACHE[home] = db
+ return db
+
+
+def load_loop(session_id: str) -> Optional[LoopState]:
+ """Load the loop for a session, or None if none exists."""
+ if not session_id:
+ return None
+ db = _get_session_db()
+ if db is None:
+ return None
+ try:
+ raw = db.get_meta(_meta_key(session_id))
+ except Exception as exc:
+ logger.debug("LoopManager: get_meta failed: %s", exc)
+ return None
+ if not raw:
+ return None
+ try:
+ return LoopState.from_json(raw)
+ except Exception as exc:
+ logger.warning("LoopManager: could not parse stored loop for %s: %s", session_id, exc)
+ return None
+
+
+def save_loop(session_id: str, state: LoopState) -> None:
+ """Persist a loop to SessionDB. No-op if DB unavailable."""
+ if not session_id:
+ return
+ db = _get_session_db()
+ if db is None:
+ return
+ try:
+ db.set_meta(_meta_key(session_id), state.to_json())
+ except Exception as exc:
+ logger.debug("LoopManager: set_meta failed: %s", exc)
+
+
+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)
+
+
+def list_active_loops() -> List[Tuple[str, LoopState]]:
+ """Return ``[(session_id, LoopState), ...]`` for every ACTIVE loop.
+
+ Used by the gateway's idle wakeup watcher, which has no per-session
+ scheduler and instead scans for due loops on a coarse tick. Best-effort:
+ any DB error yields ``[]``.
+ """
+ db = _get_session_db()
+ if db is None:
+ return []
+ try:
+ rows = db.list_meta_prefix(_META_PREFIX)
+ except Exception as exc:
+ logger.debug("LoopManager: list_meta_prefix failed: %s", exc)
+ return []
+ out: List[Tuple[str, LoopState]] = []
+ for key, raw in rows:
+ session_id = key[len(_META_PREFIX):]
+ if not session_id or not raw:
+ continue
+ try:
+ state = LoopState.from_json(raw)
+ except Exception:
+ continue
+ if state.status == "active":
+ out.append((session_id, state))
+ return out
+
+
+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.
+
+ 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). Copies the loop onto the new session
+ and archives the old row as ``cleared`` so exactly one active loop row
+ exists per logical conversation. Best-effort and never raises.
+ """
+ if not old_session_id or not new_session_id or old_session_id == new_session_id:
+ return False
+ try:
+ 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:
+ return False
+ save_loop(new_session_id, state)
+ clear_loop(old_session_id)
+ logger.debug(
+ "LoopManager: migrated loop %s -> %s (%s)",
+ old_session_id, new_session_id, reason or "rotation",
+ )
+ return True
+ except Exception as exc: # pragma: no cover - defensive
+ logger.debug("LoopManager: loop migration failed: %s", exc)
+ return False
+
+
+# ──────────────────────────────────────────────────────────────────────
+# Response evaluation helpers
+# ──────────────────────────────────────────────────────────────────────
+
+
+def response_signals_complete(response: str) -> bool:
+ """True when the agent ended its reply with the LOOP_COMPLETE marker."""
+ if not response:
+ return False
+ return _LOOP_COMPLETE_RE.search(response) is not None
+
+
+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.
+ """
+ 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)
+ text = re.sub(r"\s+", " ", text)
+ return hashlib.sha256(text.encode("utf-8", "replace")).hexdigest()
+
+
+# ──────────────────────────────────────────────────────────────────────
+# LoopManager — the orchestration surface CLI + gateway + TUI talk to
+# ──────────────────────────────────────────────────────────────────────
+
+
+class LoopManager:
+ """Per-session /loop state + tick decisions.
+
+ Drivers (CLI process_loop, gateway wakeup watcher, TUI ticker) call:
+
+ - ``set(...)`` / ``pause()`` / ``resume()`` / ``clear()`` — user controls.
+ - ``is_due()`` — should a wakeup fire now? (cheap, in-memory)
+ - ``fire_tick()`` — claim the tick; returns the wakeup message to inject.
+ - ``complete_tick(last_response)`` — evaluate the finished wakeup turn:
+ detect LOOP_COMPLETE, judge --until, apply --times / max_ticks caps,
+ schedule the next tick (with self-paced backoff when applicable).
+ - ``status_line()`` — printable one-liner.
+ """
+
+ def __init__(self, session_id: str):
+ self.session_id = session_id
+ self._state: Optional[LoopState] = load_loop(session_id)
+
+ # --- introspection ------------------------------------------------
+
+ @property
+ def state(self) -> Optional[LoopState]:
+ return self._state
+
+ def refresh(self) -> None:
+ """Re-read state from the DB (cross-process safety for the gateway)."""
+ self._state = load_loop(self.session_id)
+
+ def is_active(self) -> bool:
+ return self._state is not None and self._state.status == "active"
+
+ def has_loop(self) -> bool:
+ return self._state is not None and self._state.status in {"active", "paused"}
+
+ def status_line(self) -> str:
+ s = self._state
+ if s is None or s.status == "cleared":
+ return "No loop set. Start one with /loop [interval] <prompt>."
+ fired = f"{s.ticks_fired} tick{'s' if s.ticks_fired != 1 else ''}"
+ caps = []
+ if s.times:
+ caps.append(f"{s.ticks_fired}/{s.times} runs")
+ elif s.max_ticks:
+ caps.append(f"{s.ticks_fired}/{s.max_ticks} budget")
+ else:
+ caps.append(fired)
+ if s.until:
+ caps.append(f"until: {s.until}")
+ meta = f"{s.cadence_label()}, {', '.join(caps)}"
+ if s.status == "active":
+ remaining = s.remaining_label()
+ tail = f", {remaining}" if remaining else ""
+ if s.awaiting_response:
+ tail = ", wakeup running"
+ return f"↻ Loop (active, {meta}{tail}): {s.prompt}"
+ if s.status == "paused":
+ extra = f" — {s.paused_reason}" if s.paused_reason else ""
+ return f"⏸ Loop (paused, {meta}{extra}): {s.prompt}"
+ if s.status == "done":
+ extra = f" — {s.last_stop_reason}" if s.last_stop_reason else ""
+ return f"✓ Loop finished ({fired}{extra}): {s.prompt}"
+ return f"Loop ({s.status}, {meta}): {s.prompt}"
+
+ # --- mutation -----------------------------------------------------
+
+ def set(
+ self,
+ prompt: str,
+ *,
+ interval_seconds: Optional[int] = None,
+ times: int = 0,
+ until: str = "",
+ route: Optional[Dict[str, str]] = None,
+ ) -> LoopState:
+ """Start a new loop (replaces any existing one for the session)."""
+ prompt = (prompt or "").strip()
+ if not prompt:
+ raise ValueError("loop prompt is empty")
+
+ now = time.time()
+ if interval_seconds is not None:
+ interval = max(int(interval_seconds), min_interval_seconds())
+ state = LoopState(
+ prompt=prompt,
+ mode="interval",
+ interval_seconds=float(interval),
+ current_delay=float(interval),
+ next_due_at=now + interval,
+ )
+ else:
+ floor = self_paced_floor_seconds()
+ state = LoopState(
+ prompt=prompt,
+ mode="self_paced",
+ interval_seconds=0.0,
+ current_delay=float(floor),
+ next_due_at=now + floor,
+ )
+ state.times = max(0, int(times or 0))
+ state.until = (until or "").strip()
+ state.max_ticks = max_ticks_default()
+ state.created_at = now
+ state.route = dict(route or {})
+ self._state = state
+ save_loop(self.session_id, state)
+ return state
+
+ def pause(self, reason: str = "user-paused") -> Optional[LoopState]:
+ if not self._state or self._state.status not in {"active", "paused"}:
+ return None
+ self._state.status = "paused"
+ self._state.paused_reason = reason
+ self._state.awaiting_response = False
+ save_loop(self.session_id, self._state)
+ return self._state
+
+ def resume(self) -> Optional[LoopState]:
+ if not self._state or self._state.status == "cleared":
+ return None
+ self._state.status = "active"
+ self._state.paused_reason = None
+ self._state.awaiting_response = False
+ # Re-arm relative to now so a long pause doesn't fire instantly N times.
+ delay = self._state.current_delay or self._state.interval_seconds or self_paced_floor_seconds()
+ self._state.next_due_at = time.time() + min(delay, 5.0)
+ save_loop(self.session_id, self._state)
+ return self._state
+
+ def clear(self) -> bool:
+ if self._state is None or self._state.status == "cleared":
+ return False
+ self._state.status = "cleared"
+ save_loop(self.session_id, self._state)
+ self._state = None
+ return True
+
+ def mark_done(self, reason: str) -> None:
+ if not self._state:
+ return
+ self._state.status = "done"
+ self._state.last_stop_reason = reason
+ self._state.awaiting_response = False
+ save_loop(self.session_id, self._state)
+
+ # --- 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
+ if s is None or s.status != "active" or s.awaiting_response:
+ return False
+ return (now if now is not None else time.time()) >= s.next_due_at
+
+ def fire_tick(self) -> Optional[str]:
+ """Claim a due tick. Returns the message to inject, or None.
+
+ The returned text is either the wakeup-framed prompt or — when the
+ loop's prompt is itself a slash command (``/loop 10m /recap``) —
+ the raw command so the surface's normal slash dispatch handles it.
+ Marks ``awaiting_response`` so the tick can't double-fire while its
+ turn runs; drivers MUST follow up with ``complete_tick`` (or
+ ``abandon_tick`` on injection failure).
+ """
+ s = self._state
+ if s is None or not self.is_due():
+ return None
+ s.ticks_fired += 1
+ s.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.
+ delay = s.current_delay or s.interval_seconds or self_paced_floor_seconds()
+ s.next_due_at = s.last_fired_at + delay
+ save_loop(self.session_id, s)
+
+ if s.prompt.lstrip().startswith("/"):
+ return s.prompt.strip()
+ cadence = f", {s.cadence_label()}" if s.mode == "interval" else ", self-paced"
+ template = WAKEUP_PROMPT_WITH_UNTIL_TEMPLATE if s.until else WAKEUP_PROMPT_TEMPLATE
+ return template.format(tick=s.ticks_fired, cadence=cadence, prompt=s.prompt, until=s.until)
+
+ def abandon_tick(self) -> None:
+ """Roll back a fired tick whose injection failed (nothing ran)."""
+ s = self._state
+ if s is None or not s.awaiting_response:
+ return
+ s.awaiting_response = False
+ s.ticks_fired = max(0, s.ticks_fired - 1)
+ save_loop(self.session_id, s)
+
+ def complete_tick(self, last_response: str) -> Dict[str, Any]:
+ """Evaluate the finished wakeup turn and schedule what's next.
+
+ Returns a decision dict::
+
+ {"status": "active|done|paused", "stopped": bool,
+ "reason": str, "message": str}
+
+ ``message`` is a user-visible one-liner ("" when nothing worth
+ saying — the common still-looping case stays quiet).
+ """
+ s = self._state
+ if s is None or not s.awaiting_response:
+ return {"status": s.status if s else None, "stopped": False, "reason": "no tick in flight", "message": ""}
+ s.awaiting_response = False
+ now = time.time()
+
+ # 1. Agent self-stop marker.
+ if response_signals_complete(last_response):
+ s.status = "done"
+ s.last_stop_reason = "agent signaled the task is complete"
+ save_loop(self.session_id, s)
+ return {
+ "status": "done",
+ "stopped": True,
+ "reason": s.last_stop_reason,
+ "message": f"✓ Loop finished after {s.ticks_fired} tick{'s' if s.ticks_fired != 1 else ''} — task complete.",
+ }
+
+ # 2. Evidence-based --until judge (reuses the /goal judge; fail-open).
+ if s.until and (last_response or "").strip():
+ try:
+ from hermes_cli.goals import judge_goal
+
+ verdict, reason, _pf, _wait, _tf = judge_goal(s.until, last_response)
+ except Exception as exc:
+ verdict, reason = "continue", f"judge unavailable: {type(exc).__name__}"
+ if verdict == "done":
+ s.status = "done"
+ s.last_stop_reason = f"stop condition met: {reason}"
+ save_loop(self.session_id, s)
+ return {
+ "status": "done",
+ "stopped": True,
+ "reason": s.last_stop_reason,
+ "message": f"✓ Loop finished after {s.ticks_fired} tick{'s' if s.ticks_fired != 1 else ''} — {reason}",
+ }
+
+ # 3. --times user cap.
+ if s.times and s.ticks_fired >= s.times:
+ s.status = "done"
+ s.last_stop_reason = f"completed the requested {s.times} runs"
+ save_loop(self.session_id, s)
+ return {
+ "status": "done",
+ "stopped": True,
+ "reason": s.last_stop_reason,
+ "message": f"✓ Loop finished — ran {s.times}/{s.times} times.",
+ }
+
+ # 4. Config backstop budget → pause (recoverable), not done.
+ if s.max_ticks and s.ticks_fired >= s.max_ticks:
+ s.status = "paused"
+ s.paused_reason = f"tick budget exhausted ({s.ticks_fired}/{s.max_ticks})"
+ save_loop(self.session_id, s)
+ return {
+ "status": "paused",
+ "stopped": True,
+ "reason": s.paused_reason,
+ "message": (
+ f"⏸ Loop paused — {s.ticks_fired}/{s.max_ticks} ticks used "
+ "(loops.max_ticks). /loop resume to keep going, /loop stop to end it."
+ ),
+ }
+
+ # 5. Still looping — schedule the next tick from turn end.
+ 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)
+ else:
+ s.current_delay = float(floor)
+ s.last_response_digest = digest
+ else:
+ s.current_delay = s.interval_seconds
+ s.next_due_at = now + s.current_delay
+ save_loop(self.session_id, s)
+ 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.
+
+ Both features inject synthetic continuation turns at idle boundaries.
+ When a goal is actively driving the session (status ``active`` and not
+ parked on a wait barrier), its judge-driven continuations own the idle
+ boundary — firing a loop wakeup in between would interleave two
+ synthetic conversations and burn the goal's turn budget on loop chatter.
+ A goal that is parked (waiting on a pid/session/deadline), paused, or
+ done does NOT block the loop.
+ """
+ try:
+ from hermes_cli.goals import GoalManager
+
+ mgr = GoalManager(session_id=session_id)
+ if not mgr.is_active():
+ return False
+ # Parked goal → the loop may use the idle time.
+ return not mgr.is_waiting()
+ except Exception:
+ return False
+
+
+# ──────────────────────────────────────────────────────────────────────
+# Shared slash-command dispatch (CLI + gateway + TUI use the same logic)
+# ──────────────────────────────────────────────────────────────────────
+
+
+def dispatch_loop_command(
+ mgr: "LoopManager",
+ args: str,
+ *,
+ route: Optional[Dict[str, str]] = None,
+) -> Dict[str, Any]:
+ """Surface-agnostic handler for ``/loop <args>``.
+
+ 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.
+ """
+ arg = (args or "").strip()
+ lower = arg.lower()
+
+ if not arg or lower == "status":
+ return {"output": mgr.status_line(), "created": False}
+
+ if lower == "pause":
+ state = mgr.pause(reason="user-paused")
+ if state is None:
+ return {"output": "No loop set.", "created": False}
+ return {"output": f"⏸ Loop paused: {state.prompt}\nUse /loop resume to continue.", "created": False}
+
+ if lower == "resume":
+ state = mgr.resume()
+ if state is None:
+ return {"output": "No loop to resume.", "created": False}
+ return {
+ "output": f"▶ Loop resumed ({state.cadence_label()}): {state.prompt}",
+ "created": False,
+ }
+
+ if lower in {"stop", "clear", "cancel"}:
+ had = mgr.clear()
+ return {"output": "✓ Loop stopped." if had else "No active loop.", "created": False}
+
+ if lower in {"help", "--help", "-h"}:
+ return {
+ "output": (
+ "Usage: /loop [interval] <prompt> [--times N] [--until <condition>]\n"
+ " /loop 5m check the deploy status — fixed cadence\n"
+ " /loop every 10m /recap — loop a slash command\n"
+ " /loop keep fixing tests until green — self-paced (backs off while output is unchanged)\n"
+ " /loop 2m poll CI --times 30 — stop after 30 runs\n"
+ " /loop 5m watch the queue --until queue is empty\n"
+ "Controls: /loop status · /loop pause · /loop resume · /loop stop\n"
+ "The loop also stops itself when the agent replies with "
+ f"{LOOP_COMPLETE_MARKER}."
+ ),
+ "created": False,
+ }
+
+ parsed = parse_loop_args(arg)
+ if parsed["error"]:
+ if parsed["error"] == "empty":
+ return {"output": "Usage: /loop [interval] <prompt> — see /loop help.", "created": False}
+ return {"output": f"/loop: {parsed['error']}", "created": False}
+
+ replacing = mgr.has_loop()
+ try:
+ state = mgr.set(
+ parsed["prompt"],
+ interval_seconds=parsed["interval_seconds"],
+ times=parsed["times"],
+ until=parsed["until"],
+ route=route,
+ )
+ except ValueError as exc:
+ return {"output": f"/loop: {exc}", "created": False}
+
+ lines = [f"↻ Loop set ({state.cadence_label()}): {state.prompt}"]
+ if parsed["interval_seconds"] is not None and parsed["interval_seconds"] < state.interval_seconds:
+ lines.append(
+ f"(interval raised to the {format_interval(state.interval_seconds)} minimum — "
+ "loops.min_interval_seconds)"
+ )
+ if state.mode == "self_paced":
+ lines.append(
+ f"Self-paced: first check in {format_interval(state.current_delay)}; "
+ f"backs off up to {format_interval(self_paced_ceiling_seconds())} while nothing changes."
+ )
+ if state.times:
+ lines.append(f"Runs {state.times} time{'s' if state.times != 1 else ''}, then stops.")
+ if state.until:
+ lines.append(f"Stops when: {state.until}")
+ if not state.times and state.max_ticks:
+ lines.append(f"Backstop budget: {state.max_ticks} ticks (loops.max_ticks; 0 = unlimited).")
+ lines.append(f"First wakeup {state.remaining_label()}. Controls: /loop status · pause · resume · stop.")
+ if replacing:
+ lines.insert(1, "(replaced the previous loop for this session)")
+ return {"output": "\n".join(lines), "created": True}
+
+
+__all__ = [
+ "LoopState",
+ "LoopManager",
+ "parse_loop_args",
+ "parse_interval_token",
+ "format_interval",
+ "response_signals_complete",
+ "goal_blocks_loop_tick",
+ "load_loop",
+ "save_loop",
+ "clear_loop",
+ "list_active_loops",
+ "migrate_loop_to_session",
+ "dispatch_loop_command",
+ "LOOP_COMPLETE_MARKER",
+ "WAKEUP_PROMPT_TEMPLATE",
+ "WAKEUP_PROMPT_WITH_UNTIL_TEMPLATE",
+ "DEFAULT_MIN_INTERVAL_SECONDS",
+ "DEFAULT_MAX_TICKS",
+]
diff --git a/hermes_state.py b/hermes_state.py
index 1f44cfc184f..1b4fad10d01 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -10790,6 +10790,24 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
return self._execute_write(_do)
+ def list_meta_prefix(self, prefix: str) -> List[Tuple[str, str]]:
+ """Return ``[(key, value), ...]`` for state_meta keys with ``prefix``.
+
+ Used by feature stores that persist one row per session under a
+ namespaced key (e.g. ``loop:<session_id>``) and need to enumerate
+ them across sessions (the gateway's idle /loop wakeup watcher).
+ ``prefix`` is matched literally — LIKE wildcards in it are escaped.
+ """
+ if not prefix:
+ return []
+ escaped = prefix.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
+ with self._lock:
+ rows = self._conn.execute(
+ "SELECT key, value FROM state_meta WHERE key LIKE ? ESCAPE '\\'",
+ (escaped + "%",),
+ ).fetchall()
+ return [(row[0], row[1]) for row in rows]
+
def apply_telegram_topic_migration(self) -> None:
"""Create Telegram DM topic-mode tables on explicit /topic opt-in.
diff --git a/tests/gateway/test_loop_command.py b/tests/gateway/test_loop_command.py
new file mode 100644
index 00000000000..c11876a9954
--- /dev/null
+++ b/tests/gateway/test_loop_command.py
@@ -0,0 +1,139 @@
+"""Gateway /loop command tests — dispatch, routing capture, mid-run guard."""
+
+import time
+
+import pytest
+
+from gateway.config import GatewayConfig, Platform, PlatformConfig
+from gateway.platforms.base import MessageEvent, MessageType
+from gateway.run import GatewayRunner
+from gateway.session import SessionSource
+from hermes_cli import loops
+
+
+class _FakeSessionEntry:
+ session_id = "sid-gateway-loop"
+
+
+class _FakeSessionStore:
+ def __init__(self):
+ self.entry = _FakeSessionEntry()
+
+ def get_or_create_session(self, source):
+ return self.entry
+
+ def _generate_session_key(self, source):
+ return "agent:main:discord:channel:loop-test"
+
+
+def loop_env(tmp_path, monkeypatch):
+ home = tmp_path / ".hermes"
+ home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ loops._DB_CACHE.clear()
+ yield home
+ loops._DB_CACHE.clear()
+
+
+def _make_runner():
+ runner = object.__new__(GatewayRunner)
+ runner.config = GatewayConfig(
+ platforms={Platform.DISCORD: PlatformConfig(enabled=True, token="token")}
+ )
+ runner.session_store = _FakeSessionStore()
+ runner.adapters = {}
+ runner._queued_events = {}
+ return runner
+
+
+def _make_event(text: str) -> MessageEvent:
+ return MessageEvent(
+ text=text,
+ message_type=MessageType.TEXT,
+ source=SessionSource(
+ platform=Platform.DISCORD,
+ chat_id="chat-loop",
+ chat_type="channel",
+ thread_id="thread-9",
+ user_id="user-loop",
+ ),
+ message_id="msg-loop",
+ )
+
+
+async def test_gateway_loop_create_captures_route(loop_env):
+ runner = _make_runner()
+ response = await GatewayRunner._handle_loop_command(runner, _make_event("/loop 5m check the deploy"))
+ assert "Loop set" in response
+ assert "every 5m" in response
+
+ state = loops.load_loop("sid-gateway-loop")
+ assert state is not None
+ assert state.prompt == "check the deploy"
+ assert state.route["platform"] == "discord"
+ assert state.route["chat_id"] == "chat-loop"
+ assert state.route["thread_id"] == "thread-9"
+
+
+async def test_gateway_loop_status_pause_stop(loop_env):
+ runner = _make_runner()
+ await GatewayRunner._handle_loop_command(runner, _make_event("/loop 5m poll CI"))
+
+ status = await GatewayRunner._handle_loop_command(runner, _make_event("/loop status"))
+ assert "poll CI" in status
+
+ paused = await GatewayRunner._handle_loop_command(runner, _make_event("/loop pause"))
+ assert "paused" in paused.lower()
+
+ stopped = await GatewayRunner._handle_loop_command(runner, _make_event("/loop stop"))
+ assert "stopped" in stopped.lower()
+
+
+async def test_gateway_loop_goal_note_when_goal_active(loop_env):
+ from hermes_cli.goals import GoalManager
+
+ GoalManager(session_id="sid-gateway-loop").set("finish the migration")
+ runner = _make_runner()
+ response = await GatewayRunner._handle_loop_command(runner, _make_event("/loop 5m poll CI"))
+ assert "active /goal" in response
+
+
+async def test_post_turn_loop_completion_completes_inflight_tick(loop_env):
+ runner = _make_runner()
+ await GatewayRunner._handle_loop_command(runner, _make_event("/loop 5m poll CI"))
+
+ mgr = loops.LoopManager(session_id="sid-gateway-loop")
+ mgr.state.next_due_at = time.time() - 1
+ assert mgr.fire_tick() is not None
+
+ entry = _FakeSessionEntry()
+ await GatewayRunner._post_turn_loop_completion(
+ runner,
+ session_entry=entry,
+ source=None,
+ final_response="CI is done.\nLOOP_COMPLETE",
+ )
+ reloaded = loops.load_loop("sid-gateway-loop")
+ assert reloaded.status == "done"
+
+
+async def test_post_turn_loop_completion_noop_without_inflight_tick(loop_env):
+ runner = _make_runner()
+ await GatewayRunner._handle_loop_command(runner, _make_event("/loop 5m poll CI"))
+ entry = _FakeSessionEntry()
+ # No tick fired — the ordinary user turn must not consume loop state.
+ await GatewayRunner._post_turn_loop_completion(
+ runner,
+ session_entry=entry,
+ source=None,
+ final_response="regular reply LOOP_COMPLETE",
+ )
+ reloaded = loops.load_loop("sid-gateway-loop")
+ assert reloaded.status == "active"
+ assert reloaded.ticks_fired == 0
diff --git a/tests/hermes_cli/test_loops.py b/tests/hermes_cli/test_loops.py
new file mode 100644
index 00000000000..dba5ed39a40
--- /dev/null
+++ b/tests/hermes_cli/test_loops.py
@@ -0,0 +1,670 @@
+"""Tests for hermes_cli/loops.py — /loop recurring in-session wakeups."""
+
+from __future__ import annotations
+
+import time
+from unittest.mock import patch
+
+import pytest
+
+
+# ──────────────────────────────────────────────────────────────────────
+# Fixtures
+# ──────────────────────────────────────────────────────────────────────
+
+
+def hermes_home(tmp_path, monkeypatch):
+ """Isolated HERMES_HOME so SessionDB.state_meta writes don't clobber the real one."""
+ from pathlib import Path
+
+ home = tmp_path / ".hermes"
+ home.mkdir()
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(home))
+
+ from hermes_cli import loops
+
+ loops._DB_CACHE.clear()
+ yield home
+ loops._DB_CACHE.clear()
+
+
+# ──────────────────────────────────────────────────────────────────────
+# Interval / argument parsing
+# ──────────────────────────────────────────────────────────────────────
+
+
+class TestParseIntervalToken:
+ def test_minutes(self):
+ from hermes_cli.loops import parse_interval_token
+
+ assert parse_interval_token("5m") == 300
+
+ def test_seconds(self):
+ from hermes_cli.loops import parse_interval_token
+
+ assert parse_interval_token("30s") == 30
+
+ def test_hours(self):
+ from hermes_cli.loops import parse_interval_token
+
+ assert parse_interval_token("2h") == 7200
+
+ def test_compound(self):
+ from hermes_cli.loops import parse_interval_token
+
+ assert parse_interval_token("1h30m") == 5400
+
+ def test_case_insensitive(self):
+ from hermes_cli.loops import parse_interval_token
+
+ assert parse_interval_token("5M") == 300
+
+ def test_bare_number_is_not_interval(self):
+ from hermes_cli.loops import parse_interval_token
+
+ assert parse_interval_token("3") is None
+
+ def test_prose_is_not_interval(self):
+ from hermes_cli.loops import parse_interval_token
+
+ assert parse_interval_token("check") is None
+ assert parse_interval_token("") is None
+ assert parse_interval_token("5x") is None
+
+ def test_zero_rejected(self):
+ from hermes_cli.loops import parse_interval_token
+
+ assert parse_interval_token("0m") is None
+ assert parse_interval_token("0s") is None
+
+
+class TestParseLoopArgs:
+ def test_fixed_interval(self):
+ from hermes_cli.loops import parse_loop_args
+
+ p = parse_loop_args("5m check the deploy status")
+ assert p["interval_seconds"] == 300
+ assert p["prompt"] == "check the deploy status"
+ assert p["error"] is None
+
+ def test_every_sugar(self):
+ from hermes_cli.loops import parse_loop_args
+
+ p = parse_loop_args("every 10m /recap")
+ assert p["interval_seconds"] == 600
+ assert p["prompt"] == "/recap"
+
+ def test_self_paced(self):
+ from hermes_cli.loops import parse_loop_args
+
+ p = parse_loop_args("keep refining the failing test until the suite passes")
+ assert p["interval_seconds"] is None
+ assert p["prompt"].startswith("keep refining")
+
+ def test_times_flag(self):
+ from hermes_cli.loops import parse_loop_args
+
+ p = parse_loop_args("2m poll CI --times 30")
+ assert p["interval_seconds"] == 120
+ assert p["prompt"] == "poll CI"
+ assert p["times"] == 30
+
+ def test_until_flag(self):
+ from hermes_cli.loops import parse_loop_args
+
+ p = parse_loop_args("5m watch the queue --until queue depth reaches zero")
+ assert p["interval_seconds"] == 300
+ assert p["prompt"] == "watch the queue"
+ assert p["until"] == "queue depth reaches zero"
+
+ def test_until_and_times_together(self):
+ from hermes_cli.loops import parse_loop_args
+
+ p = parse_loop_args("2m poll --times 5 --until it is green")
+ assert p["times"] == 5
+ assert p["until"] == "it is green"
+ assert p["prompt"] == "poll"
+
+ def test_bad_times(self):
+ from hermes_cli.loops import parse_loop_args
+
+ p = parse_loop_args("2m poll --times zero")
+ assert p["error"] is not None
+
+ def test_interval_only_is_error(self):
+ from hermes_cli.loops import parse_loop_args
+
+ p = parse_loop_args("5m")
+ assert p["error"] is not None
+
+ def test_empty(self):
+ from hermes_cli.loops import parse_loop_args
+
+ assert parse_loop_args("")["error"] == "empty"
+
+ def test_prompt_with_leading_number_not_eaten(self):
+ from hermes_cli.loops import parse_loop_args
+
+ p = parse_loop_args("3 things to verify in the repo")
+ assert p["interval_seconds"] is None
+ assert p["prompt"].startswith("3 things")
+
+
+class TestFormatInterval:
+ def test_render(self):
+ from hermes_cli.loops import format_interval
+
+ assert format_interval(30) == "30s"
+ assert format_interval(300) == "5m"
+ assert format_interval(5400) == "1h30m"
+ assert format_interval(90) == "1m30s"
+ assert format_interval(0) == "0s"
+
+
+# ──────────────────────────────────────────────────────────────────────
+# LOOP_COMPLETE marker
+# ──────────────────────────────────────────────────────────────────────
+
+
+class TestResponseSignalsComplete:
+ def test_marker_on_own_line(self):
+ from hermes_cli.loops import response_signals_complete
+
+ assert response_signals_complete("Deploy is live.\nLOOP_COMPLETE") is True
+
+ def test_marker_with_trailing_period(self):
+ from hermes_cli.loops import response_signals_complete
+
+ assert response_signals_complete("done\nLOOP_COMPLETE.") is True
+
+ def test_marker_mid_sentence_does_not_count(self):
+ from hermes_cli.loops import response_signals_complete
+
+ assert response_signals_complete("I will emit LOOP_COMPLETE when finished") is False
+
+ def test_no_marker(self):
+ from hermes_cli.loops import response_signals_complete
+
+ assert response_signals_complete("still building") is False
+ assert response_signals_complete("") is False
+
+
+# ──────────────────────────────────────────────────────────────────────
+# LoopState round-trip
+# ──────────────────────────────────────────────────────────────────────
+
+
+class TestLoopStateSerde:
+ def test_round_trip(self):
+ from hermes_cli.loops import LoopState
+
+ s = LoopState(
+ prompt="check CI",
+ mode="interval",
+ interval_seconds=300.0,
+ current_delay=300.0,
+ times=5,
+ until="ci is green",
+ ticks_fired=2,
+ route={"platform": "telegram", "chat_id": "123"},
+ )
+ s2 = LoopState.from_json(s.to_json())
+ assert s2.prompt == "check CI"
+ assert s2.interval_seconds == 300.0
+ assert s2.times == 5
+ assert s2.until == "ci is green"
+ assert s2.ticks_fired == 2
+ assert s2.route == {"platform": "telegram", "chat_id": "123"}
+
+ def test_old_row_missing_fields(self):
+ from hermes_cli.loops import LoopState
+
+ s = LoopState.from_json('{"prompt": "p"}')
+ assert s.prompt == "p"
+ assert s.status == "active"
+ assert s.route == {}
+
+
+# ──────────────────────────────────────────────────────────────────────
+# Persistence
+# ──────────────────────────────────────────────────────────────────────
+
+
+class TestPersistence:
+ def test_save_load_clear(self, hermes_home):
+ from hermes_cli.loops import LoopManager, load_loop
+
+ mgr = LoopManager(session_id="sess-1")
+ mgr.set("check the deploy", interval_seconds=300)
+ loaded = load_loop("sess-1")
+ assert loaded is not None
+ assert loaded.prompt == "check the deploy"
+ assert loaded.status == "active"
+
+ assert mgr.clear() is True
+ cleared = load_loop("sess-1")
+ assert cleared is not None and cleared.status == "cleared"
+
+ def test_list_active_loops(self, hermes_home):
+ from hermes_cli.loops import LoopManager, list_active_loops
+
+ LoopManager(session_id="a").set("task a", interval_seconds=60)
+ mgr_b = LoopManager(session_id="b")
+ mgr_b.set("task b", interval_seconds=60)
+ mgr_b.pause()
+
+ active = dict(list_active_loops())
+ assert "a" in active
+ assert "b" not in active
+
+ def test_migrate_to_session(self, hermes_home):
+ from hermes_cli.loops import LoopManager, load_loop, migrate_loop_to_session
+
+ LoopManager(session_id="parent").set("watch it", interval_seconds=60)
+ assert migrate_loop_to_session("parent", "child", reason="compression") is True
+ child = load_loop("child")
+ assert child is not None and child.prompt == "watch it"
+ parent = load_loop("parent")
+ assert parent is not None and parent.status == "cleared"
+
+ def test_migrate_no_source(self, hermes_home):
+ from hermes_cli.loops import migrate_loop_to_session
+
+ assert migrate_loop_to_session("nope", "child2") is False
+ assert migrate_loop_to_session("same", "same") is False
+
+ def test_migrate_does_not_clobber_child(self, hermes_home):
+ from hermes_cli.loops import LoopManager, load_loop, migrate_loop_to_session
+
+ LoopManager(session_id="p2").set("parent loop", interval_seconds=60)
+ LoopManager(session_id="c2").set("child loop", interval_seconds=60)
+ assert migrate_loop_to_session("p2", "c2") is False
+ assert load_loop("c2").prompt == "child loop"
+
+
+# ──────────────────────────────────────────────────────────────────────
+# Tick lifecycle
+# ──────────────────────────────────────────────────────────────────────
+
+
+class TestTickLifecycle:
+ def test_not_due_immediately(self, hermes_home):
+ from hermes_cli.loops import LoopManager
+
+ mgr = LoopManager(session_id="t1")
+ mgr.set("poll", interval_seconds=300)
+ assert mgr.is_due() is False
+
+ def test_due_after_interval(self, hermes_home):
+ from hermes_cli.loops import LoopManager
+
+ mgr = LoopManager(session_id="t2")
+ state = mgr.set("poll", interval_seconds=300)
+ state.next_due_at = time.time() - 1
+ assert mgr.is_due() is True
+
+ def test_fire_marks_awaiting_and_blocks_refire(self, hermes_home):
+ from hermes_cli.loops import LoopManager
+
+ mgr = LoopManager(session_id="t3")
+ state = mgr.set("poll the build", interval_seconds=300)
+ state.next_due_at = time.time() - 1
+ wakeup = mgr.fire_tick()
+ assert wakeup is not None
+ assert "[/loop wakeup #1" in wakeup
+ assert "poll the build" in wakeup
+ assert "LOOP_COMPLETE" in wakeup
+ assert mgr.state.awaiting_response is True
+ assert mgr.is_due() is False # can't double-fire mid-turn
+ assert mgr.fire_tick() is None
+
+ def test_slash_prompt_returned_raw(self, hermes_home):
+ from hermes_cli.loops import LoopManager
+
+ mgr = LoopManager(session_id="t4")
+ state = mgr.set("/recap", interval_seconds=300)
+ state.next_due_at = time.time() - 1
+ assert mgr.fire_tick() == "/recap"
+
+ def test_abandon_tick_rolls_back(self, hermes_home):
+ from hermes_cli.loops import LoopManager
+
+ mgr = LoopManager(session_id="t5")
+ state = mgr.set("poll", interval_seconds=300)
+ state.next_due_at = time.time() - 1
+ mgr.fire_tick()
+ mgr.abandon_tick()
+ assert mgr.state.awaiting_response is False
+ assert mgr.state.ticks_fired == 0
+
+ def test_complete_tick_marker_stops(self, hermes_home):
+ from hermes_cli.loops import LoopManager
+
+ mgr = LoopManager(session_id="t6")
+ state = mgr.set("poll", interval_seconds=300)
+ state.next_due_at = time.time() - 1
+ mgr.fire_tick()
+ decision = mgr.complete_tick("The deploy is live.\nLOOP_COMPLETE")
+ assert decision["stopped"] is True
+ assert decision["status"] == "done"
+
+ def test_complete_tick_times_cap(self, hermes_home):
+ from hermes_cli.loops import LoopManager
+
+ mgr = LoopManager(session_id="t7")
+ state = mgr.set("poll", interval_seconds=300, times=1)
+ state.next_due_at = time.time() - 1
+ mgr.fire_tick()
+ decision = mgr.complete_tick("still building")
+ assert decision["stopped"] is True
+ assert decision["status"] == "done"
+ assert "1/1" in decision["message"]
+
+ def test_complete_tick_continues_and_reschedules(self, hermes_home):
+ from hermes_cli.loops import LoopManager
+
+ mgr = LoopManager(session_id="t8")
+ state = mgr.set("poll", interval_seconds=300)
+ state.next_due_at = time.time() - 1
+ mgr.fire_tick()
+ decision = mgr.complete_tick("still building")
+ assert decision["stopped"] is False
+ assert decision["status"] == "active"
+ assert mgr.state.awaiting_response is False
+ assert mgr.state.next_due_at > time.time() + 250
+
+ def test_complete_tick_max_ticks_pauses(self, hermes_home):
+ from hermes_cli.loops import LoopManager
+
+ mgr = LoopManager(session_id="t9")
+ state = mgr.set("poll", interval_seconds=300)
+ state.max_ticks = 1
+ state.next_due_at = time.time() - 1
+ mgr.fire_tick()
+ decision = mgr.complete_tick("still building")
+ assert decision["stopped"] is True
+ assert decision["status"] == "paused"
+
+ def test_until_judge_done_stops(self, hermes_home):
+ from hermes_cli.loops import LoopManager
+
+ mgr = LoopManager(session_id="t10")
+ state = mgr.set("poll", interval_seconds=300, until="the suite is green")
+ state.next_due_at = time.time() - 1
+ mgr.fire_tick()
+ with patch("hermes_cli.goals.judge_goal", return_value=("done", "suite green", False, None, False)):
+ decision = mgr.complete_tick("All 500 tests passed.")
+ assert decision["stopped"] is True
+ assert decision["status"] == "done"
+
+ def test_until_judge_continue_loops(self, hermes_home):
+ from hermes_cli.loops import LoopManager
+
+ mgr = LoopManager(session_id="t11")
+ state = mgr.set("poll", interval_seconds=300, until="the suite is green")
+ state.next_due_at = time.time() - 1
+ mgr.fire_tick()
+ with patch("hermes_cli.goals.judge_goal", return_value=("continue", "3 failures", False, None, False)):
+ decision = mgr.complete_tick("3 tests still failing")
+ assert decision["stopped"] is False
+
+ def test_until_judge_error_fails_open(self, hermes_home):
+ from hermes_cli.loops import LoopManager
+
+ mgr = LoopManager(session_id="t12")
+ state = mgr.set("poll", interval_seconds=300, until="green")
+ state.next_due_at = time.time() - 1
+ mgr.fire_tick()
+ with patch("hermes_cli.goals.judge_goal", side_effect=RuntimeError("api down")):
+ decision = mgr.complete_tick("some output")
+ assert decision["stopped"] is False # fail-open: keep looping
+
+
+class TestSelfPacedBackoff:
+ def test_backoff_doubles_on_unchanged_and_resets_on_change(self, hermes_home):
+ from hermes_cli.loops import LoopManager
+
+ mgr = LoopManager(session_id="sp1")
+ state = mgr.set("watch the queue") # self-paced
+ floor = state.current_delay
+ assert state.mode == "self_paced"
+
+ # Tick 1: response A → delay stays at floor (change from empty digest).
+ state.next_due_at = time.time() - 1
+ mgr.fire_tick()
+ mgr.complete_tick("queue depth is 5")
+ assert mgr.state.current_delay == floor
+
+ # Tick 2: same response → backoff doubles.
+ mgr.state.next_due_at = time.time() - 1
+ mgr.fire_tick()
+ mgr.complete_tick("queue depth is 5")
+ assert mgr.state.current_delay == floor * 2
+
+ # Tick 3: same again → doubles again.
+ mgr.state.next_due_at = time.time() - 1
+ mgr.fire_tick()
+ mgr.complete_tick("queue depth is 5")
+ assert mgr.state.current_delay == floor * 4
+
+ # Tick 4: changed response → snaps back to floor.
+ mgr.state.next_due_at = time.time() - 1
+ mgr.fire_tick()
+ mgr.complete_tick("queue depth is 2 — draining")
+ assert mgr.state.current_delay == floor
+
+ def test_timestamp_only_changes_do_not_reset(self, hermes_home):
+ from hermes_cli.loops import LoopManager
+
+ mgr = LoopManager(session_id="sp2")
+ state = mgr.set("watch")
+ floor = state.current_delay
+ state.next_due_at = time.time() - 1
+ mgr.fire_tick()
+ mgr.complete_tick("Still building. Checked at 14:02:33")
+ mgr.state.next_due_at = time.time() - 1
+ mgr.fire_tick()
+ mgr.complete_tick("Still building. Checked at 14:07:33")
+ assert mgr.state.current_delay == floor * 2 # digest ignored the clock
+
+
+# ──────────────────────────────────────────────────────────────────────
+# Controls (pause/resume/clear) + min interval + status
+# ──────────────────────────────────────────────────────────────────────
+
+
+class TestControls:
+ def test_min_interval_enforced(self, hermes_home):
+ from hermes_cli.loops import LoopManager, min_interval_seconds
+
+ mgr = LoopManager(session_id="c1")
+ state = mgr.set("poll", interval_seconds=1)
+ assert state.interval_seconds >= min_interval_seconds()
+
+ def test_pause_resume(self, hermes_home):
+ from hermes_cli.loops import LoopManager
+
+ mgr = LoopManager(session_id="c2")
+ state = mgr.set("poll", interval_seconds=300)
+ state.next_due_at = time.time() - 1
+ mgr.pause()
+ assert mgr.is_active() is False
+ assert mgr.is_due() is False
+ mgr.resume()
+ assert mgr.is_active() is True
+
+ def test_paused_mid_tick_clears_awaiting(self, hermes_home):
+ from hermes_cli.loops import LoopManager
+
+ mgr = LoopManager(session_id="c3")
+ state = mgr.set("poll", interval_seconds=300)
+ state.next_due_at = time.time() - 1
+ mgr.fire_tick()
+ mgr.pause(reason="user-interrupted")
+ assert mgr.state.awaiting_response is False
+
+ def test_status_line_shapes(self, hermes_home):
+ from hermes_cli.loops import LoopManager
+
+ mgr = LoopManager(session_id="c4")
+ assert "No loop set" in mgr.status_line()
+ mgr.set("poll the build", interval_seconds=300)
+ assert "active" in mgr.status_line()
+ assert "poll the build" in mgr.status_line()
+ mgr.pause()
+ assert "paused" in mgr.status_line()
+ mgr.clear()
+ assert "No loop set" in mgr.status_line()
+
+
+# ──────────────────────────────────────────────────────────────────────
+# /goal mixing
+# ──────────────────────────────────────────────────────────────────────
+
+
+class TestGoalMixing:
+ def test_active_goal_blocks_tick(self, hermes_home):
+ from hermes_cli.goals import GoalManager
+ from hermes_cli.loops import goal_blocks_loop_tick
+
+ GoalManager(session_id="g1").set("finish the migration")
+ assert goal_blocks_loop_tick("g1") is True
+
+ def test_no_goal_does_not_block(self, hermes_home):
+ from hermes_cli.loops import goal_blocks_loop_tick
+
+ assert goal_blocks_loop_tick("g2") is False
+
+ def test_paused_goal_does_not_block(self, hermes_home):
+ from hermes_cli.goals import GoalManager
+ from hermes_cli.loops import goal_blocks_loop_tick
+
+ gm = GoalManager(session_id="g3")
+ gm.set("finish it")
+ gm.pause()
+ assert goal_blocks_loop_tick("g3") is False
+
+ def test_parked_goal_does_not_block(self, hermes_home):
+ from hermes_cli.goals import GoalManager
+ from hermes_cli.loops import goal_blocks_loop_tick
+
+ gm = GoalManager(session_id="g4")
+ gm.set("finish it")
+ gm.wait_for_seconds(3600, reason="waiting on CI")
+ assert goal_blocks_loop_tick("g4") is False
+
+
+# ──────────────────────────────────────────────────────────────────────
+# dispatch_loop_command (shared slash handler)
+# ──────────────────────────────────────────────────────────────────────
+
+
+class TestDispatchLoopCommand:
+ def test_create_fixed(self, hermes_home):
+ from hermes_cli.loops import LoopManager, dispatch_loop_command
+
+ mgr = LoopManager(session_id="d1")
+ result = dispatch_loop_command(mgr, "5m check the deploy")
+ assert result["created"] is True
+ assert "Loop set" in result["output"]
+ assert "every 5m" in result["output"]
+
+ def test_create_self_paced(self, hermes_home):
+ from hermes_cli.loops import LoopManager, dispatch_loop_command
+
+ mgr = LoopManager(session_id="d2")
+ result = dispatch_loop_command(mgr, "keep fixing the tests")
+ assert result["created"] is True
+ assert "Self-paced" in result["output"]
+
+ def test_status_empty(self, hermes_home):
+ from hermes_cli.loops import LoopManager, dispatch_loop_command
+
+ mgr = LoopManager(session_id="d3")
+ result = dispatch_loop_command(mgr, "")
+ assert result["created"] is False
+ assert "No loop set" in result["output"]
+
+ def test_pause_resume_stop(self, hermes_home):
+ from hermes_cli.loops import LoopManager, dispatch_loop_command
+
+ mgr = LoopManager(session_id="d4")
+ dispatch_loop_command(mgr, "5m poll")
+ assert "paused" in dispatch_loop_command(mgr, "pause")["output"].lower()
+ assert "resumed" in dispatch_loop_command(mgr, "resume")["output"].lower()
+ assert "stopped" in dispatch_loop_command(mgr, "stop")["output"].lower()
+ assert "No active loop" in dispatch_loop_command(mgr, "stop")["output"]
+
+ def test_route_stored(self, hermes_home):
+ from hermes_cli.loops import LoopManager, dispatch_loop_command, load_loop
+
+ mgr = LoopManager(session_id="d5")
+ route = {"platform": "telegram", "chat_id": "42", "chat_type": "private"}
+ dispatch_loop_command(mgr, "5m ping", route=route)
+ assert load_loop("d5").route == route
+
+ def test_help(self, hermes_home):
+ from hermes_cli.loops import LoopManager, dispatch_loop_command
+
+ mgr = LoopManager(session_id="d6")
+ out = dispatch_loop_command(mgr, "help")["output"]
+ assert "Usage" in out
+ assert "--times" in out
+
+ def test_bad_times_error(self, hermes_home):
+ from hermes_cli.loops import LoopManager, dispatch_loop_command
+
+ mgr = LoopManager(session_id="d7")
+ result = dispatch_loop_command(mgr, "5m poll --times banana")
+ assert result["created"] is False
+ assert "--times" in result["output"]
+
+
+# ──────────────────────────────────────────────────────────────────────
+# Command registry
+# ──────────────────────────────────────────────────────────────────────
+
+
+class TestCommandRegistry:
+ def test_loop_registered_with_proactive_alias(self):
+ from hermes_cli.commands import resolve_command
+
+ cmd = resolve_command("loop")
+ assert cmd is not None
+ assert cmd.name == "loop"
+ alias = resolve_command("proactive")
+ assert alias is not None
+ assert alias.name == "loop"
+
+
+# ──────────────────────────────────────────────────────────────────────
+# SessionDB.list_meta_prefix
+# ──────────────────────────────────────────────────────────────────────
+
+
+class TestListMetaPrefix:
+ def test_prefix_scan(self, hermes_home):
+ from hermes_state import SessionDB
+
+ db = SessionDB()
+ db.set_meta("lmp-test:aaa", "1")
+ db.set_meta("lmp-test:bbb", "2")
+ db.set_meta("other:aaa", "3")
+ rows = dict(db.list_meta_prefix("lmp-test:"))
+ assert rows == {"lmp-test:aaa": "1", "lmp-test:bbb": "2"}
+
+ def test_wildcards_escaped(self, hermes_home):
+ from hermes_state import SessionDB
+
+ db = SessionDB()
+ db.set_meta("pre%fix:x", "1")
+ db.set_meta("prefix:y", "2")
+ assert db.list_meta_prefix("pre%") == [("pre%fix:x", "1")]
+
+ def test_empty_prefix(self, hermes_home):
+ from hermes_state import SessionDB
+
+ db = SessionDB()
+ assert db.list_meta_prefix("") == []
diff --git a/tests/tui_gateway/test_loop_command.py b/tests/tui_gateway/test_loop_command.py
new file mode 100644
index 00000000000..41522bcc49f
--- /dev/null
+++ b/tests/tui_gateway/test_loop_command.py
@@ -0,0 +1,205 @@
+"""Tests for /loop handling in tui_gateway.
+
+The TUI routes ``/loop`` through ``command.dispatch`` (same rationale as
+``/goal`` — the CLI handler drives ``_pending_input``, which the slash
+worker has no reader for). State mutations go through the shared
+``dispatch_loop_command``; the per-session notification poller fires due
+wakeups via ``_maybe_fire_tui_loop_tick``.
+"""
+
+from __future__ import annotations
+
+import importlib
+import threading
+import time
+from pathlib import Path
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+
+def hermes_home(tmp_path, monkeypatch):
+ home = tmp_path / ".hermes"
+ home.mkdir()
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(home))
+
+ from hermes_cli import loops
+
+ loops._DB_CACHE.clear()
+ yield home
+ loops._DB_CACHE.clear()
+
+
+def server(hermes_home):
+ with patch.dict(
+ "sys.modules",
+ {
+ "hermes_cli.env_loader": MagicMock(),
+ "hermes_cli.banner": MagicMock(),
+ },
+ ):
+ mod = importlib.import_module("tui_gateway.server")
+ yield mod
+ mod._sessions.clear()
+ mod._pending.clear()
+ mod._answers.clear()
+
+
+def session(server):
+ sid = "sid-loop-test"
+ session_key = "tui-loop-session-1"
+ s = {
+ "session_key": session_key,
+ "history": [],
+ "history_lock": threading.Lock(),
+ "history_version": 0,
+ "running": False,
+ "attached_images": [],
+ "cols": 120,
+ }
+ server._sessions[sid] = s
+ return sid, session_key, s
+
+
+def _call(server, method, **params):
+ handler = server._methods[method]
+ return handler(1, params)
+
+
+# ── command.dispatch /loop ────────────────────────────────────────────
+
+
+def test_loop_bare_shows_status_when_none_set(server, session):
+ sid, _, _ = session
+ r = _call(server, "command.dispatch", name="loop", arg="", session_id=sid)
+ assert r["result"]["type"] == "exec"
+ assert "No loop set" in r["result"]["output"]
+
+
+def test_loop_set_persists(server, session):
+ sid, session_key, _ = session
+ r = _call(server, "command.dispatch", name="loop", arg="5m check the deploy", session_id=sid)
+ result = r["result"]
+ assert result["type"] == "exec"
+ assert "Loop set" in result["output"]
+
+ from hermes_cli.loops import LoopManager
+
+ mgr = LoopManager(session_key)
+ assert mgr.state is not None
+ assert mgr.state.prompt == "check the deploy"
+ assert mgr.state.status == "active"
+ assert mgr.state.interval_seconds == 300.0
+
+
+def test_loop_proactive_alias_resolves(server, session):
+ sid, _, _ = session
+ r = _call(server, "command.dispatch", name="proactive", arg="5m ping", session_id=sid)
+ assert "Loop set" in r["result"]["output"]
+
+
+def test_loop_pause_resume_stop(server, session):
+ sid, session_key, _ = session
+ _call(server, "command.dispatch", name="loop", arg="5m poll CI", session_id=sid)
+
+ r = _call(server, "command.dispatch", name="loop", arg="pause", session_id=sid)
+ assert "paused" in r["result"]["output"].lower()
+
+ r = _call(server, "command.dispatch", name="loop", arg="resume", session_id=sid)
+ assert "resumed" in r["result"]["output"].lower()
+
+ r = _call(server, "command.dispatch", name="loop", arg="stop", session_id=sid)
+ assert "stopped" in r["result"]["output"].lower()
+
+ from hermes_cli.loops import LoopManager
+
+ assert not LoopManager(session_key).has_loop()
+
+
+def test_loop_requires_session(server):
+ r = _call(server, "command.dispatch", name="loop", arg="5m x", session_id="unknown")
+ assert "error" in r
+ assert r["error"]["code"] == 4001
+
+
+# ── idle wakeup driver ────────────────────────────────────────────────
+
+
+def test_tui_tick_fires_when_idle_and_due(server, session):
+ sid, session_key, s = session
+ from hermes_cli.loops import LoopManager, save_loop
+
+ mgr = LoopManager(session_key)
+ mgr.set("poll the build", interval_seconds=60)
+ mgr.state.next_due_at = time.time() - 1
+ save_loop(session_key, mgr.state)
+
+ fired = {}
+
+ def fake_submit(rid, sid_, session_, text, **kwargs):
+ fired["text"] = text
+
+ with patch.object(server, "_run_prompt_submit", fake_submit), \
+ patch.object(server, "_emit"):
+ server._maybe_fire_tui_loop_tick(sid, s)
+
+ assert "poll the build" in fired.get("text", "")
+ assert "[/loop wakeup #1" in fired["text"]
+ # Session claimed for the wakeup turn.
+ assert s["running"] is True
+
+
+def test_tui_tick_defers_when_running(server, session):
+ sid, session_key, s = session
+ from hermes_cli.loops import LoopManager, save_loop
+
+ mgr = LoopManager(session_key)
+ mgr.set("poll", interval_seconds=60)
+ mgr.state.next_due_at = time.time() - 1
+ save_loop(session_key, mgr.state)
+ s["running"] = True
+
+ with patch.object(server, "_run_prompt_submit") as submit, \
+ patch.object(server, "_emit"):
+ server._maybe_fire_tui_loop_tick(sid, s)
+
+ submit.assert_not_called()
+ # Tick not consumed — still due for the next poll.
+ assert LoopManager(session_key).state.ticks_fired == 0
+
+
+def test_tui_tick_defers_to_active_goal(server, session):
+ sid, session_key, s = session
+ from hermes_cli.goals import GoalManager
+ from hermes_cli.loops import LoopManager, save_loop
+
+ GoalManager(session_id=session_key).set("finish the feature")
+ mgr = LoopManager(session_key)
+ mgr.set("poll", interval_seconds=60)
+ mgr.state.next_due_at = time.time() - 1
+ save_loop(session_key, mgr.state)
+
+ with patch.object(server, "_run_prompt_submit") as submit, \
+ patch.object(server, "_emit"):
+ server._maybe_fire_tui_loop_tick(sid, s)
+
+ submit.assert_not_called()
+ assert s["running"] is False
+
+
+def test_tui_tick_noop_when_not_due(server, session):
+ sid, session_key, s = session
+ from hermes_cli.loops import LoopManager
+
+ LoopManager(session_key).set("poll", interval_seconds=300)
+
+ with patch.object(server, "_run_prompt_submit") as submit, \
+ patch.object(server, "_emit"):
+ server._maybe_fire_tui_loop_tick(sid, s)
+
+ submit.assert_not_called()
+ assert s["running"] is False
diff --git a/tui_gateway/methods_tools.py b/tui_gateway/methods_tools.py
index 90764fd4f22..d27f4e0dda0 100644
--- a/tui_gateway/methods_tools.py
+++ b/tui_gateway/methods_tools.py
@@ -834,6 +834,37 @@ def _(rid, params: dict) -> dict:
{"type": "send", "notice": notice, "message": state.goal},
)
+ if name == "loop":
+ # /loop — recurring in-session wakeups (Claude Code parity). State
+ # mutation via the shared dispatcher; the notification poller thread
+ # fires due wakeups into this session while it's idle.
+ if not session:
+ return _err(rid, 4001, "no active session")
+ try:
+ from hermes_cli.loops import LoopManager, dispatch_loop_command
+ except Exception as exc:
+ return _err(rid, 5030, f"loops unavailable: {exc}")
+
+ sid_key = session.get("session_key") or ""
+ if not sid_key:
+ return _err(rid, 4001, "no session key")
+
+ mgr = LoopManager(session_id=sid_key)
+ result = dispatch_loop_command(mgr, arg)
+ output = result.get("output") or ""
+ if result.get("created"):
+ try:
+ from hermes_cli.loops import goal_blocks_loop_tick
+
+ if goal_blocks_loop_tick(sid_key):
+ output += (
+ "\nNote: an active /goal is driving this session — loop "
+ "wakeups defer until the goal finishes, pauses, or parks."
+ )
+ except Exception:
+ pass
+ return _ok(rid, {"type": "exec", "output": output})
+
if name == "undo":
# /undo [N]: back up N user turns (default 1), soft-delete the
# truncated rows on disk, and prefill the composer with the text
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index 62c19a3a5ab..a3a1a4ddfd5 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -9158,6 +9158,101 @@ _KANBAN_NOTIFY_KINDS = (
)
_KANBAN_SILENT_KINDS = frozenset({"archived", "unblocked"})
_KANBAN_POLL_SECONDS = 5.0
+_LOOP_POLL_SECONDS = 5.0
+
+
+def _maybe_fire_tui_loop_tick(sid: str, session: dict) -> None:
+ """Fire a due /loop wakeup for an idle TUI/Desktop/dashboard session.
+
+ Called from the per-session notification poller thread on a coarse
+ cadence. Claims the session under history_lock (running=True) before
+ dispatching so a racing user prompt wins cleanly. The post-turn hook
+ in the turn dispatcher completes the tick.
+ """
+ try:
+ from hermes_cli.loops import LoopManager, goal_blocks_loop_tick
+ except Exception:
+ return
+
+ sid_key = session.get("session_key") or ""
+ if not sid_key:
+ return
+ mgr = LoopManager(session_id=sid_key)
+ if not mgr.is_due():
+ return
+ if goal_blocks_loop_tick(sid_key):
+ return
+
+ with session["history_lock"]:
+ if session.get("running"):
+ return # busy — stays due, next poll retries
+ session["running"] = True
+
+ wakeup = mgr.fire_tick()
+ if not wakeup:
+ with session["history_lock"]:
+ session["running"] = False
+ return
+
+ tick_no = mgr.state.ticks_fired if mgr.state else "?"
+ rid = f"__loop__{int(time.time() * 1000)}"
+ try:
+ _emit(
+ "status.update",
+ sid,
+ {"kind": "loop", "text": f"↻ /loop wakeup #{tick_no} firing…"},
+ )
+ if wakeup.lstrip().startswith("/"):
+ # Slash-command loop: route through the slash pipeline instead of
+ # the model. No model reply to evaluate — complete immediately.
+ with session["history_lock"]:
+ session["running"] = False
+ try:
+ parts = wakeup.lstrip()[1:].split(None, 1)
+ resp = _methods["command.dispatch"](
+ rid,
+ {
+ "name": parts[0] if parts else "",
+ "arg": parts[1] if len(parts) > 1 else "",
+ "session_id": sid,
+ },
+ )
+ payload = (resp or {}).get("result") or {}
+ out = str(payload.get("output") or "").strip()
+ if out:
+ _emit("status.update", sid, {"kind": "loop", "text": out})
+ if payload.get("type") == "send" and payload.get("message"):
+ # The command resolves to a prompt (skill command etc.) —
+ # run it as a normal turn; the post-turn hook completes
+ # the tick.
+ with session["history_lock"]:
+ if session.get("running"):
+ mgr.abandon_tick()
+ return
+ session["running"] = True
+ _emit("message.start", sid)
+ _run_prompt_submit(rid, sid, session, payload["message"])
+ return
+ except Exception:
+ pass
+ decision = mgr.complete_tick("")
+ if decision.get("message"):
+ _emit("status.update", sid, {"kind": "loop", "text": decision["message"]})
+ return
+ _emit("message.start", sid)
+ _run_prompt_submit(rid, sid, session, wakeup)
+ except Exception as exc:
+ print(
+ f"[tui_gateway] loop wakeup dispatch failed: "
+ f"{type(exc).__name__}: {exc}",
+ file=sys.stderr,
+ )
+ with session["history_lock"]:
+ session["running"] = False
+ try:
+ mgr.abandon_tick()
+ except Exception:
+ pass
def _format_kanban_event_text(sub: dict, task, ev, board_slug: str) -> Optional[str]:
@@ -9337,8 +9432,23 @@ def _notification_poller_loop(
_emitted = set() # dedup re-queued events so same completion isn't emitted 50 times while session is busy
_last_kanban_poll = 0.0
+ _last_loop_poll = 0.0
while not stop_event.is_set() and not session.get("_finalized"):
_now = time.monotonic()
+ # ── /loop wakeup driver ──────────────────────────────────────
+ # Fire a due /loop tick for THIS session while it's idle. Same
+ # claim-under-lock pattern as the kanban dispatch below. Active
+ # non-parked /goal owns the idle boundary and defers the tick.
+ if _now - _last_loop_poll >= _LOOP_POLL_SECONDS:
+ _last_loop_poll = _now
+ try:
+ _maybe_fire_tui_loop_tick(sid, session)
+ except Exception as _loop_exc:
+ print(
+ f"[tui_gateway] loop wakeup poll failed: "
+ f"{type(_loop_exc).__name__}: {_loop_exc}",
+ file=sys.stderr,
+ )
if _now - _last_kanban_poll >= _KANBAN_POLL_SECONDS:
_last_kanban_poll = _now
try:
@@ -10397,6 +10507,36 @@ def _run_prompt_submit(
file=sys.stderr,
)
+ # ── /loop tick completion ──────────────────────────────────
+ # If the turn that just finished was a /loop wakeup (fired by
+ # the notification poller), evaluate it: LOOP_COMPLETE marker,
+ # --until judge, --times / max_ticks caps, next-tick schedule.
+ if status == "complete":
+ try:
+ from hermes_cli.loops import LoopManager
+
+ loop_sid_key = session.get("session_key") or ""
+ if loop_sid_key:
+ loop_mgr = LoopManager(session_id=loop_sid_key)
+ loop_state = loop_mgr.state
+ if loop_state is not None and loop_state.awaiting_response:
+ loop_decision = loop_mgr.complete_tick(
+ raw if isinstance(raw, str) else ""
+ )
+ loop_msg = loop_decision.get("message") or ""
+ if loop_msg:
+ _emit(
+ "status.update",
+ sid,
+ {"kind": "loop", "text": loop_msg},
+ )
+ except Exception as _loop_exc:
+ print(
+ f"[tui_gateway] loop completion hook failed: "
+ f"{type(_loop_exc).__name__}: {_loop_exc}",
+ file=sys.stderr,
+ )
+
# Apply pending_title now that the DB row exists — in the
# session-owned profile store (not the launch profile).
_pending = session.get("pending_title")
@@ -12260,6 +12400,8 @@ _PENDING_INPUT_COMMANDS: frozenset[str] = frozenset(
"steer",
"plan",
"goal",
+ "loop",
+ "proactive",
"moa",
"undo",
"learn",
diff --git a/website/docs/user-guide/features/loops.md b/website/docs/user-guide/features/loops.md
new file mode 100644
index 00000000000..7b066b44ba0
--- /dev/null
+++ b/website/docs/user-guide/features/loops.md
@@ -0,0 +1,122 @@
+---
+sidebar_position: 17
+title: "Recurring Loops"
+description: "Re-run a prompt on a recurring interval inside your session — Hermes' take on Claude Code's /loop."
+---
+
+# Recurring Loops (`/loop`)
+
+`/loop` re-runs a prompt (or a slash command) on a recurring cadence **inside your current session**. Each wakeup is a real agent turn: Hermes reads the current state fresh — the latest CI result, the newest queue depth, the file as it is now — does the work, reports back, and goes quiet until the next tick.
+
+It's Hermes' take on **Claude Code's `/loop`** (and its `/proactive` alias, which works here too). Where [`/goal`](./goals.md) is judge-driven — "keep working until this objective is achieved" — `/loop` is timer-driven: "do this again every N minutes (or whenever it makes sense) until something says stop."
+
+## When to use it
+
+- **Polling external state.** "Watch the deploy / the CI run / the queue and tell me when it changes." The canonical use case.
+- **Iterate-until-green.** "Run the tests, fix what fails, repeat until they pass."
+- **Monitoring during a work session.** Keep an eye on error rates or a long job's progress while you do something else in the same conversation.
+- **Periodic housekeeping.** Re-run a lint pass or a status summary every N minutes during a long session.
+
+When the work should run **unattended** — overnight, on a real schedule, surviving restarts of your terminal — use a [cron job](./cron.md) instead. `/loop` lives inside a session; cron lives outside all of them. And when the task is a single objective with a definition of done, [`/goal`](./goals.md) is usually the better fit.
+
+## Quick start
+
+```
+/loop 5m check the deploy status and tell me if it's live yet
+```
+
+What you'll see:
+
+1. **Loop accepted** — `↻ Loop set (every 5m): check the deploy status…`
+2. **First wakeup in 5m** — while the session is idle, Hermes injects the wakeup and runs a normal turn against current state.
+3. **Repeat** — every 5 minutes, until a stop condition fires or you stop it.
+
+Loop a slash command just as easily:
+
+```
+/loop 10m /recap
+```
+
+## The two cadence modes
+
+**Fixed interval — you set the clock.** Give an interval (`30s`, `5m`, `2h`, `1h30m`) and the loop fires on that schedule. Use it when the thing you're watching changes on its own timeline:
+
+```
+/loop 2m poll the build at ci.example.com/job/42 and ping me the moment it finishes
+```
+
+**Self-paced — Hermes sets the clock.** Omit the interval and the loop paces itself: it starts at the floor (1 minute by default), and while the agent's replies stop changing it backs off exponentially — 2m, 4m, 8m, up to the ceiling (15 minutes by default). The moment a reply differs from the last one, cadence snaps back to the floor. Change detection is a local digest comparison (timestamps are ignored), so idle waits cost nothing extra:
+
+```
+/loop keep an eye on the migration and summarize progress
+```
+
+The rule of thumb: **fixed interval when an external clock drives the work; self-paced when the work drives the rhythm.**
+
+## Stop conditions
+
+A loop ends when any of these fires:
+
+| Condition | How |
+|---|---|
+| The agent decides it's done | The wakeup prompt teaches the agent to end its reply with `LOOP_COMPLETE` on its own line when the task is finished or moot. |
+| A run cap | `--times N` — stop after N wakeups. |
+| An evidence-based condition | `--until <condition>` — after each wakeup, the same auxiliary judge that powers `/goal` checks the reply against your condition (fail-open: a broken judge never wedges the loop). |
+| You | `/loop stop` (or `/loop pause` to keep it around). |
+| The backstop budget | `loops.max_ticks` (default 100) pauses the loop so an unattended session can't burn tokens forever. `0` = unlimited. |
+
+Examples:
+
+```
+/loop 2m poll CI --times 30
+/loop 5m watch the queue --until queue depth reaches zero
+```
+
+## Commands
+
+| Command | What it does |
+|---|---|
+| `/loop [interval] <prompt> [--times N] [--until <cond>]` | Start (or replace) the loop for this session. |
+| `/loop` or `/loop status` | Show cadence, ticks fired, and time to the next wakeup. |
+| `/loop pause` | Stop firing without losing the loop. |
+| `/loop resume` | Pick it back up. |
+| `/loop stop` | End the loop. |
+| `/proactive …` | Alias for `/loop` (Claude Code parity). |
+
+Works on the CLI, the TUI (`hermes --tui`), the web dashboard chat, the desktop app, and every gateway platform (Telegram, Discord, Slack, WhatsApp, …). On messaging platforms the gateway fires wakeups even between your messages — the loop belongs to the chat's session, and its results arrive as ordinary replies.
+
+## Mixing with `/goal`
+
+Both features inject synthetic turns at idle boundaries, so they follow one rule: **an active goal owns the session.** While a `/goal` is actively driving (judge saying "continue"), loop wakeups defer. The loop resumes using idle time as soon as the goal finishes, pauses, or parks itself on a wait barrier (`/goal wait`, or the judge's automatic WAIT verdict). A parked goal plus a `/loop` is a natural combo: the goal waits on the big async thing while the loop keeps a heartbeat on something else.
+
+A real user message always wins over both — wakeups only fire while the session is idle and nothing of yours is queued.
+
+## Behavior details
+
+- **A wakeup is a normal user-role turn.** No system-prompt mutation, no toolset swap — prompt caching stays intact.
+- **Survives `/resume` and compression.** Loop state persists per session and migrates across context-compression boundaries, same as `/goal`.
+- **One loop per session.** Setting a new `/loop` replaces the old one. Run several loops by running several sessions (or use cron for a fleet of schedules).
+- **Interrupting a wakeup turn (Ctrl+C) pauses the loop** — recoverable with `/loop resume`, so cancel actually means cancel.
+- **Token cost scales with cadence.** Every tick is a full agent turn. Match the interval to how often the state actually changes; prefer self-pacing for idle waits.
+
+## Configuration
+
+```yaml
+# ~/.hermes/config.yaml
+loops:
+ min_interval_seconds: 30 # floor for fixed intervals
+ max_ticks: 100 # backstop budget (0 = unlimited)
+ self_paced_floor_seconds: 60 # self-paced starting cadence
+ self_paced_ceiling_seconds: 900 # self-paced max backoff
+```
+
+The `--until` judge routes through the `goal_judge` auxiliary task, so `auxiliary.goal_judge.*` overrides (provider, model, max_tokens) apply to loop conditions too.
+
+## `/loop` vs `/goal` vs cron
+
+| | `/loop` | `/goal` | cron |
+|---|---|---|---|
+| **Trigger** | Timer (or self-paced) | Judge verdict after each turn | Schedule, outside any session |
+| **Lives in** | Your current session | Your current session | Its own session per run |
+| **Ends when** | Stop condition / caps / you | Goal achieved / budget / you | You remove the job |
+| **Best for** | Polling, monitoring, periodic re-runs | One objective, iterate until done | Unattended, long-horizon schedules |
diff --git a/website/sidebars.ts b/website/sidebars.ts
index a917148fd65..0839f3bbe66 100644
--- a/website/sidebars.ts
+++ b/website/sidebars.ts
@@ -101,6 +101,7 @@ const sidebars: SidebarsConfig = {
'user-guide/features/kanban-worker-lanes',
'user-guide/features/goals',
'user-guide/features/heartbeat',
+ 'user-guide/features/loops',
'user-guide/features/code-execution',
'user-guide/features/hooks',
'user-guide/features/batch-processing',