Skip to content

The agent that grows with you

refactor(hermes_cli): goals.py — phase helpers for evaluate_after_turn, shared save/park/judge-call helpers, kanban status table, compact docs

Teknium27e5e13d2ed3
diff --git a/hermes_cli/goals.py b/hermes_cli/goals.py
index cc829e3faf3..de533b0b8cf 100644
--- a/hermes_cli/goals.py
+++ b/hermes_cli/goals.py
@@ -1,12 +1,12 @@
"""Persistent session goals — the Ralph loop for Hermes.
-A goal is a free-form user objective that stays active across turns. After each turn completes, a
-small judge call asks an auxiliary model "is this goal satisfied by the assistant's last response?".
+A goal is a free-form user objective that stays active across turns. After each turn a small judge
+call asks an auxiliary model "is this goal satisfied by the assistant's last response?".
-- The continuation prompt is just a normal user message appended to the session via
-``run_conversation``. No system-prompt mutation, no toolset swap — prompt caching stays intact. -
-Judge failures are fail-OPEN: ``continue``. A broken judge must not wedge progress; the turn budget
-is the backstop.
+- The continuation prompt is a normal user message appended via ``run_conversation``: no
+ system-prompt mutation, no toolset swap, so prompt caching stays intact.
+- Judge failures are fail-OPEN (``continue``); a broken judge must not wedge progress — the turn
+ budget is the backstop.
"""
from __future__ import annotations
@@ -29,44 +29,27 @@ from hermes_cli._subprocess_compat import noninteractive_git_env
logger = logging.getLogger(__name__)
-# ──────────────────────────────────────────────────────────────────────
-# Constants & defaults
-# ──────────────────────────────────────────────────────────────────────
+# ── Constants & defaults ──────────────────────────────────────────────
DEFAULT_MAX_TURNS = 20
DEFAULT_JUDGE_TIMEOUT = 30.0
-# Judge output budget. The freeform judge returns a one-line JSON verdict, but
-# reasoning models (deepseek-v4, qwq, etc.) burn tokens on hidden reasoning
-# before emitting the visible JSON — and the first /goal turn's prompt is
-# larger than later turns, which pushes total reply length past tight caps.
-# 200 tokens (the original default) reliably truncated the JSON on reasoning
-# models, leaving '{"done": true, "reason": "The agent successfully' and
-# triggering the auto-pause. 4096 covers reasoning + verdict on every model
-# we've live-tested; override via auxiliary.goal_judge.max_tokens for
-# specifically constrained setups.
+# Judge output budget. Reasoning models burn hidden-reasoning tokens before the visible one-line
+# JSON verdict; 200 (the original) reliably truncated it and tripped the auto-pause. 4096 covers
+# every model live-tested; override via auxiliary.goal_judge.max_tokens.
DEFAULT_JUDGE_MAX_TOKENS = 4096
-# Cap how much of the last response + recent messages we send to the judge.
+# Cap how much of the last response we send to the judge.
_JUDGE_RESPONSE_SNIPPET_CHARS = 4000
-# After this many consecutive judge *parse* failures (empty output / non-JSON),
-# the loop auto-pauses and points the user at the goal_judge config. API /
-# transport errors do NOT count toward this — those are transient. This guards
-# against small models (e.g. deepseek-v4-flash) that cannot follow the strict
-# JSON reply contract; without it the loop runs until the turn budget is
-# exhausted with every reply shaped like `judge returned empty response` or
-# `judge reply was not JSON`.
+# Consecutive judge *parse* failures (empty / non-JSON) before the loop auto-pauses and points at
+# the goal_judge config. API/transport errors do NOT count — those are tracked separately below.
+# Guards against small models that cannot follow the strict JSON contract burning the whole budget.
DEFAULT_MAX_CONSECUTIVE_PARSE_FAILURES = 3
-# Transport failures (API auth errors 401, timeouts, DNS, etc.) are also
-# tracked and auto-pause the loop after this many consecutive failures.
-# A broken/invalid API key returns 401 every call — the loop must not
-# run until the turn budget, wasting every turn on an unreachable judge.
+# Consecutive transport failures (401, timeout, DNS) before auto-pause: a broken API key returns
+# 401 every call and must not spend every turn on an unreachable judge.
DEFAULT_MAX_CONSECUTIVE_TRANSPORT_FAILURES = 5
-# Quality gates: deterministic shell commands that must pass before the goal
-# judge may declare the goal done. Defaults mirror the bounded-autonomy
-# pattern (per-gate retry limit + timeout, bounded output fed back to the
-# agent). A failed gate short-circuits the judge — its output IS the
-# continuation prompt, so the agent works on concrete evidence instead of a
-# vibe check.
+# Quality gates: deterministic shell commands that must pass before the judge may declare DONE. A
+# failed gate short-circuits the judge — its output IS the continuation prompt, so the agent works
+# on concrete evidence instead of a vibe check.
DEFAULT_GATE_TIMEOUT_SECONDS = 300
DEFAULT_GATE_MAX_RETRIES = 3
# Bounded tail of a failed gate's combined stdout/stderr fed back to the agent.
@@ -81,10 +64,8 @@ CONTINUATION_PROMPT_TEMPLATE = (
"If you are blocked and need input from the user, say so clearly and stop."
)
-# Used when the goal carries a structured completion contract. The contract
-# block tells the agent exactly what "done" means, how to prove it, what not
-# to break, what's in scope, and when to stop and ask — so it targets the
-# verification surface instead of declaring victory loosely.
+# With a completion contract: the block tells the agent what "done" means, how to prove it, what
+# not to break, scope, and when to stop — so it targets the verification surface.
CONTINUATION_PROMPT_WITH_CONTRACT_TEMPLATE = (
"[Continuing toward your standing goal]\n"
"Goal: {goal}\n\n"
@@ -98,9 +79,7 @@ CONTINUATION_PROMPT_WITH_CONTRACT_TEMPLATE = (
"user input, say so clearly and stop."
)
-# Used when the user has added one or more /subgoal criteria. Surfaced
-# to the agent verbatim so it sees what to target on the next turn,
-# and surfaced to the judge so the verdict considers them too.
+# With /subgoal criteria: surfaced verbatim to the agent and to the judge.
CONTINUATION_PROMPT_WITH_SUBGOALS_TEMPLATE = (
"[Continuing toward your standing goal]\n"
"Goal: {goal}\n\n"
@@ -113,9 +92,7 @@ CONTINUATION_PROMPT_WITH_SUBGOALS_TEMPLATE = (
"and stop."
)
-
-# Fed back when a quality gate fails: the gate's bounded output is the
-# evidence the agent must repair against. Deterministic — no judge involved.
+# Fed back when a quality gate fails: bounded output is the evidence to repair against (no judge).
CONTINUATION_PROMPT_GATE_FAILED_TEMPLATE = (
"[Continuing toward your standing goal — a quality gate failed]\n"
"Goal: {goal}\n\n"
@@ -132,7 +109,6 @@ CONTINUATION_PROMPT_GATE_FAILED_TEMPLATE = (
"gate itself is wrong or cannot pass, say so clearly and stop."
)
-
JUDGE_SYSTEM_PROMPT = (
"You are a strict judge evaluating whether an autonomous agent has "
"achieved a user's stated goal. You receive the goal text, the agent's "
@@ -183,16 +159,12 @@ JUDGE_SYSTEM_PROMPT = (
"accepted (true=done, false=continue)."
)
-
-# Rendered into the judge prompt when the agent has background processes
-# running. Gives the judge the context it needs to decide WAIT vs CONTINUE
-# (and which pid to wait on) without it having to probe anything itself.
+# Judge prompt block listing running background processes (WAIT vs CONTINUE, which pid).
JUDGE_BACKGROUND_BLOCK_TEMPLATE = (
"Background processes the agent currently has running (it may be waiting "
"on one of these):\n{background_lines}\n\n"
)
-
JUDGE_USER_PROMPT_TEMPLATE = (
"Goal:\n{goal}\n\n"
"Agent's most recent response:\n{response}\n\n"
@@ -201,8 +173,7 @@ JUDGE_USER_PROMPT_TEMPLATE = (
"Is the goal satisfied — done, blocked, continue, or wait?"
)
-# Used when the user has added /subgoal criteria. The judge must
-# evaluate ALL of them being met, not just the original goal.
+# With /subgoal criteria: the judge must see ALL of them met, not just the original goal.
JUDGE_USER_PROMPT_WITH_SUBGOALS_TEMPLATE = (
"Goal:\n{goal}\n\n"
"Additional criteria the user added mid-loop (all must also be "
@@ -221,10 +192,7 @@ JUDGE_USER_PROMPT_WITH_SUBGOALS_TEMPLATE = (
"Is the goal AND every additional criterion satisfied?"
)
-
-# Used when the goal carries a structured completion contract. The judge
-# decides DONE strictly against the Verification criterion and refuses to
-# accept completion when a constraint was violated.
+# With a contract: DONE strictly against the Verification criterion; a violated constraint refuses.
JUDGE_USER_PROMPT_WITH_CONTRACT_TEMPLATE = (
"Goal:\n{goal}\n\n"
"Completion contract (the authoritative definition of done):\n"
@@ -249,10 +217,7 @@ JUDGE_USER_PROMPT_WITH_CONTRACT_TEMPLATE = (
"Is the goal satisfied per its completion contract — done, blocked, continue, or wait?"
)
-
-# System prompt for /goal draft — turns a plain-language objective into a
-# structured completion contract the user can review before activating.
-# Adapted from Codex's "let Codex draft the goal" guidance.
+# /goal draft: turn a plain objective into a reviewable contract (after Codex's "draft the goal").
DRAFT_CONTRACT_SYSTEM_PROMPT = (
"You turn a user's plain-language objective into a structured completion "
"contract for an autonomous coding agent. The contract has five fields:\n"
@@ -274,19 +239,13 @@ DRAFT_CONTRACT_SYSTEM_PROMPT = (
)
-# ──────────────────────────────────────────────────────────────────────
-# Completion contract
-# ──────────────────────────────────────────────────────────────────────
+# ── Completion contract ───────────────────────────────────────────────
-# The five contract fields, in display order. Adapted from OpenAI Codex's
-# "strong goal" guidance: a durable objective works best when it names what
-# "done" means, how to prove it, what must not regress, what tools/paths are
-# in bounds, and when to stop and ask. A bare free-form goal (no contract)
-# stays fully supported — every field defaults empty and is simply omitted
-# from the prompts when unset.
+# The five contract fields, in display order (after OpenAI Codex's "strong goal" guidance: what
+# "done" means, how to prove it, what must not regress, what is in bounds, when to stop and ask).
+# A bare free-form goal stays fully supported — empty fields are omitted from every prompt.
_CONTRACT_FIELDS = ("outcome", "verification", "constraints", "boundaries", "stop_when")
-# Human labels for rendering and for the inline `field: value` parser.
_CONTRACT_LABELS = {
"outcome": "Outcome",
"verification": "Verification",
@@ -295,43 +254,23 @@ _CONTRACT_LABELS = {
"stop_when": "Stop when blocked",
}
-# Inline-input aliases the user may type before a value, mapped to the
-# canonical field name. e.g. `verify: tests pass` or `done when: ...`.
+# Inline-input aliases the user may type before a value (`verify: tests pass`, `done when: ...`).
_CONTRACT_ALIASES = {
- "outcome": "outcome",
- "goal": "outcome",
- "done": "outcome",
- "done when": "outcome",
- "verification": "verification",
- "verify": "verification",
- "verified by": "verification",
- "evidence": "verification",
- "proof": "verification",
- "constraints": "constraints",
- "constraint": "constraints",
- "preserve": "constraints",
- "must not": "constraints",
- "do not change": "constraints",
- "boundaries": "boundaries",
- "boundary": "boundaries",
- "scope": "boundaries",
- "allowed": "boundaries",
- "files": "boundaries",
- "stop when": "stop_when",
- "stop_when": "stop_when",
- "blocked": "stop_when",
- "stop if blocked": "stop_when",
- "give up when": "stop_when",
+ "outcome": "outcome", "goal": "outcome", "done": "outcome", "done when": "outcome",
+ "verification": "verification", "verify": "verification", "verified by": "verification",
+ "evidence": "verification", "proof": "verification",
+ "constraints": "constraints", "constraint": "constraints", "preserve": "constraints",
+ "must not": "constraints", "do not change": "constraints",
+ "boundaries": "boundaries", "boundary": "boundaries", "scope": "boundaries",
+ "allowed": "boundaries", "files": "boundaries",
+ "stop when": "stop_when", "stop_when": "stop_when", "blocked": "stop_when",
+ "stop if blocked": "stop_when", "give up when": "stop_when",
}
@dataclass
class GoalContract:
- """Optional structured completion contract for a goal.
-
- Each field is free-form prose the user (or :func:`draft_contract`) supplies. Empty fields are
- omitted everywhere — a goal with no contract behaves exactly like the original free-form goal.
- """
+ """Optional structured completion contract; empty fields are omitted everywhere."""
outcome: str = ""
verification: str = ""
@@ -352,68 +291,51 @@ class GoalContract:
return cls(**{f: str(data.get(f) or "").strip() for f in _CONTRACT_FIELDS})
def render_block(self) -> str:
- """Render non-empty contract fields as a labelled block. Empty
- contract → empty string (callers skip the section entirely)."""
- lines = []
- for f in _CONTRACT_FIELDS:
- val = getattr(self, f).strip()
- if val:
- lines.append(f"- {_CONTRACT_LABELS[f]}: {val}")
- return "\n".join(lines)
+ """Non-empty fields as a labelled block; empty contract → empty string."""
+ return "\n".join(
+ f"- {_CONTRACT_LABELS[f]}: {getattr(self, f).strip()}"
+ for f in _CONTRACT_FIELDS if getattr(self, f).strip()
+ )
def parse_contract(text: str) -> Tuple[str, GoalContract]:
- """Split user-typed goal text into a headline + structured contract.
-
- Supports inline ``field: value`` lines so power users can type a full contract in one shot,
- e.g.::
+ """Split user-typed goal text into a headline + contract from inline ``field: value`` lines.
- Migrate auth to JWT verify: the auth test suite passes constraints: keep the public /login
- response shape unchanged boundaries: only touch services/auth and its tests stop when: a schema
- change needs product sign-off
+ A headline without an explicit ``outcome:`` IS the outcome — it is not duplicated into the
+ contract block (the goal text already carries it), so outcome stays empty in that case.
"""
if not text:
return "", GoalContract()
-
headline_parts: List[str] = []
fields: Dict[str, List[str]] = {f: [] for f in _CONTRACT_FIELDS}
-
for raw_line in text.splitlines():
line = raw_line.strip()
if not line:
continue
- matched = False
if ":" in line:
prefix, _, value = line.partition(":")
key = _CONTRACT_ALIASES.get(prefix.strip().lower())
if key is not None and value.strip():
fields[key].append(value.strip())
- matched = True
- if not matched:
- headline_parts.append(line)
+ continue
+ headline_parts.append(line)
+ contract = GoalContract(**{f: " ".join(v).strip() for f, v in fields.items()})
+ return " ".join(headline_parts).strip(), contract
- headline = " ".join(headline_parts).strip()
- contract = GoalContract(
- **{f: " ".join(v).strip() for f, v in fields.items()}
- )
- # If a headline was given but no explicit `outcome:` field, the headline
- # IS the outcome — don't duplicate it into the contract block (the goal
- # text already carries it), so leave outcome empty in that case.
- return headline, contract
+def _render_extra_criteria(subgoals: List[str]) -> str:
+ return "\n".join(f"- Extra criterion {i}: {text}" for i, text in enumerate(subgoals, start=1))
-# ──────────────────────────────────────────────────────────────────────
-# Quality gates
-# ──────────────────────────────────────────────────────────────────────
+
+# ── Quality gates ─────────────────────────────────────────────────────
@dataclass
class GoalGate:
"""A deterministic shell command that must pass before a goal can be done.
- Gates run at turn boundary BEFORE the LLM judge. A failing gate short-circuits judging entirely:
- its bounded output becomes the continuation prompt, so the agent iterates against concrete
- evidence. Only when every gate passes does the judge get to decide DONE.
+ Gates run at turn boundary BEFORE the LLM judge; a failing gate short-circuits judging and its
+ bounded output becomes the continuation prompt.
"""
command: str
@@ -422,8 +344,7 @@ class GoalGate:
attempts: int = 0
last_exit_code: Optional[int] = None
last_output_tail: str = ""
- # Workspace fingerprint at the time of the last FAILED run — used to skip
- # re-running an identical gate when nothing changed since it failed.
+ # Workspace fingerprint at the last FAILED run — skips re-running an identical gate unchanged.
last_failed_fingerprint: str = ""
def to_dict(self) -> Dict[str, Any]:
@@ -445,76 +366,59 @@ class GoalGate:
def workspace_fingerprint(cwd: Optional[str] = None) -> str:
- """Cheap workspace change fingerprint for unchanged-gate skip.
-
- Uses ``git status --porcelain`` + ``git rev-parse HEAD`` inside a repo. Outside git returns an
- empty string, which never matches, so gates always re-run — a safe fallback.
- """
+ """sha256 of ``git rev-parse HEAD`` + ``git status --porcelain``; "" outside git (never matches,
+ so gates always re-run — a safe fallback)."""
workdir = cwd or os.getcwd()
try:
- head = subprocess.run(
- ["git", "rev-parse", "HEAD"],
- capture_output=True, text=True, encoding="utf-8", errors="replace",
- timeout=10, cwd=workdir,
- stdin=subprocess.DEVNULL, env=noninteractive_git_env(),
- )
- if head.returncode != 0:
- return ""
- status = subprocess.run(
- ["git", "status", "--porcelain"],
- capture_output=True, text=True, encoding="utf-8", errors="replace",
- timeout=30, cwd=workdir,
- stdin=subprocess.DEVNULL, env=noninteractive_git_env(),
- )
- if status.returncode != 0:
- return ""
- blob = head.stdout.strip() + "\n" + status.stdout
+ outputs = []
+ for argv, timeout in (
+ (["git", "rev-parse", "HEAD"], 10),
+ (["git", "status", "--porcelain"], 30),
+ ):
+ proc = subprocess.run(
+ argv, capture_output=True, text=True, encoding="utf-8", errors="replace",
+ timeout=timeout, cwd=workdir, stdin=subprocess.DEVNULL, env=noninteractive_git_env(),
+ )
+ if proc.returncode != 0:
+ return ""
+ outputs.append(proc.stdout)
+ blob = outputs[0].strip() + "\n" + outputs[1]
return hashlib.sha256(blob.encode("utf-8", "replace")).hexdigest()
except Exception:
return ""
def run_gate(gate: GoalGate, *, cwd: Optional[str] = None) -> Tuple[bool, int, str]:
- """Run one gate command. Returns ``(passed, exit_code, output_tail)``.
-
- Runs through the shell in ``cwd`` with a hard timeout; on timeout the process is killed and
- treated as failed with exit code -1. Output is the combined stdout+stderr tail, bounded to
- ``_GATE_OUTPUT_TAIL_CHARS``.
- """
+ """Run one gate through the shell. Returns ``(passed, exit_code, output_tail)``; a timeout kills
+ the process and counts as exit code -1."""
try:
proc = subprocess.run(
gate.command,
shell=True,
capture_output=True,
text=True,
- # A gate runs whatever the operator configured, so its output is
- # arbitrary bytes. The default text mode decodes with the process
- # codepage under errors="strict": one byte the codepage can't map
- # (emoji or CJK from a test runner on a non-UTF-8 Windows console,
- # or stray binary) kills the reader thread, leaves stdout as None,
- # and the tail the agent needs to fix the failure arrives empty.
+ # Operator-configured output is arbitrary bytes; strict codepage decoding of one
+ # unmappable byte (emoji/CJK on a non-UTF-8 Windows console) kills the reader thread
+ # and the tail the agent needs arrives empty.
encoding="utf-8",
errors="replace",
timeout=max(1, int(gate.timeout_seconds)),
cwd=cwd or None,
)
combined = (proc.stdout or "") + (("\n" + proc.stderr) if proc.stderr else "")
- tail = combined[-_GATE_OUTPUT_TAIL_CHARS:]
- return proc.returncode == 0, proc.returncode, tail
+ return proc.returncode == 0, proc.returncode, combined[-_GATE_OUTPUT_TAIL_CHARS:]
except subprocess.TimeoutExpired as exc:
- out = ""
- for chunk in (exc.stdout, exc.stderr):
- if chunk:
- out += chunk if isinstance(chunk, str) else chunk.decode("utf-8", "replace")
+ out = "".join(
+ chunk if isinstance(chunk, str) else chunk.decode("utf-8", "replace")
+ for chunk in (exc.stdout, exc.stderr) if chunk
+ )
tail = (out + f"\n[gate timed out after {gate.timeout_seconds}s]")[-_GATE_OUTPUT_TAIL_CHARS:]
return False, -1, tail
except Exception as exc:
return False, -1, f"[gate could not run: {type(exc).__name__}: {exc}]"
-# ──────────────────────────────────────────────────────────────────────
-# Dataclass
-# ──────────────────────────────────────────────────────────────────────
+# ── Goal state ────────────────────────────────────────────────────────
@dataclass
@@ -531,61 +435,37 @@ class GoalState:
last_reason: Optional[str] = None
paused_reason: Optional[str] = None # why we auto-paused (budget, etc.)
consecutive_parse_failures: int = 0 # judge-output parse failures in a row
- # Transport failures are API/auth/network errors. Broken API keys return
- # 401 every call — track them separately so the loop auto-pauses instead
- # of burning every turn budget slot on an unreachable judge.
+ # Tracked separately from parse failures: a broken API key returns 401 every call and must
+ # auto-pause instead of burning the budget on an unreachable judge.
consecutive_transport_failures: int = 0 # judge API/transport errors in a row
- # User-added criteria appended mid-loop via the /subgoal command.
- # When non-empty the judge prompt and continuation prompt both
- # include them so the agent works toward them and the judge factors
- # them into the verdict. Backwards-compatible: defaults to empty so
- # old state_meta rows load unchanged.
+ # User-added criteria (/subgoal). Both the judge and continuation prompts include them.
subgoals: List[str] = field(default_factory=list)
- # Wait barrier: when the agent is blocked on long-running async work
- # (CI poller, build, test run, deploy, rate-limit cooldown) the goal loop
- # PARKS instead of being re-poked every turn into busy-work. Two barrier
- # kinds, set automatically by the judge (which now sees the live
- # background-process list and can return a ``wait`` verdict) or manually
- # via ``/goal wait``:
- # • ``waiting_on_pid`` — park until that process exits.
- # • ``waiting_on_session`` — park until that process_registry session's
- # OWN trigger fires: it exits, OR (if it has watch_patterns) its
- # pattern matches. Covers long-lived watchers/servers that signal
- # mid-run via a trigger and may never exit. Preferred over raw pid
- # when the agent set up a watch_patterns/notify_on_complete process.
- # • ``waiting_until`` — park until this wall-clock epoch (time backoff).
- # While ANY is active, ``evaluate_after_turn`` short-circuits to
- # should_continue=False without burning a turn or calling the judge. The
- # barrier auto-clears when the pid exits / the trigger fires / the deadline
- # passes, then the next turn resumes normal judging. Cleared by that,
- # ``/goal unwait``, pause, resume, or clear. Backwards-compatible: old
- # state_meta rows load with no barrier.
+ # Wait barrier: parks the loop instead of re-poking the agent into busy-work while it is blocked
+ # on async work. Set by the judge's ``wait`` verdict or ``/goal wait``:
+ # • waiting_on_pid — until that process exits.
+ # • waiting_on_session — until that process_registry session's OWN trigger fires (exit OR
+ # watch_patterns match); preferred for long-lived watchers that signal mid-run.
+ # • waiting_until — until this wall-clock epoch (time backoff).
+ # While ANY is active, evaluate_after_turn returns should_continue=False without burning a turn
+ # or calling the judge. Cleared lazily when satisfied, or by /goal unwait, pause, resume, clear.
+ # All fields default empty so old state_meta rows load unchanged.
waiting_on_pid: Optional[int] = None
waiting_on_session: Optional[str] = None
waiting_until: float = 0.0
waiting_reason: Optional[str] = None
waiting_since: float = 0.0
- # Optional structured completion contract (outcome / verification /
- # constraints / boundaries / stop_when). Empty by default; a goal with
- # no contract behaves exactly like the original free-form goal.
contract: GoalContract = field(default_factory=GoalContract)
- # Quality gates (/goal gate add <cmd>): deterministic shell commands that
- # must ALL pass before the judge may declare the goal done. Empty by
- # default — a goal with no gates behaves exactly as before.
+ # /goal gate add <cmd>: ALL must pass before the judge may declare done.
gates: List[GoalGate] = field(default_factory=list)
def to_json(self) -> str:
- data = asdict(self)
- # asdict already recursed GoalContract into a plain dict.
- return json.dumps(data, ensure_ascii=False)
+ return json.dumps(asdict(self), ensure_ascii=False)
@classmethod
def from_json(cls, raw: str) -> "GoalState":
data = json.loads(raw)
raw_subgoals = data.get("subgoals") or []
- subgoals: List[str] = []
- if isinstance(raw_subgoals, list):
- subgoals = [str(s).strip() for s in raw_subgoals if str(s).strip()]
+ subgoals = [str(s).strip() for s in raw_subgoals if str(s).strip()] if isinstance(raw_subgoals, list) else []
return cls(
goal=data.get("goal", ""),
status=data.get("status", "active"),
@@ -612,23 +492,22 @@ class GoalState:
],
)
- # --- contract helpers -------------------------------------------------
-
def has_contract(self) -> bool:
return self.contract is not None and not self.contract.is_empty()
- # --- subgoals helpers -------------------------------------------------
-
def render_subgoals_block(self) -> str:
- """Render the subgoals as a numbered ``- N. text`` block. Empty when no subgoals exist."""
- if not self.subgoals:
- return ""
+ """Numbered ``- N. text`` block; empty when there are no subgoals."""
return "\n".join(f"- {i}. {text}" for i, text in enumerate(self.subgoals, start=1))
+ def clear_wait(self) -> None:
+ self.waiting_on_pid = None
+ self.waiting_on_session = None
+ self.waiting_until = 0.0
+ self.waiting_reason = None
+ self.waiting_since = 0.0
-# ──────────────────────────────────────────────────────────────────────
-# Persistence (SessionDB state_meta)
-# ──────────────────────────────────────────────────────────────────────
+
+# ── Persistence (SessionDB state_meta) ────────────────────────────────
def _meta_key(session_id: str) -> str:
@@ -639,42 +518,28 @@ _DB_CACHE: Dict[str, Any] = {}
_DB_BOOTSTRAP_LOCK = threading.Lock()
_DB_BOOTSTRAP_INFLIGHT: Dict[str, threading.Event] = {}
-# How long a loop-thread caller waits for an ALREADY-RUNNING bootstrap
-# before degrading to None. Normal SessionDB init is ~10-100ms, so a call
-# that arrives mid-bootstrap usually picks the cached instance up within
-# this window. A contended init (locked state.db mid-migration) blows past
-# it and the caller degrades. The loop stalls far under the watchdog's
-# probe window.
+# How long a loop-thread caller waits for an ALREADY-RUNNING bootstrap before degrading to None.
+# Normal SessionDB init is ~10-100ms so a mid-bootstrap call usually picks the cached instance up;
+# a contended init (locked state.db mid-migration) exceeds it and degrades. Far under the
+# watchdog's probe window.
_DB_BOOTSTRAP_LOOP_WAIT_S = 0.25
-# The call that STARTS the bootstrap (cold cache, nothing in flight)
-# waits this long instead of the short window above. A fresh state.db
-# init measures ~300ms warm on a fast machine: schema DDL, FTS table
-# creation, and the first hermes_cli.config import (journal-mode
-# resolution). It is longer on a slow CI box, and it is well past 0.25s.
-# The old window dropped the first /goal write. The response said
-# "Goal set" but nothing persisted. The longer window is a bounded
-# one-time stall. Only the kick call pays it. Every later call keeps
-# the short window, so a contended migration never stalls the loop
-# repeatedly.
+# The call that STARTS the bootstrap (cold cache) waits this long instead. A fresh state.db init
+# (schema DDL, FTS tables, first hermes_cli.config import) measures ~300ms warm and more on slow
+# CI — well past 0.25s, which used to drop the first /goal write ("Goal set" but nothing
+# persisted). Only the kick call pays this one-time stall; later calls keep the short window.
_DB_BOOTSTRAP_INIT_WAIT_S = 1.5
def _bootstrap_session_db(home: str, done: threading.Event) -> None:
"""Construct SessionDB off-loop and populate the cache (worker thread)."""
try:
- from hermes_constants import (
- reset_hermes_home_override,
- set_hermes_home_override,
- )
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
from hermes_state import SessionDB
- # Bind the caller's home for this thread. The cache key is the
- # caller's scoped home, so the constructed SessionDB must point at
- # that home's state.db too. Without the override, a multiplexed
- # worker thread resolves the process env (the default profile's
- # HERMES_HOME). It then caches the wrong profile's DB under this
- # profile's key.
+ # Bind the caller's home for this thread: the cache key is the caller's scoped home, and
+ # without the override a multiplexed worker thread would resolve the process env (default
+ # profile) and cache the wrong profile's DB under this profile's key.
token = set_hermes_home_override(home)
try:
db = SessionDB()
@@ -691,17 +556,12 @@ def _bootstrap_session_db(home: str, done: threading.Event) -> None:
def _get_session_db() -> Optional[Any]:
- """Return a SessionDB instance for the current HERMES_HOME.
+ """Return a cached SessionDB for the current HERMES_HOME (one per home so profile switches work).
- SessionDB has no built-in singleton, but opening a new connection per /goal call would thrash
- the file. We cache one instance per ``hermes_home`` path so profile switches still pick up the
- right DB. Defensive against import/instantiation failures so tests and non-standard launchers
- can still use the GoalManager.
-
- Never constructs SessionDB on an event-loop thread. On a cache miss with a running loop we kick
- a one-shot background bootstrap and wait a bounded grace window for it. The kick call waits the
- one-time init window (``_DB_BOOTSTRAP_INIT_WAIT_S``), so a healthy cold init completes and the
- first write is not dropped.
+ Never constructs SessionDB on an event-loop thread: on a cache miss with a running loop, kick a
+ one-shot background bootstrap and wait a bounded grace window (the kick call waits the longer
+ ``_DB_BOOTSTRAP_INIT_WAIT_S`` so a healthy cold init completes and the first write isn't dropped).
+ Defensive against import/instantiation failures so tests and non-standard launchers still work.
"""
try:
from hermes_constants import get_hermes_home
@@ -725,8 +585,7 @@ def _get_session_db() -> Optional[Any]:
if on_loop_thread:
with _DB_BOOTSTRAP_LOCK:
- # Re-check under the lock: a bootstrap may have finished between
- # the unlocked read above and here.
+ # Re-check under the lock: a bootstrap may have finished since the unlocked read.
cached = _DB_CACHE.get(home)
if cached is not None:
return cached
@@ -735,24 +594,12 @@ def _get_session_db() -> Optional[Any]:
done = threading.Event()
_DB_BOOTSTRAP_INFLIGHT[home] = done
threading.Thread(
- target=_bootstrap_session_db,
- args=(home, done),
- name="goals-sessiondb-bootstrap",
- daemon=True,
+ target=_bootstrap_session_db, args=(home, done),
+ name="goals-sessiondb-bootstrap", daemon=True,
).start()
- # This call starts the bootstrap, so it pays the one-time
- # init cost. Wait long enough for a healthy cold init
- # (~300ms warm, more on slow CI) to finish. This keeps the
- # first goal/heartbeat write from being silently dropped.
- wait = _DB_BOOTSTRAP_INIT_WAIT_S
+ wait = _DB_BOOTSTRAP_INIT_WAIT_S # kick call pays the one-time init cost
else:
- # Bootstrap already running: brief grace window only. A
- # healthy init usually finishes in tens of ms, so this
- # still picks the cached instance up. A contended init
- # (the crash-loop scenario) exceeds the window and we
- # degrade to None. The stall is bounded, far below the
- # watchdog's probe timeout.
- wait = _DB_BOOTSTRAP_LOOP_WAIT_S
+ wait = _DB_BOOTSTRAP_LOOP_WAIT_S # already running: brief grace window only
done.wait(wait)
return _DB_CACHE.get(home)
@@ -764,8 +611,7 @@ def _get_session_db() -> Optional[Any]:
with _DB_BOOTSTRAP_LOCK:
existing = _DB_CACHE.get(home)
if existing is not None:
- # A concurrent bootstrap won the race; keep one instance and
- # close ours so connections don't leak.
+ # A concurrent bootstrap won the race; close ours so connections don't leak.
try:
db.close()
except Exception:
@@ -776,11 +622,8 @@ def _get_session_db() -> Optional[Any]:
def _warn_dropped_write(manager: str, kind: str, session_id: str) -> None:
- """Log a dropped state write at WARNING.
-
- The reply already told the user the state was set; a silent drop makes that reply a lie. One
- shared message keeps goal, loop and heartbeat logs greppable as one bug class.
- """
+ """WARN on a dropped state write — the reply already told the user the state was set. One shared
+ message keeps goal, loop and heartbeat logs greppable as one bug class."""
logger.warning(
"%s: %s for %s not persisted — session DB unavailable "
"(bootstrap window exceeded, in-memory state still active)",
@@ -835,19 +678,15 @@ def clear_goal(session_id: str) -> None:
def migrate_goal_to_session(old_session_id: str, new_session_id: str, *, reason: str = "") -> bool:
- """Carry a persistent /goal from a parent session to its continuation.
-
- Returns True when a goal was migrated, False when there was nothing to migrate or the DB was
- unavailable. Best-effort and never raises — a failure here must not block compression.
- """
+ """Carry a persistent /goal from a parent session to its continuation. Best-effort, never raises
+ (a failure here must not block compression). Returns True when a goal was migrated."""
if not old_session_id or not new_session_id or old_session_id == new_session_id:
return False
try:
state = load_goal(old_session_id)
- if state is None or getattr(state, "status", None) == "cleared":
+ if state is None or state.status == "cleared":
return False
- # Don't clobber a goal already set on the child (e.g. a resumed
- # lineage that re-established its own goal).
+ # Don't clobber a goal already set on the child (e.g. a resumed lineage).
if load_goal(new_session_id) is not None:
return False
save_goal(new_session_id, state)
@@ -863,27 +702,19 @@ def migrate_goal_to_session(old_session_id: str, new_session_id: str, *, reason:
return False
-# ──────────────────────────────────────────────────────────────────────
-# Judge
-# ──────────────────────────────────────────────────────────────────────
+# ── Judge ─────────────────────────────────────────────────────────────
def _truncate(text: str, limit: int) -> str:
if not text:
return ""
- if len(text) <= limit:
- return text
- return text[:limit] + "… [truncated]"
+ return text if len(text) <= limit else text[:limit] + "… [truncated]"
def _pid_alive(pid: int) -> bool:
- """Return True if a process with ``pid`` is currently alive.
-
- Delegates to ``gateway.status._pid_exists`` — the canonical, cross-platform, footgun-safe
- liveness check (psutil with a ctypes / POSIX fallback). Critically this avoids ``os.kill(pid,
- 0)``, which on Windows is NOT a no-op: it routes to ``CTRL_C_EVENT`` and hard-kills the target's
- console process group (bpo-14484).
- """
+ """Liveness via ``gateway.status._pid_exists`` (psutil + ctypes/POSIX fallback). Never uses
+ ``os.kill(pid, 0)``: on Windows that routes to CTRL_C_EVENT and hard-kills the target's console
+ group (bpo-14484)."""
if not pid or pid <= 0:
return False
try:
@@ -892,7 +723,6 @@ def _pid_alive(pid: int) -> bool:
return bool(_pid_exists(int(pid)))
except Exception:
pass
- # Last-resort fallback if gateway.status is unavailable: psutil directly.
try:
import psutil # type: ignore
@@ -902,12 +732,8 @@ def _pid_alive(pid: int) -> bool:
def _session_waiting(session_id: str) -> bool:
- """Whether a goal parked on a process_registry session should stay parked.
-
- Delegates to ``process_registry.is_session_waiting`` — True while the session is running and (if
- it has watch_patterns) its trigger hasn't fired. Fail-safe: any import/registry error yields
- False (don't wait) so a stale barrier can never wedge the loop.
- """
+ """True while the process_registry session is running and its trigger hasn't fired. Fail-safe:
+ any import/registry error yields False so a stale barrier can never wedge the loop."""
if not session_id:
return False
try:
@@ -921,114 +747,78 @@ def _session_waiting(session_id: str) -> bool:
_JSON_OBJECT_RE = re.compile(r"\{.*?\}", re.DOTALL)
-def _goal_judge_max_tokens() -> int:
- """Resolve auxiliary.goal_judge.max_tokens, falling back to the default.
-
- ``load_config()`` is cached on the config file's (mtime, size), so calling this once per judge
- turn is cheap. A non-positive or non-int value falls back to the default rather than crashing
- the goal loop.
- """
+def _goal_judge_setting(key: str, default, cast):
+ """Resolve ``auxiliary.goal_judge.<key>``; non-positive/garbage falls back to ``default``
+ rather than crashing the loop. ``load_config()`` is cached on (mtime, size) so this is cheap."""
try:
from hermes_cli.config import load_config
- cfg = load_config()
- value = (
- (cfg.get("auxiliary") or {})
- .get("goal_judge", {})
- .get("max_tokens", DEFAULT_JUDGE_MAX_TOKENS)
- )
- value = int(value)
+ value = cast((load_config().get("auxiliary") or {}).get("goal_judge", {}).get(key, default))
if value > 0:
return value
except Exception:
pass
- return DEFAULT_JUDGE_MAX_TOKENS
+ return default
-def _goal_judge_timeout() -> float:
- """Resolve auxiliary.goal_judge.timeout, falling back to the default.
-
- Mirrors :func:`_goal_judge_max_tokens`. A non-positive or non-numeric value falls back rather
- than crashing the goal loop.
- """
- try:
- from hermes_cli.config import load_config
+def _goal_judge_max_tokens() -> int:
+ return _goal_judge_setting("max_tokens", DEFAULT_JUDGE_MAX_TOKENS, int)
- cfg = load_config()
- value = (
- (cfg.get("auxiliary") or {})
- .get("goal_judge", {})
- .get("timeout", DEFAULT_JUDGE_TIMEOUT)
- )
- value = float(value)
- if value > 0:
- return value
- except Exception:
- pass
- return DEFAULT_JUDGE_TIMEOUT
+def _goal_judge_timeout() -> float:
+ return _goal_judge_setting("timeout", DEFAULT_JUDGE_TIMEOUT, float)
-def _parse_judge_response(raw: str) -> Tuple[str, str, bool, Optional[Dict[str, Any]]]:
- """Parse the judge's reply. Fail-open on unusable output.
- Returns ``(verdict, reason, parse_failed, wait_directive)``. ``parse_failed`` flags output that
- wasn't the expected JSON verdict so callers can auto-pause after N consecutive failures instead
- of letting a weak judge burn the budget. ``wait_directive`` is ``{"pid"}`` or ``{"seconds"}``
- for a ``wait`` verdict; a wait with neither is downgraded to ``continue``. Accepts both the
- ``{"verdict": ...}`` shape and the legacy ``{"done": <bool>}`` shape.
- """
+def _extract_json_object(raw: str) -> Optional[Dict[str, Any]]:
+ """Best-effort: strip code fences, parse the blob, else pull the first ``{...}`` out."""
if not raw:
- return "continue", "judge returned empty response", True, None
-
+ return None
text = raw.strip()
-
- # Strip markdown code fences the model may wrap JSON in.
if text.startswith("```"):
text = text.strip("`")
- # Peel off leading json/JSON/etc tag
- nl = text.find("\n")
+ nl = text.find("\n") # peel off leading json/JSON tag
if nl != -1:
text = text[nl + 1:]
-
- # First try: parse the whole blob.
- data: Optional[Dict[str, Any]] = None
try:
data = json.loads(text)
except Exception:
- # Second try: pull the first JSON object out.
match = _JSON_OBJECT_RE.search(text)
- if match:
- try:
- data = json.loads(match.group(0))
- except Exception:
- data = None
+ if not match:
+ return None
+ try:
+ data = json.loads(match.group(0))
+ except Exception:
+ return None
+ return data if isinstance(data, dict) else None
- if not isinstance(data, dict):
+
+def _parse_judge_response(raw: str) -> Tuple[str, str, bool, Optional[Dict[str, Any]]]:
+ """Parse the judge's reply, fail-open. Returns ``(verdict, reason, parse_failed, wait_directive)``.
+
+ ``parse_failed`` flags non-JSON output so callers can auto-pause after N in a row.
+ ``wait_directive`` is ``{"session_id"}`` / ``{"pid"}`` / ``{"seconds"}`` for a ``wait``
+ verdict; a wait with no target is downgraded to ``continue``. Accepts ``{"verdict": ...}`` and
+ the legacy ``{"done": <bool>}`` shape.
+ """
+ if not raw:
+ return "continue", "judge returned empty response", True, None
+ data = _extract_json_object(raw)
+ if data is None:
return "continue", f"judge reply was not JSON: {_truncate(raw, 200)!r}", True, None
reason = str(data.get("reason") or "").strip() or "no reason provided"
-
- # Determine verdict — prefer the explicit "verdict" field, fall back to
- # the legacy "done" boolean.
verdict_raw = data.get("verdict")
if isinstance(verdict_raw, str):
verdict = verdict_raw.strip().lower()
else:
done_val = data.get("done")
- if isinstance(done_val, str):
- done = done_val.strip().lower() in {"true", "yes", "1", "done"}
- else:
- done = bool(done_val)
+ done = done_val.strip().lower() in {"true", "yes", "1", "done"} if isinstance(done_val, str) else bool(done_val)
verdict = "done" if done else "continue"
-
if verdict not in {"done", "blocked", "continue", "wait"}:
verdict = "continue"
-
if verdict != "wait":
return verdict, reason, False, None
- # Wait verdict: extract a concrete directive (pid or seconds). Accept a
- # few key spellings the model might emit.
def _first_int(*keys: str) -> Optional[int]:
for k in keys:
v = data.get(k)
@@ -1042,8 +832,7 @@ def _parse_judge_response(raw: str) -> Tuple[str, str, bool, Optional[Dict[str,
continue
return None
- # Prefer a session-id directive (releases on the process's own trigger —
- # exit OR watch-pattern match), then pid (exit only), then seconds.
+ # Prefer session (releases on the process's own trigger), then pid (exit only), then seconds.
sess = data.get("wait_on_session") or data.get("session_id") or data.get("wait_session")
if isinstance(sess, str) and sess.strip():
return "wait", reason, False, {"session_id": sess.strip()}
@@ -1053,41 +842,25 @@ def _parse_judge_response(raw: str) -> Tuple[str, str, bool, Optional[Dict[str,
seconds = _first_int("wait_for_seconds", "seconds", "wait_seconds")
if seconds is not None:
return "wait", reason, False, {"seconds": seconds}
- # Wait with no usable target — can't park on nothing; treat as continue.
return "continue", f"{reason} (wait verdict had no target — continuing)", False, None
def _render_background_block(background_processes: Optional[List[Dict[str, Any]]]) -> str:
- """Render the live background-process list for the judge prompt.
-
- Each entry is a ``process_registry.list_sessions()`` dict. Only RUNNING processes are worth
- showing (an exited one is nothing to wait on). Returns an empty string when there's nothing
- running, so the judge prompt is byte-identical to the no-background case (no behavior change for
- the common path).
- """
- if not background_processes:
- return ""
+ """Render RUNNING ``process_registry.list_sessions()`` entries for the judge prompt. Empty string
+ when nothing is running, so the prompt stays byte-identical to the no-background case."""
lines: List[str] = []
- for p in background_processes:
- if not isinstance(p, dict):
- continue
- if p.get("status") == "exited":
- continue
- pid = p.get("pid")
- if not pid:
+ for p in background_processes or []:
+ if not isinstance(p, dict) or p.get("status") == "exited" or not p.get("pid"):
continue
cmd = _truncate(str(p.get("command") or "").replace("\n", " ").strip(), 120)
- uptime = p.get("uptime_seconds")
tail = _truncate(str(p.get("output_preview") or "").replace("\n", " ").strip(), 120)
- sid = p.get("session_id")
- line = f"- pid {pid}"
- if sid:
- line += f" / session {sid}"
+ line = f"- pid {p['pid']}"
+ if p.get("session_id"):
+ line += f" / session {p['session_id']}"
line += f": {cmd}"
- if uptime is not None:
- line += f" (running {uptime}s)"
- # Surface the process's own trigger so the judge can wait on a
- # mid-run signal (watch-pattern) or completion, not just exit.
+ if p.get("uptime_seconds") is not None:
+ line += f" (running {p['uptime_seconds']}s)"
+ # Surface the process's own trigger so the judge can wait on a mid-run signal, not just exit.
wps = p.get("watch_patterns")
if wps:
hit = " [already matched]" if p.get("watch_hit") else ""
@@ -1102,6 +875,25 @@ def _render_background_block(background_processes: Optional[List[Dict[str, Any]]
return JUDGE_BACKGROUND_BLOCK_TEMPLATE.format(background_lines="\n".join(lines))
+def _call_goal_judge_llm(call_llm, system_prompt: str, user_prompt: str, timeout: Optional[float]) -> str:
+ """Route through call_llm so auxiliary.goal_judge.* config (provider/model, extra_body,
+ reasoning_effort, retries) all apply. Returns the raw reply text."""
+ resp = call_llm(
+ task="goal_judge",
+ messages=[
+ {"role": "system", "content": system_prompt},
+ {"role": "user", "content": user_prompt},
+ ],
+ temperature=0,
+ max_tokens=_goal_judge_max_tokens(),
+ timeout=timeout,
+ )
+ try:
+ return resp.choices[0].message.content or ""
+ except Exception:
+ return ""
+
+
def judge_goal(
goal: str,
last_response: str,
@@ -1113,24 +905,17 @@ def judge_goal(
) -> Tuple[str, str, bool, Optional[Dict[str, Any]], bool]:
"""Ask the auxiliary model whether the goal is satisfied.
- Returns ``(verdict, reason, parse_failed, wait_directive, transport_failed)`` where verdict is
- ``"done"``, ``"blocked"``, ``"continue"``, ``"wait"``, or ``"skipped"`` (when the judge couldn't
- be reached). ``wait_directive`` is set only for ``"wait"`` (``{"pid": int}`` or ``{"seconds":
- int}``); ``None`` otherwise.
-
- ``parse_failed`` is True only when the judge call succeeded but its output was unusable (empty
- or non-JSON). API/transport errors return False — they are transient and should fail-open
- silently.
+ Returns ``(verdict, reason, parse_failed, wait_directive, transport_failed)``; verdict is
+ ``done`` / ``blocked`` / ``continue`` / ``wait`` / ``skipped`` (judge unreachable).
+ ``parse_failed`` is True only when the call succeeded but the output was unusable; transport
+ errors set ``transport_failed`` instead and fail-open to ``continue``.
"""
if not goal.strip():
return "skipped", "empty goal", False, None, False
if not last_response.strip():
- # No substantive reply this turn — almost certainly not done yet.
return "continue", "empty response (nothing to evaluate)", False, None, False
if timeout is None:
- # The declared default for this path is the config key, not the
- # module constant — see _goal_judge_timeout (#91022).
- timeout = _goal_judge_timeout()
+ timeout = _goal_judge_timeout() # the declared default is the config key, not the constant
try:
from agent.auxiliary_client import call_llm
@@ -1138,71 +923,34 @@ def judge_goal(
logger.debug("goal judge: auxiliary client import failed: %s", exc)
return "continue", "auxiliary client unavailable", False, None, False
- # Build the prompt. Priority: contract > subgoals > plain. When both a
- # contract and subgoals exist, the subgoals are appended into the
- # contract block as extra criteria so the judge sees a single source of
- # truth.
+ # Prompt priority: contract > subgoals > plain. With both, subgoals fold into the contract
+ # block as extra criteria so the judge sees a single source of truth.
clean_subgoals = [s.strip() for s in (subgoals or []) if s and s.strip()]
- background_block = _render_background_block(background_processes)
- current_time = datetime.now(tz=timezone.utc).astimezone().strftime("%Y-%m-%d %H:%M:%S %Z")
-
+ common = dict(
+ goal=_truncate(goal, 2000),
+ response=_truncate(last_response, _JUDGE_RESPONSE_SNIPPET_CHARS),
+ background_block=_render_background_block(background_processes),
+ current_time=datetime.now(tz=timezone.utc).astimezone().strftime("%Y-%m-%d %H:%M:%S %Z"),
+ )
if contract is not None and not contract.is_empty():
contract_block = contract.render_block()
if clean_subgoals:
- extra = "\n".join(
- f"- Extra criterion {i}: {text}"
- for i, text in enumerate(clean_subgoals, start=1)
- )
- contract_block = f"{contract_block}\n{extra}"
+ contract_block = f"{contract_block}\n{_render_extra_criteria(clean_subgoals)}"
prompt = JUDGE_USER_PROMPT_WITH_CONTRACT_TEMPLATE.format(
- goal=_truncate(goal, 2000),
- contract_block=_truncate(contract_block, 2500),
- response=_truncate(last_response, _JUDGE_RESPONSE_SNIPPET_CHARS),
- background_block=background_block,
- current_time=current_time,
- )
+ contract_block=_truncate(contract_block, 2500), **common)
elif clean_subgoals:
- subgoals_block = "\n".join(
- f"- {i}. {text}" for i, text in enumerate(clean_subgoals, start=1)
- )
+ subgoals_block = "\n".join(f"- {i}. {text}" for i, text in enumerate(clean_subgoals, start=1))
prompt = JUDGE_USER_PROMPT_WITH_SUBGOALS_TEMPLATE.format(
- goal=_truncate(goal, 2000),
- subgoals_block=_truncate(subgoals_block, 2000),
- response=_truncate(last_response, _JUDGE_RESPONSE_SNIPPET_CHARS),
- background_block=background_block,
- current_time=current_time,
- )
+ subgoals_block=_truncate(subgoals_block, 2000), **common)
else:
- prompt = JUDGE_USER_PROMPT_TEMPLATE.format(
- goal=_truncate(goal, 2000),
- response=_truncate(last_response, _JUDGE_RESPONSE_SNIPPET_CHARS),
- background_block=background_block,
- current_time=current_time,
- )
+ prompt = JUDGE_USER_PROMPT_TEMPLATE.format(**common)
try:
- # Route through call_llm so auxiliary.goal_judge.* config
- # (provider/model/base_url, extra_body, reasoning_effort, retries)
- # all apply — the direct-create path dropped extra_body (#35566).
- resp = call_llm(
- task="goal_judge",
- messages=[
- {"role": "system", "content": JUDGE_SYSTEM_PROMPT},
- {"role": "user", "content": prompt},
- ],
- temperature=0,
- max_tokens=_goal_judge_max_tokens(),
- timeout=timeout,
- )
+ raw = _call_goal_judge_llm(call_llm, JUDGE_SYSTEM_PROMPT, prompt, timeout)
except Exception as exc:
logger.info("goal judge: API call failed (%s) — falling through to continue", exc)
return "continue", f"judge error: {type(exc).__name__}", False, None, True
- try:
- raw = resp.choices[0].message.content or ""
- except Exception:
- raw = ""
-
verdict, reason, parse_failed, wait_directive = _parse_judge_response(raw)
logger.info(
"goal judge: verdict=%s reason=%s%s",
@@ -1213,13 +961,8 @@ def judge_goal(
def gather_background_processes(task_id: Optional[str] = None) -> List[Dict[str, Any]]:
- """Return the live background-process snapshot for the goal judge.
-
- Thin, fail-safe wrapper over ``process_registry.list_sessions(task_id)``. Returns only RUNNING
- processes (an exited one is nothing to wait on) and never raises — any import/registry failure
- yields ``[]`` so the goal loop degrades to its pre-wait-barrier behavior (judge just won't see
- processes).
- """
+ """Fail-safe snapshot of RUNNING ``process_registry`` sessions for the judge; ``[]`` on any error
+ so the loop degrades to its pre-wait-barrier behavior."""
try:
from tools.process_registry import process_registry
@@ -1231,17 +974,12 @@ def gather_background_processes(task_id: Optional[str] = None) -> List[Dict[str,
def draft_contract(objective: str, *, timeout: Optional[float] = None) -> Optional[GoalContract]:
- """Expand a plain-language objective into a structured completion contract.
-
- Uses the ``goal_judge`` auxiliary task (main-model-first, cache-safe — it is a side LLM call,
- not a conversation turn). Returns a populated :class:`GoalContract` on success, or ``None`` when
- the auxiliary client is unavailable or the model's reply can't be parsed.
- """
+ """Expand a plain-language objective into a completion contract via the ``goal_judge`` auxiliary
+ task (a side LLM call, not a conversation turn). None when unavailable or unparseable."""
objective = (objective or "").strip()
if not objective:
return None
if timeout is None:
- # Same config-backed default as judge_goal (#91022).
timeout = _goal_judge_timeout()
try:
@@ -1251,26 +989,12 @@ def draft_contract(objective: str, *, timeout: Optional[float] = None) -> Option
return None
try:
- # Route through call_llm — same #35566 fix as the judge call above.
- resp = call_llm(
- task="goal_judge",
- messages=[
- {"role": "system", "content": DRAFT_CONTRACT_SYSTEM_PROMPT},
- {"role": "user", "content": f"Objective:\n{_truncate(objective, 4000)}"},
- ],
- temperature=0,
- max_tokens=_goal_judge_max_tokens(),
- timeout=timeout,
- )
+ raw = _call_goal_judge_llm(
+ call_llm, DRAFT_CONTRACT_SYSTEM_PROMPT, f"Objective:\n{_truncate(objective, 4000)}", timeout)
except Exception as exc:
logger.info("goal draft: API call failed (%s)", exc)
return None
- try:
- raw = resp.choices[0].message.content or ""
- except Exception:
- raw = ""
-
data = _extract_json_object(raw)
if not isinstance(data, dict):
logger.debug("goal draft: reply was not JSON: %r", _truncate(raw, 200))
@@ -1279,36 +1003,18 @@ def draft_contract(objective: str, *, timeout: Optional[float] = None) -> Option
return None if contract.is_empty() else contract
-def _extract_json_object(raw: str) -> Optional[Dict[str, Any]]:
- """Best-effort: pull the first JSON object out of a model reply.
-
- Shares the fence-stripping + first-object fallback logic used by the judge parser, but returns
- the dict (or None) rather than a verdict.
- """
- if not raw:
- return None
- text = raw.strip()
- if text.startswith("```"):
- text = text.strip("`")
- nl = text.find("\n")
- if nl != -1:
- text = text[nl + 1:]
- try:
- data = json.loads(text)
- except Exception:
- match = _JSON_OBJECT_RE.search(text)
- if not match:
- return None
- try:
- data = json.loads(match.group(0))
- except Exception:
- return None
- return data if isinstance(data, dict) else None
+# ── GoalManager — the orchestration surface CLI + gateway talk to ──────
-# ──────────────────────────────────────────────────────────────────────
-# GoalManager — the orchestration surface CLI + gateway talk to
-# ──────────────────────────────────────────────────────────────────────
+def _decision(status, should_continue: bool, prompt: Optional[str], verdict: str, reason: str, message: str) -> Dict[str, Any]:
+ return {
+ "status": status,
+ "should_continue": should_continue,
+ "continuation_prompt": prompt,
+ "verdict": verdict,
+ "reason": reason,
+ "message": message,
+ }
class GoalManager:
@@ -1341,7 +1047,7 @@ class GoalManager:
def status_line(self) -> str:
s = self._state
- if s is None or s.status in {"cleared",}:
+ if s is None or s.status == "cleared":
return "No active goal. Set one with /goal <text>."
turns = f"{s.turns_used}/{s.max_turns} turns"
sub = f", {len(s.subgoals)} subgoal{'s' if len(s.subgoals) != 1 else ''}" if s.subgoals else ""
@@ -1369,11 +1075,30 @@ class GoalManager:
# --- mutation -----------------------------------------------------
+ def _save(self) -> Optional[GoalState]:
+ save_goal(self.session_id, self._state)
+ return self._state
+
+ def _require_goal(self) -> GoalState:
+ if self._state is None or not self.has_goal():
+ raise RuntimeError("no active goal")
+ return self._state
+
+ def _require_active(self) -> GoalState:
+ if self._state is None or self._state.status != "active":
+ raise RuntimeError("no active goal to park")
+ return self._state
+
+ def _pause_state(self, reason: str) -> None:
+ self._state.status = "paused"
+ self._state.paused_reason = reason
+ self._save()
+
def set(self, goal: str, *, max_turns: Optional[int] = None, contract: Optional[GoalContract] = None) -> GoalState:
goal = (goal or "").strip()
if not goal:
raise ValueError("goal text is empty")
- state = GoalState(
+ self._state = GoalState(
goal=goal,
status="active",
turns_used=0,
@@ -1382,53 +1107,38 @@ class GoalManager:
last_turn_at=0.0,
contract=contract if contract is not None else GoalContract(),
)
- self._state = state
- save_goal(self.session_id, state)
- return state
+ return self._save()
def set_contract(self, contract: GoalContract) -> Optional[GoalState]:
"""Attach or replace the completion contract on the active goal."""
if self._state is None:
return None
self._state.contract = contract or GoalContract()
- save_goal(self.session_id, self._state)
- return self._state
+ return self._save()
def pause(self, reason: str = "user-paused") -> Optional[GoalState]:
if not self._state:
return None
self._state.status = "paused"
self._state.paused_reason = reason
- # A wait barrier is meaningless once paused — drop it.
- self._state.waiting_on_pid = None
- self._state.waiting_on_session = None
- self._state.waiting_until = 0.0
- self._state.waiting_reason = None
- self._state.waiting_since = 0.0
- save_goal(self.session_id, self._state)
- return self._state
+ self._state.clear_wait() # a wait barrier is meaningless once paused
+ return self._save()
def resume(self, *, reset_budget: bool = True) -> Optional[GoalState]:
if not self._state:
return None
self._state.status = "active"
self._state.paused_reason = None
- # Resuming starts fresh — clear any stale barrier.
- self._state.waiting_on_pid = None
- self._state.waiting_on_session = None
- self._state.waiting_until = 0.0
- self._state.waiting_reason = None
- self._state.waiting_since = 0.0
+ self._state.clear_wait() # resuming starts fresh
if reset_budget:
self._state.turns_used = 0
- save_goal(self.session_id, self._state)
- return self._state
+ return self._save()
def clear(self) -> None:
if self._state is None:
return
self._state.status = "cleared"
- save_goal(self.session_id, self._state)
+ self._save()
self._state = None
def mark_done(self, reason: str) -> None:
@@ -1437,43 +1147,36 @@ class GoalManager:
self._state.status = "done"
self._state.last_verdict = "done"
self._state.last_reason = reason
- save_goal(self.session_id, self._state)
+ self._save()
# --- /subgoal user controls ---------------------------------------
def add_subgoal(self, text: str) -> str:
- """Append a user-added criterion to the active goal. Requires ``has_goal()``; raises
- ``RuntimeError`` otherwise.
- """
- if self._state is None or not self.has_goal():
- raise RuntimeError("no active goal")
+ """Append a user-added criterion; raises ``RuntimeError`` without ``has_goal()``."""
+ state = self._require_goal()
text = (text or "").strip()
if not text:
raise ValueError("subgoal text is empty")
- self._state.subgoals.append(text)
- save_goal(self.session_id, self._state)
+ state.subgoals.append(text)
+ self._save()
return text
def remove_subgoal(self, index_1based: int) -> str:
"""Remove a subgoal by 1-based index. Returns the removed text."""
- if self._state is None or not self.has_goal():
- raise RuntimeError("no active goal")
+ state = self._require_goal()
idx = int(index_1based) - 1
- if idx < 0 or idx >= len(self._state.subgoals):
- raise IndexError(
- f"index out of range (1..{len(self._state.subgoals)})"
- )
- removed = self._state.subgoals.pop(idx)
- save_goal(self.session_id, self._state)
+ if idx < 0 or idx >= len(state.subgoals):
+ raise IndexError(f"index out of range (1..{len(state.subgoals)})")
+ removed = state.subgoals.pop(idx)
+ self._save()
return removed
def clear_subgoals(self) -> int:
"""Wipe all subgoals. Returns the previous count."""
- if self._state is None or not self.has_goal():
- raise RuntimeError("no active goal")
- prev = len(self._state.subgoals)
- self._state.subgoals = []
- save_goal(self.session_id, self._state)
+ state = self._require_goal()
+ prev = len(state.subgoals)
+ state.subgoals = []
+ self._save()
return prev
def render_subgoals(self) -> str:
@@ -1493,13 +1196,8 @@ class GoalManager:
timeout_seconds: Optional[int] = None,
max_retries: Optional[int] = None,
) -> GoalGate:
- """Append a quality-gate command to the active goal.
-
- Requires ``has_goal()``; raises ``RuntimeError`` otherwise. Returns the created gate so
- callers can echo it back.
- """
- if self._state is None or not self.has_goal():
- raise RuntimeError("no active goal")
+ """Append a quality-gate command; raises ``RuntimeError`` without ``has_goal()``."""
+ state = self._require_goal()
command = (command or "").strip()
if not command:
raise ValueError("gate command is empty")
@@ -1508,28 +1206,26 @@ class GoalManager:
timeout_seconds=int(timeout_seconds) if timeout_seconds else DEFAULT_GATE_TIMEOUT_SECONDS,
max_retries=int(max_retries) if max_retries else DEFAULT_GATE_MAX_RETRIES,
)
- self._state.gates.append(gate)
- save_goal(self.session_id, self._state)
+ state.gates.append(gate)
+ self._save()
return gate
def remove_gate(self, index_1based: int) -> str:
"""Remove a gate by 1-based index. Returns the removed command."""
- if self._state is None or not self.has_goal():
- raise RuntimeError("no active goal")
+ state = self._require_goal()
idx = int(index_1based) - 1
- if idx < 0 or idx >= len(self._state.gates):
- raise IndexError(f"index out of range (1..{len(self._state.gates)})")
- removed = self._state.gates.pop(idx)
- save_goal(self.session_id, self._state)
+ if idx < 0 or idx >= len(state.gates):
+ raise IndexError(f"index out of range (1..{len(state.gates)})")
+ removed = state.gates.pop(idx)
+ self._save()
return removed.command
def clear_gates(self) -> int:
"""Remove all gates. Returns the previous count."""
- if self._state is None or not self.has_goal():
- raise RuntimeError("no active goal")
- prev = len(self._state.gates)
- self._state.gates = []
- save_goal(self.session_id, self._state)
+ state = self._require_goal()
+ prev = len(state.gates)
+ state.gates = []
+ self._save()
return prev
def render_gates(self) -> str:
@@ -1553,7 +1249,7 @@ class GoalManager:
An unchanged workspace since the last failure of the same gate is NOT re-run — the recorded
failure is replayed and the attempt count advances, so a stalled agent can't spin re-running
- an identical red suite (mirrors Prime-Agent's unchanged-gate rule).
+ an identical red suite.
"""
state = self._state
if state is None or not state.gates:
@@ -1582,26 +1278,17 @@ class GoalManager:
skipped_note = " (workspace unchanged since last failure — not re-run)" if unchanged else ""
if gate.attempts > gate.max_retries:
- state.status = "paused"
- state.paused_reason = (
- f"quality gate exhausted {gate.attempts - 1} retries: $ {gate.command}"
+ self._pause_state(f"quality gate exhausted {gate.attempts - 1} retries: $ {gate.command}")
+ return _decision(
+ "paused", False, None, "gate_failed",
+ f"gate exhausted retries: $ {gate.command}",
+ f"⏸ Goal paused — quality gate still failing after "
+ f"{gate.max_retries} retries: $ {gate.command} "
+ f"(exit {exit_code}). Fix it manually or /goal gate remove it, "
+ f"then /goal resume.",
)
- save_goal(self.session_id, state)
- return {
- "status": "paused",
- "should_continue": False,
- "continuation_prompt": None,
- "verdict": "gate_failed",
- "reason": f"gate exhausted retries: $ {gate.command}",
- "message": (
- f"⏸ Goal paused — quality gate still failing after "
- f"{gate.max_retries} retries: $ {gate.command} "
- f"(exit {exit_code}). Fix it manually or /goal gate remove it, "
- f"then /goal resume."
- ),
- }
-
- save_goal(self.session_id, state)
+
+ self._save()
prompt = CONTINUATION_PROMPT_GATE_FAILED_TEMPLATE.format(
goal=state.goal,
command=gate.command,
@@ -1610,132 +1297,114 @@ class GoalManager:
max_retries=gate.max_retries,
output=tail or "(no output)",
)
- return {
- "status": "active",
- "should_continue": True,
- "continuation_prompt": prompt,
- "verdict": "gate_failed",
- "reason": f"gate failed (exit {exit_code}): $ {gate.command}",
- "message": (
- f"✗ Quality gate failed ({state.turns_used}/{state.max_turns} turns, "
- f"attempt {gate.attempts}/{gate.max_retries}){skipped_note}: $ {gate.command}"
- ),
- }
-
- save_goal(self.session_id, state)
+ return _decision(
+ "active", True, prompt, "gate_failed",
+ f"gate failed (exit {exit_code}): $ {gate.command}",
+ f"✗ Quality gate failed ({state.turns_used}/{state.max_turns} turns, "
+ f"attempt {gate.attempts}/{gate.max_retries}){skipped_note}: $ {gate.command}",
+ )
+
+ self._save()
return None
# --- /goal wait barrier -------------------------------------------
- def wait_on(self, pid: int, reason: str = "") -> GoalState:
- """Park the goal loop on a background process PID.
+ def _park(self, reason: str, **barrier) -> GoalState:
+ state = self._require_active()
+ state.clear_wait()
+ for k, v in barrier.items():
+ setattr(state, k, v)
+ state.waiting_reason = (reason or "").strip() or None
+ state.waiting_since = time.time()
+ return self._save()
- While the PID is alive ``evaluate_after_turn`` returns ``should_continue=False`` without
- calling the judge, so the loop quiesces instead of re-poking the agent into busy work.
- Auto-clears when the process exits; requires an active goal. For a process with a
- watch/notify trigger prefer ``wait_on_session`` so a mid-run trigger (not just exit)
- releases the barrier.
- """
- if self._state is None or self._state.status != "active":
- raise RuntimeError("no active goal to park")
+ def wait_on(self, pid: int, reason: str = "") -> GoalState:
+ """Park the goal loop until a background PID exits (no turn burned, no judge call). For a
+ process with a watch/notify trigger prefer ``wait_on_session``. Requires an active goal."""
+ self._require_active()
pid = int(pid)
if pid <= 0:
raise ValueError("pid must be a positive integer")
- self._state.waiting_on_pid = pid
- self._state.waiting_on_session = None
- self._state.waiting_until = 0.0
- self._state.waiting_reason = (reason or "").strip() or None
- self._state.waiting_since = time.time()
- save_goal(self.session_id, self._state)
- return self._state
+ return self._park(reason, waiting_on_pid=pid)
def wait_on_session(self, session_id: str, reason: str = "") -> GoalState:
- """Park the goal loop on a process_registry session's OWN trigger.
-
- Unlike ``wait_on`` (which releases only on PID exit), this releases when the session's
- trigger fires: it exits, OR — if it was started with ``watch_patterns`` — its pattern
- matches. This is the right barrier for a long-lived watcher/server/poller that signals mid-
- run and may never exit. Requires an active goal.
- """
- if self._state is None or self._state.status != "active":
- raise RuntimeError("no active goal to park")
+ """Park on a process_registry session's OWN trigger: exit OR ``watch_patterns`` match. The
+ right barrier for a long-lived watcher/poller that signals mid-run and may never exit."""
+ self._require_active()
session_id = str(session_id or "").strip()
if not session_id:
raise ValueError("session_id must be a non-empty string")
- self._state.waiting_on_session = session_id
- self._state.waiting_on_pid = None
- self._state.waiting_until = 0.0
- self._state.waiting_reason = (reason or "").strip() or None
- self._state.waiting_since = time.time()
- save_goal(self.session_id, self._state)
- return self._state
+ return self._park(reason, waiting_on_session=session_id)
def wait_for_seconds(self, seconds: int, reason: str = "") -> GoalState:
- """Park the goal loop until ``seconds`` from now have elapsed.
-
- Time-based counterpart to ``wait_on`` for backoff/cooldown waits with no process to track
- (e.g. rate limits). Auto-clears once the deadline passes; requires an active goal.
- """
- if self._state is None or self._state.status != "active":
- raise RuntimeError("no active goal to park")
+ """Park until ``seconds`` from now (backoff/cooldown waits with no process to track)."""
+ self._require_active()
seconds = int(seconds)
if seconds <= 0:
raise ValueError("seconds must be a positive integer")
- self._state.waiting_on_pid = None
- self._state.waiting_on_session = None
- self._state.waiting_until = time.time() + seconds
- self._state.waiting_reason = (reason or "").strip() or None
- self._state.waiting_since = time.time()
- save_goal(self.session_id, self._state)
- return self._state
+ return self._park(reason, waiting_until=time.time() + seconds)
def stop_waiting(self) -> bool:
"""Clear any active wait barrier (pid / session / time). Returns True if one was cleared."""
- if self._state is None:
- return False
- if (
- self._state.waiting_on_pid is None
- and self._state.waiting_on_session is None
- and not self._state.waiting_until
- ):
+ s = self._state
+ if s is None or (s.waiting_on_pid is None and s.waiting_on_session is None and not s.waiting_until):
return False
- self._state.waiting_on_pid = None
- self._state.waiting_on_session = None
- self._state.waiting_until = 0.0
- self._state.waiting_reason = None
- self._state.waiting_since = 0.0
- save_goal(self.session_id, self._state)
+ s.clear_wait()
+ self._save()
return True
def is_waiting(self) -> bool:
- """True iff a barrier is set AND not yet satisfied.
-
- Session barrier: until the process exits or its watch-pattern fires. Pid barrier: while
- alive. Time barrier: until the deadline. Side effect: a satisfied barrier is cleared here
- (lazy auto-clear) so the next evaluation resumes normal judging.
- """
+ """True iff a barrier is set AND not yet satisfied. A satisfied barrier is cleared here
+ (lazy auto-clear) so the next evaluation resumes normal judging."""
s = self._state
if s is None:
return False
if s.waiting_on_session is not None:
- if _session_waiting(s.waiting_on_session):
- return True
- self.stop_waiting() # session exited or trigger fired
- return False
- if s.waiting_on_pid is not None:
- if _pid_alive(s.waiting_on_pid):
- return True
- self.stop_waiting() # process gone
- return False
- if s.waiting_until:
- if time.time() < s.waiting_until:
- return True
- self.stop_waiting() # deadline passed
+ still = _session_waiting(s.waiting_on_session)
+ elif s.waiting_on_pid is not None:
+ still = _pid_alive(s.waiting_on_pid)
+ elif s.waiting_until:
+ still = time.time() < s.waiting_until
+ else:
return False
- return False
+ if not still:
+ self.stop_waiting()
+ return still
# --- the main entry point called after every turn -----------------
+ def _waiting_decision(self, state: GoalState) -> Dict[str, Any]:
+ if state.waiting_on_session is not None:
+ tgt = f"session {state.waiting_on_session}"
+ elif state.waiting_on_pid is not None:
+ tgt = f"pid {state.waiting_on_pid}"
+ else:
+ tgt = f"{max(0, int(state.waiting_until - time.time()))}s remaining"
+ 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]:
+ """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"):
+ self.wait_on_session(str(wait_directive["session_id"]), reason=reason)
+ tgt = f"session {wait_directive['session_id']}"
+ elif wait_directive.get("pid"):
+ self.wait_on(int(wait_directive["pid"]), reason=reason)
+ tgt = f"pid {wait_directive['pid']}"
+ else:
+ self.wait_for_seconds(int(wait_directive["seconds"]), reason=reason)
+ tgt = f"{wait_directive['seconds']}s"
+ return _decision("active", False, None, "wait", reason, f"⏳ Goal parked (judge) — waiting on {tgt}: {reason}")
+
+ def _budget_pause(self, state: GoalState, verdict: str, reason: str, note: str = "") -> Dict[str, Any]:
+ self._pause_state(f"turn budget exhausted ({state.turns_used}/{state.max_turns})")
+ return _decision(
+ "paused", False, None, verdict, reason,
+ f"⏸ Goal paused — {state.turns_used}/{state.max_turns} turns used{note}. "
+ "Use /goal resume to keep going, or /goal clear to stop.",
+ )
+
def evaluate_after_turn(
self,
last_response: str,
@@ -1743,74 +1412,35 @@ class GoalManager:
user_initiated: bool = True,
background_processes: Optional[List[Dict[str, Any]]] = None,
) -> Dict[str, Any]:
- """Run the judge and update state. Return a decision dict.
+ """Run gates + judge and update state. Return a decision dict.
- ``user_initiated`` distinguishes a real user prompt (True) from a continuation prompt we fed
- ourselves (False). Both increment ``turns_used`` because both consume model budget.
+ ``user_initiated`` distinguishes a real user prompt from a continuation we fed ourselves;
+ both increment ``turns_used`` because both consume model budget.
- Decision keys: - ``status``: current goal status after update - ``should_continue``: bool —
- caller should fire another turn - ``continuation_prompt``: str or None - ``verdict``: "done"
- | "blocked" | "continue" | "wait" | "skipped" | "inactive" - ``reason``: str - ``message``:
- user-visible one-liner to print/send
+ Decision keys: ``status`` (goal status after update), ``should_continue`` (caller should fire
+ another turn), ``continuation_prompt`` (str or None), ``verdict`` ("done" | "blocked" |
+ "continue" | "wait" | "waiting" | "gate_failed" | "skipped" | "inactive"), ``reason``,
+ ``message`` (user-visible one-liner).
"""
state = self._state
if state is None or state.status != "active":
- return {
- "status": state.status if state else None,
- "should_continue": False,
- "continuation_prompt": None,
- "verdict": "inactive",
- "reason": "no active goal",
- "message": "",
- }
-
- # Wait barrier: if the loop is parked (on a live process OR a time
- # deadline that hasn't passed), quiesce — do NOT burn a turn or call
- # the judge. Resumes automatically once the barrier clears.
+ return _decision(state.status if state else None, False, None, "inactive", "no active goal", "")
+
+ # Parked on a live process or an unexpired deadline: quiesce without burning a turn.
if self.is_waiting():
- if state.waiting_on_session is not None:
- tgt = f"session {state.waiting_on_session}"
- elif state.waiting_on_pid is not None:
- tgt = f"pid {state.waiting_on_pid}"
- else:
- remaining = max(0, int(state.waiting_until - time.time()))
- tgt = f"{remaining}s remaining"
- reason = state.waiting_reason or tgt
- return {
- "status": "active",
- "should_continue": False,
- "continuation_prompt": None,
- "verdict": "waiting",
- "reason": reason,
- "message": f"⏳ Goal parked — waiting on {tgt}: {reason}",
- }
-
- # Count the turn that just finished.
+ return self._waiting_decision(state)
+
state.turns_used += 1
state.last_turn_at = time.time()
- # Quality gates run BEFORE the LLM judge: a failing gate is
- # deterministic evidence the goal is not done, so the judge call is
- # skipped entirely and the gate's output drives the next turn. Gate
- # continuations respect the same turn budget as judge continuations.
+ # Gates run BEFORE the judge: a failing gate is deterministic evidence the goal is not done,
+ # so the judge is skipped and the gate's output drives the next turn (same turn budget).
gate_decision = self._check_gates()
if gate_decision is not None:
if gate_decision.get("should_continue") and state.turns_used >= state.max_turns:
- state.status = "paused"
- state.paused_reason = f"turn budget exhausted ({state.turns_used}/{state.max_turns})"
- save_goal(self.session_id, state)
- return {
- "status": "paused",
- "should_continue": False,
- "continuation_prompt": None,
- "verdict": "gate_failed",
- "reason": gate_decision.get("reason", ""),
- "message": (
- f"⏸ Goal paused — {state.turns_used}/{state.max_turns} turns used "
- f"(a quality gate is still failing). "
- "Use /goal resume to keep going, or /goal clear to stop."
- ),
- }
+ return self._budget_pause(
+ state, "gate_failed", gate_decision.get("reason", ""),
+ note=" (a quality gate is still failing)")
return gate_decision
verdict, reason, parse_failed, wait_directive, transport_failed = judge_goal(
@@ -1822,196 +1452,86 @@ class GoalManager:
)
state.last_verdict = verdict
state.last_reason = reason
+ # Parse failures reset on any usable reply INCLUDING transport errors, so a flaky network
+ # doesn't trip the auto-pause meant for bad judge models; transport failures are counted
+ # separately because persistent API errors (401, DNS) mean a broken config.
+ state.consecutive_parse_failures = state.consecutive_parse_failures + 1 if parse_failed else 0
+ state.consecutive_transport_failures = state.consecutive_transport_failures + 1 if transport_failed else 0
- # Track consecutive judge parse failures. Reset on any usable reply,
- # including API / transport errors (parse_failed=False) so a flaky
- # network doesn't trip the auto-pause meant for bad judge models.
- if parse_failed:
- state.consecutive_parse_failures += 1
- else:
- state.consecutive_parse_failures = 0
-
- # Track consecutive transport failures separately — persistent API
- # errors (401 auth, DNS, timeout) signal a broken config, not
- # transient network flakiness. Auto-pause after N consecutive
- # transport failures so a permanently broken judge doesn't burn
- # every turn budget slot on an unreachable API.
- if transport_failed:
- state.consecutive_transport_failures += 1
- else:
- state.consecutive_transport_failures = 0
-
- # WAIT verdict: the judge decided the agent is blocked on async work
- # and re-poking now would be busy-work. Set the barrier and park —
- # the turn we just counted stands (the judge call happened), but no
- # continuation fires. The loop resumes automatically when the pid
- # exits or the deadline passes (next evaluate_after_turn falls through
- # the is_waiting() short-circuit once the barrier clears).
if verdict == "wait" and wait_directive:
- if wait_directive.get("session_id"):
- self.wait_on_session(str(wait_directive["session_id"]), reason=reason)
- tgt = f"session {wait_directive['session_id']}"
- elif wait_directive.get("pid"):
- self.wait_on(int(wait_directive["pid"]), reason=reason)
- tgt = f"pid {wait_directive['pid']}"
- else:
- self.wait_for_seconds(int(wait_directive["seconds"]), reason=reason)
- tgt = f"{wait_directive['seconds']}s"
- return {
- "status": "active",
- "should_continue": False,
- "continuation_prompt": None,
- "verdict": "wait",
- "reason": reason,
- "message": f"⏳ Goal parked (judge) — waiting on {tgt}: {reason}",
- }
-
- # BLOCKED verdict: the judge ruled the goal genuinely cannot be
- # satisfied as stated (impossible, out of scope, needs user input).
- # This is NOT done — don't keep burning turns on an unachievable goal
- # and don't wave it through as complete (#100954). Pause so the user
- # sees the judge's reason and can re-scope (/goal set) or override
- # (/goal resume).
+ return self._apply_wait_directive(wait_directive, reason)
+
+ # 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.
if verdict == "blocked":
- state.status = "paused"
- state.paused_reason = f"judged unachievable: {reason}"
- save_goal(self.session_id, state)
- return {
- "status": "paused",
- "should_continue": False,
- "continuation_prompt": None,
- "verdict": "blocked",
- "reason": reason,
- "message": (
- f"🚫 Goal judged unachievable — paused: {reason} "
- "Re-scope with /goal set, or override with /goal resume."
- ),
- }
+ self._pause_state(f"judged unachievable: {reason}")
+ return _decision(
+ "paused", False, None, "blocked", reason,
+ f"🚫 Goal judged unachievable — paused: {reason} "
+ "Re-scope with /goal set, or override with /goal resume.",
+ )
if verdict == "done":
state.status = "done"
- save_goal(self.session_id, state)
- return {
- "status": "done",
- "should_continue": False,
- "continuation_prompt": None,
- "verdict": "done",
- "reason": reason,
- "message": f"✓ Goal achieved: {reason}",
- }
-
- # Auto-pause when the judge cannot reach the API at all N turns in a
- # row (401 auth, DNS failure, timeout). Persistent transport failures
- # signal a broken configuration (e.g. invalid API key), not transient
- # flakiness. Without this guard, a permanently broken judge burns
- # every turn budget slot on an unreachable API.
+ self._save()
+ return _decision("done", False, None, "done", reason, f"✓ Goal achieved: {reason}")
+
if state.consecutive_transport_failures >= DEFAULT_MAX_CONSECUTIVE_TRANSPORT_FAILURES:
- state.status = "paused"
- state.paused_reason = (
+ self._pause_state(
f"judge API unreachable {state.consecutive_transport_failures} turns in a row "
f"(check auxiliary.goal_judge provider/key in config.yaml)"
)
- save_goal(self.session_id, state)
- return {
- "status": "paused",
- "should_continue": False,
- "continuation_prompt": None,
- "verdict": "continue",
- "reason": reason,
- "message": (
- f"⏸ Goal paused — judge API returned errors "
- f"({state.consecutive_transport_failures} turns). "
- "Check the goal_judge provider/key in ~/.hermes/config.yaml:\n"
- " auxiliary:\n"
- " goal_judge:\n"
- " provider: deepseek\n"
- " model: deepseek-v4-flash\n"
- "Then /goal resume to continue."
- ),
- }
-
- # Auto-pause when the judge model can't produce the expected JSON
- # verdict N turns in a row. Points the user at the goal_judge config
- # so they can route this side task to a model that follows the
- # contract (e.g. google/gemini-3-flash-preview). Without this guard,
- # weak judge models burn the entire turn budget returning prose or
- # empty strings.
+ return _decision(
+ "paused", False, None, "continue", reason,
+ f"⏸ Goal paused — judge API returned errors "
+ f"({state.consecutive_transport_failures} turns). "
+ "Check the goal_judge provider/key in ~/.hermes/config.yaml:\n"
+ " auxiliary:\n"
+ " goal_judge:\n"
+ " provider: deepseek\n"
+ " model: deepseek-v4-flash\n"
+ "Then /goal resume to continue.",
+ )
+
if state.consecutive_parse_failures >= DEFAULT_MAX_CONSECUTIVE_PARSE_FAILURES:
- state.status = "paused"
- state.paused_reason = (
+ self._pause_state(
f"judge model returned unparseable output {state.consecutive_parse_failures} turns in a row"
)
- save_goal(self.session_id, state)
- return {
- "status": "paused",
- "should_continue": False,
- "continuation_prompt": None,
- "verdict": "continue",
- "reason": reason,
- "message": (
- f"⏸ Goal paused — the judge model ({state.consecutive_parse_failures} turns) "
- "isn't returning the required JSON verdict. Route the judge to a stricter "
- "model in ~/.hermes/config.yaml:\n"
- " auxiliary:\n"
- " goal_judge:\n"
- " provider: openrouter\n"
- " model: google/gemini-3-flash-preview\n"
- "Then /goal resume to continue."
- ),
- }
+ return _decision(
+ "paused", False, None, "continue", reason,
+ f"⏸ Goal paused — the judge model ({state.consecutive_parse_failures} turns) "
+ "isn't returning the required JSON verdict. Route the judge to a stricter "
+ "model in ~/.hermes/config.yaml:\n"
+ " auxiliary:\n"
+ " goal_judge:\n"
+ " provider: openrouter\n"
+ " model: google/gemini-3-flash-preview\n"
+ "Then /goal resume to continue.",
+ )
if state.turns_used >= state.max_turns:
- state.status = "paused"
- state.paused_reason = f"turn budget exhausted ({state.turns_used}/{state.max_turns})"
- save_goal(self.session_id, state)
- return {
- "status": "paused",
- "should_continue": False,
- "continuation_prompt": None,
- "verdict": "continue",
- "reason": reason,
- "message": (
- f"⏸ Goal paused — {state.turns_used}/{state.max_turns} turns used. "
- "Use /goal resume to keep going, or /goal clear to stop."
- ),
- }
-
- save_goal(self.session_id, state)
- return {
- "status": "active",
- "should_continue": True,
- "continuation_prompt": self.next_continuation_prompt(),
- "verdict": "continue",
- "reason": reason,
- "message": (
- f"↻ Continuing toward goal ({state.turns_used}/{state.max_turns}): {reason}"
- ),
- }
+ return self._budget_pause(state, "continue", reason)
+
+ self._save()
+ return _decision(
+ "active", True, self.next_continuation_prompt(), "continue", reason,
+ f"↻ Continuing toward goal ({state.turns_used}/{state.max_turns}): {reason}",
+ )
def next_continuation_prompt(self) -> Optional[str]:
- if not self._state or self._state.status != "active":
+ s = self._state
+ if not s or s.status != "active":
return None
- # Contract takes priority: it carries the verification surface and
- # constraints the agent must target. Subgoals fold in as extra
- # criteria appended to the contract block.
- if self._state.has_contract():
- contract_block = self._state.contract.render_block()
- if self._state.subgoals:
- extra = "\n".join(
- f"- Extra criterion {i}: {text}"
- for i, text in enumerate(self._state.subgoals, start=1)
- )
- contract_block = f"{contract_block}\n{extra}"
- return CONTINUATION_PROMPT_WITH_CONTRACT_TEMPLATE.format(
- goal=self._state.goal,
- contract_block=contract_block,
- )
- if self._state.subgoals:
+ # Contract first (it carries the verification surface); subgoals fold in as extra criteria.
+ if s.has_contract():
+ contract_block = s.contract.render_block()
+ if s.subgoals:
+ contract_block = f"{contract_block}\n{_render_extra_criteria(s.subgoals)}"
+ return CONTINUATION_PROMPT_WITH_CONTRACT_TEMPLATE.format(goal=s.goal, contract_block=contract_block)
+ if s.subgoals:
return CONTINUATION_PROMPT_WITH_SUBGOALS_TEMPLATE.format(
- goal=self._state.goal,
- subgoals_block=self._state.render_subgoals_block(),
- )
- return CONTINUATION_PROMPT_TEMPLATE.format(goal=self._state.goal)
+ goal=s.goal, subgoals_block=s.render_subgoals_block())
+ return CONTINUATION_PROMPT_TEMPLATE.format(goal=s.goal)
def render_contract(self) -> str:
"""Public helper for the /goal show + /goal draft slash commands."""
@@ -2022,14 +1542,10 @@ class GoalManager:
return self._state.contract.render_block()
-# ──────────────────────────────────────────────────────────────────────
-# Kanban worker goal loop
-# ──────────────────────────────────────────────────────────────────────
+# ── Kanban worker goal loop ───────────────────────────────────────────
-# Continuation prompt fed back to a kanban goal-mode worker that has not
-# yet completed/blocked its task. The card's own acceptance criteria are
-# the goal — the worker already has the full task body in its first turn,
-# so we keep this short and point it back at the lifecycle contract.
+# Fed to a kanban goal-mode worker that hasn't completed/blocked its task yet: short, and points it
+# back at the lifecycle contract (it already has the full task body).
KANBAN_GOAL_CONTINUATION_TEMPLATE = (
"[Continuing toward this kanban task — judge says it is not done yet]\n"
"Reason: {reason}\n\n"
@@ -2041,9 +1557,7 @@ KANBAN_GOAL_CONTINUATION_TEMPLATE = (
"calling one of them."
)
-# Fed when the judge believes the work is done but the worker never called
-# kanban_complete / kanban_block. One explicit nudge to terminate the task
-# the right way before the loop gives up.
+# Judge says done but the worker never called kanban_complete/kanban_block: one explicit nudge.
KANBAN_GOAL_FINALIZE_TEMPLATE = (
"[The work looks complete, but the task is still open]\n"
"Reason: {reason}\n\n"
@@ -2054,6 +1568,17 @@ KANBAN_GOAL_FINALIZE_TEMPLATE = (
)
+# Worker-driven terminal task statuses → loop outcome. The card's own acceptance criteria are the
+# goal; the worker already has the full task body, so these outcomes stop the loop cleanly.
+_KANBAN_TERMINAL_STATUSES = {
+ "done": ("completed_by_worker", "worker completed the task", "task {task_id} completed by worker after {turns} turn(s)"),
+ "blocked": ("blocked_by_worker", "worker blocked the task", "task {task_id} blocked by worker after {turns} turn(s)"),
+ # kanban_request_review is a legitimate terminator: implementation done, awaiting a reviewer.
+ "review": ("review_requested_by_worker", "worker requested review", "task {task_id} handed off for review by worker after {turns} turn(s)"),
+ "changes_requested": ("changes_requested_by_reviewer", "reviewer requested changes", "reviewer returned task {task_id} for changes after {turns} turn(s)"),
+}
+
+
def run_kanban_goal_loop(
*,
task_id: str,
@@ -2067,9 +1592,10 @@ def run_kanban_goal_loop(
) -> Dict[str, Any]:
"""Drive a kanban worker through a Ralph-style goal loop.
- 1. Check whether the worker already terminated the task (called ``kanban_complete`` /
- ``kanban_block``). If so, stop — nothing to do. 2. Otherwise judge the latest response against
- ``goal_text`` (the card's title + body).
+ Each iteration: stop if the worker already terminated the task (``kanban_complete`` /
+ ``kanban_block`` / review hand-off); otherwise judge the latest response against ``goal_text``
+ (the card's title + body) and feed a continuation or finalize nudge. A WAIT verdict is treated
+ as CONTINUE (workers finish via kanban tools, not by parking).
"""
def _log(msg: str) -> None:
@@ -2079,81 +1605,61 @@ def run_kanban_goal_loop(
except Exception:
pass
+ def _block(message: str) -> None:
+ try:
+ block_fn(message)
+ except Exception as exc:
+ _log(f"kanban goal loop: block_fn failed ({exc})")
+
+ def _result(outcome: str, reason: str) -> Dict[str, Any]:
+ return {"outcome": outcome, "turns_used": turns_used, "reason": reason}
+
max_turns = int(max_turns or DEFAULT_MAX_TURNS)
if max_turns < 1:
max_turns = DEFAULT_MAX_TURNS
last_response = first_response or ""
- # The first turn already consumed one unit of budget.
- turns_used = 1
+ turns_used = 1 # the first turn already consumed one unit of budget
nudged_to_finalize = False
while True:
- # Did the worker terminate the task itself this turn?
try:
status = task_status_fn()
except Exception as exc:
_log(f"kanban goal loop: status check failed ({exc}); stopping")
- return {"outcome": "stopped", "turns_used": turns_used, "reason": "status check failed"}
-
- if status == "done":
- _log(f"kanban goal loop: task {task_id} completed by worker after {turns_used} turn(s)")
- return {"outcome": "completed_by_worker", "turns_used": turns_used, "reason": "worker completed the task"}
- if status == "blocked":
- _log(f"kanban goal loop: task {task_id} blocked by worker after {turns_used} turn(s)")
- return {"outcome": "blocked_by_worker", "turns_used": turns_used, "reason": "worker blocked the task"}
- if status == "review":
- # A legitimate worker-driven terminator (kanban_request_review),
- # not an unexpected stop: the implementation is done and the task
- # is awaiting a reviewer. Stop the loop cleanly.
- _log(f"kanban goal loop: task {task_id} handed off for review by worker after {turns_used} turn(s)")
- return {"outcome": "review_requested_by_worker", "turns_used": turns_used, "reason": "worker requested review"}
- if status == "changes_requested":
- _log(f"kanban goal loop: reviewer returned task {task_id} for changes after {turns_used} turn(s)")
- return {"outcome": "changes_requested_by_reviewer", "turns_used": turns_used, "reason": "reviewer requested changes"}
+ return _result("stopped", "status check failed")
+
+ terminal = _KANBAN_TERMINAL_STATUSES.get(status)
+ if terminal is not None:
+ outcome, reason, log_fmt = terminal
+ _log("kanban goal loop: " + log_fmt.format(task_id=task_id, turns=turns_used))
+ return _result(outcome, reason)
if status not in ("running", "ready"):
# Reclaimed / archived / unexpected — let the dispatcher own it.
_log(f"kanban goal loop: task {task_id} status={status!r}; stopping")
- return {"outcome": "stopped", "turns_used": turns_used, "reason": f"status={status}"}
+ return _result("stopped", f"status={status}")
- # Still open — judge whether the latest response satisfies the card.
- # The kanban worker loop has no wait-barrier concept (workers finish
- # via kanban_complete / kanban_block, not by parking), so a WAIT
- # verdict is treated as CONTINUE here.
verdict, reason, _parse_failed, _wait, _transport_failed = judge_goal(goal_text, last_response)
if verdict == "wait":
verdict = "continue"
_log(f"kanban goal loop: turn {turns_used}/{max_turns} verdict={verdict} reason={_truncate(reason, 120)}")
if verdict == "blocked":
- # The judge ruled the goal cannot be satisfied at all — this is
- # NOT done (#100954). Block the card now with the judge's reason
- # instead of spending the remaining turns re-poking an impossible
- # goal, and never let it land in done.
+ # Unachievable is NOT done: block the card with the judge's reason now instead of
+ # re-poking an impossible goal, and never let it land in done.
_log(f"kanban goal loop: task {task_id} judged unachievable; blocking")
- try:
- block_fn(f"Goal-mode judge ruled the goal unachievable: {reason}")
- except Exception as exc:
- _log(f"kanban goal loop: block_fn failed ({exc})")
- return {
- "outcome": "blocked_unachievable",
- "turns_used": turns_used,
- "reason": f"judge verdict blocked: {reason}",
- }
+ _block(f"Goal-mode judge ruled the goal unachievable: {reason}")
+ return _result("blocked_unachievable", f"judge verdict blocked: {reason}")
if verdict == "done":
if nudged_to_finalize:
- # Already asked once to call kanban_complete and it still
- # didn't — block for review rather than spin.
+ # Already asked once to call kanban_complete — block for review rather than spin.
_log(f"kanban goal loop: task {task_id} judged done but worker won't finalize; blocking")
- try:
- block_fn(
- f"Goal-mode worker's output looked complete but it never "
- f"called kanban_complete after a finalize nudge ({reason})."
- )
- except Exception as exc:
- _log(f"kanban goal loop: block_fn failed ({exc})")
- return {"outcome": "blocked_budget", "turns_used": turns_used, "reason": "judged done, never finalized"}
+ _block(
+ f"Goal-mode worker's output looked complete but it never "
+ f"called kanban_complete after a finalize nudge ({reason})."
+ )
+ return _result("blocked_budget", "judged done, never finalized")
prompt = KANBAN_GOAL_FINALIZE_TEMPLATE.format(reason=_truncate(reason, 400))
nudged_to_finalize = True
else:
@@ -2162,22 +1668,18 @@ def run_kanban_goal_loop(
# Budget check BEFORE spending another turn.
if turns_used >= max_turns:
_log(f"kanban goal loop: task {task_id} exhausted {turns_used}/{max_turns} turns; blocking")
- try:
- block_fn(
- f"Goal-mode worker exhausted its turn budget "
- f"({turns_used}/{max_turns}) without completing the task. "
- f"Last judge verdict: {_truncate(reason, 300)}"
- )
- except Exception as exc:
- _log(f"kanban goal loop: block_fn failed ({exc})")
- return {"outcome": "blocked_budget", "turns_used": turns_used, "reason": "turn budget exhausted"}
+ _block(
+ f"Goal-mode worker exhausted its turn budget "
+ f"({turns_used}/{max_turns}) without completing the task. "
+ f"Last judge verdict: {_truncate(reason, 300)}"
+ )
+ return _result("blocked_budget", "turn budget exhausted")
- # Run another turn in the same session.
try:
last_response = run_turn(prompt) or ""
except Exception as exc:
_log(f"kanban goal loop: run_turn failed ({exc}); stopping")
- return {"outcome": "stopped", "turns_used": turns_used, "reason": f"run_turn error: {type(exc).__name__}"}
+ return _result("stopped", f"run_turn error: {type(exc).__name__}")
turns_used += 1