Skip to content

The agent that grows with you

fix(goal): a delegation WAIT lifts as soon as a batch returns; the TUI passes the delegation count too

Teknium8477292f0f4e
diff --git a/hermes_cli/goals.py b/hermes_cli/goals.py
index ec5d2c6e5e4..0f1d870209e 100644
--- a/hermes_cli/goals.py
+++ b/hermes_cli/goals.py
@@ -439,6 +439,9 @@ class GoalState:
waiting_on_pid: Optional[int] = None
waiting_on_session: Optional[str] = None
waiting_until: float = 0.0
+ # Live delegation batches when a timed WAIT was set because of them; the barrier lifts as soon
+ # as that count drops (a batch returned), not only when the timer runs out.
+ waiting_on_delegations: int = 0
waiting_reason: Optional[str] = None
waiting_since: float = 0.0
contract: GoalContract = field(default_factory=GoalContract)
@@ -452,7 +455,7 @@ class GoalState:
def from_json(cls, raw: str) -> "GoalState":
data = json.loads(raw)
raw_subgoals = data.get("subgoals") or []
- ints = {k: int(data.get(k) or 0) for k in ("turns_used", "consecutive_parse_failures", "consecutive_transport_failures")}
+ ints = {k: int(data.get(k) or 0) for k in ("turns_used", "consecutive_parse_failures", "consecutive_transport_failures", "waiting_on_delegations")}
floats = {k: float(data.get(k) or 0.0) for k in ("created_at", "last_turn_at", "waiting_until", "waiting_since")}
return cls(
goal=data.get("goal", ""),
@@ -484,6 +487,7 @@ class GoalState:
self.waiting_on_pid = None
self.waiting_on_session = None
self.waiting_until = 0.0
+ self.waiting_on_delegations = 0
self.waiting_reason = None
self.waiting_since = 0.0
@@ -1299,13 +1303,17 @@ class GoalManager:
raise ValueError("session_id must be a non-empty string")
return self._park(reason, waiting_on_session=session_id)
- def wait_for_seconds(self, seconds: int, reason: str = "") -> GoalState:
- """Park until ``seconds`` from now (backoff/cooldown waits with no process to track)."""
+ def wait_for_seconds(self, seconds: int, reason: str = "", *, on_delegations: int = 0) -> GoalState:
+ """Park until ``seconds`` from now (backoff/cooldown waits with no process to track). With
+ ``on_delegations`` the wait is FOR those live delegation batches: it also lifts as soon as
+ fewer are live (a batch result came back), so the loop re-judges with the result in hand
+ instead of sleeping out a 20-minute timer (independent review: results arrived with 1,199 s
+ left on the timer and nothing re-judged)."""
self._require_active()
seconds = int(seconds)
if seconds <= 0:
raise ValueError("seconds must be a positive integer")
- return self._park(reason, waiting_until=time.time() + seconds)
+ return self._park(reason, waiting_until=time.time() + seconds, waiting_on_delegations=max(0, int(on_delegations)))
def stop_waiting(self) -> bool:
"""Clear any active wait barrier (pid / session / time). Returns True if one was cleared."""
@@ -1331,6 +1339,11 @@ class GoalManager:
still = _pid_alive(s.waiting_on_pid)
elif s.waiting_until:
still = time.time() < s.waiting_until
+ if still and s.waiting_on_delegations > 0:
+ # Set because of live delegations: lift the moment one of them returned.
+ live = count_active_delegations(self.session_id)
+ if live < s.waiting_on_delegations:
+ still = False
else:
return False
if still and s.waiting_since and s.waiting_until == 0.0 and time.time() - s.waiting_since > _MAX_BARRIER_WAIT_S:
@@ -1353,7 +1366,7 @@ class GoalManager:
reason = state.waiting_reason or tgt
return _decision("active", False, None, "waiting", reason, f"⏳ Goal parked — waiting on {tgt}: {reason}")
- def _apply_wait_directive(self, wait_directive: Dict[str, Any], reason: str) -> Dict[str, Any]:
+ def _apply_wait_directive(self, wait_directive: Dict[str, Any], reason: str, *, active_delegations: int = 0) -> Dict[str, Any]:
"""Judge said WAIT: set the barrier and park. The counted turn stands (the judge ran) but no
continuation fires; the loop resumes once the barrier clears."""
if wait_directive.get("session_id"):
@@ -1361,7 +1374,7 @@ class GoalManager:
elif wait_directive.get("pid"):
tgt = f"pid {self.wait_on(int(wait_directive['pid']), reason=reason).waiting_on_pid}"
else:
- self.wait_for_seconds(int(wait_directive["seconds"]), reason=reason)
+ self.wait_for_seconds(int(wait_directive["seconds"]), reason=reason, on_delegations=active_delegations)
tgt = f"{wait_directive['seconds']}s"
return _decision("active", False, None, "wait", reason, f"⏳ Goal parked (judge) — waiting on {tgt}: {reason}")
@@ -1412,7 +1425,7 @@ class GoalManager:
state.consecutive_transport_failures = state.consecutive_transport_failures + 1 if transport_failed else 0
if verdict == "wait" and wait_directive:
- return self._apply_wait_directive(wait_directive, reason)
+ return self._apply_wait_directive(wait_directive, reason, active_delegations=active_delegations)
# BLOCKED is NOT done: pause so the user sees the judge's reason and can re-scope or override,
# instead of burning turns on an unachievable goal or waving it through as complete.
diff --git a/tests/hermes_cli/test_goal_judge_delegations.py b/tests/hermes_cli/test_goal_judge_delegations.py
index 96275141b2b..28d38c30826 100644
--- a/tests/hermes_cli/test_goal_judge_delegations.py
+++ b/tests/hermes_cli/test_goal_judge_delegations.py
@@ -46,3 +46,25 @@ def test_count_active_delegations_is_scoped_to_the_spawning_session():
assert goals.count_active_delegations("root") == 1
assert goals.count_active_delegations("other") == 1
assert goals.count_active_delegations(None) == 0
+
+
+def test_a_delegation_wait_lifts_when_a_batch_returns_not_only_when_the_timer_runs_out(tmp_path, monkeypatch):
+ """Independent-review witness: results arrived with 1,199 s left on a 1,200 s WAIT and nothing
+ re-judged; integration sat unfinished until the timer ran out."""
+ from pathlib import Path
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes")); (tmp_path / ".hermes").mkdir()
+ goals._DB_CACHE.clear()
+ mgr = goals.GoalManager(session_id="root-wait")
+ mgr.set("integrate the rounds")
+ with patch.object(goals, "count_active_delegations", return_value=4):
+ mgr.wait_for_seconds(1200, reason="4 batches running", on_delegations=4)
+ assert mgr.is_waiting() is True # all four still live: parked
+ with patch.object(goals, "count_active_delegations", return_value=3):
+ assert mgr.is_waiting() is False # one returned: barrier lifted early
+ assert mgr.state.waiting_until == 0.0 and mgr.state.waiting_on_delegations == 0
+ # a plain timed wait (no delegations) is unaffected by the delegation count
+ mgr.wait_for_seconds(1200, reason="cooldown")
+ with patch.object(goals, "count_active_delegations", return_value=0):
+ assert mgr.is_waiting() is True
+ goals._DB_CACHE.clear()
diff --git a/tui_gateway/prompt_turn.py b/tui_gateway/prompt_turn.py
index d9f9b4f07bc..cf00abf0d0e 100644
--- a/tui_gateway/prompt_turn.py
+++ b/tui_gateway/prompt_turn.py
@@ -292,15 +292,17 @@ def _goal_followup_after_turn(
return goal_followup
try:
if session.get("session_key") and (goal_mgr := _active_goal_manager(session)) is not None:
+ _active_deleg = 0
try:
- from hermes_cli.goals import gather_background_processes as _gather_bg
+ from hermes_cli.goals import count_active_delegations, gather_background_processes as _gather_bg
# Only THIS session's processes (TUI turns register under session_key): subagents'
# pollers must not park the parent's goal. Same rule as the CLI and gateway loops.
_bg_procs = _gather_bg(owner_task_id=session.get("session_key") or None)
+ _active_deleg = count_active_delegations(getattr(session.get("agent"), "session_id", None))
except Exception:
_bg_procs = None
decision = goal_mgr.evaluate_after_turn(
- raw, user_initiated=True, background_processes=_bg_procs)
+ raw, user_initiated=True, background_processes=_bg_procs, active_delegations=_active_deleg)
if verdict_msg := decision.get("message") or "":
_emit("status.update", sid, {"kind": "goal", "text": verdict_msg})
if decision.get("should_continue") and (