The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Merge origin/main into feat/gateway-health-diagnostics
Victor Kyriazakos6a174e9967b3
diff --cc cron/executions.pyindex d46eaf0d829,fac24357335..4e9b0c7ed78--- a/cron/executions.py+++ b/cron/executions.py@@@ -178,8 -183,7 +202,8 @@@ def recover_interrupted_executions() -"""Mark provably abandoned attempts unknown without scheduling retries."""now = _hermes_now().isoformat()changed = 0+ recovered: List[Dict[str, Any]] = []- with _lock, _connect() as conn:+ with _transaction() as conn:rows = conn.execute("""SELECT id, process_id, pid, process_started_at FROM executionsWHERE status IN ('claimed','running')"""diff --cc cron/jobs.pyindex 00e0d5c40c3,356385cdce7..4b5067b8bc2--- a/cron/jobs.py+++ b/cron/jobs.py@@@ -885,28 -905,64 +923,86 @@@ def get_ticker_success_age() -> Optionareturn _epoch_file_age(store.cron_dir / "ticker_last_success")+def record_catch_up_occurrence() -> None:+ """Increment the profile-local stale-schedule catch-up counter, best effort."""+ path = _current_cron_store().cron_dir / "catch_up_occurrences"+ try:+ try:+ value = int(path.read_text(encoding="utf-8").strip())+ except (OSError, ValueError):+ value = 0+ _atomic_write_counter(path, max(0, value) + 1)+ except Exception:+ pass+++ def record_ticker_error(message: str) -> None:+ """Persist the most recent tick failure so other processes can surface it.++ The ticker thread lives inside the gateway process; ``hermes cron+ status``/``list`` run in a separate process and previously could only+ infer "ticks may be failing" from marker staleness, with no clue WHY.+ A root-owned ``jobs.json`` (#68483) failed every tick for ~14h with the+ reason visible only in the gateway's errors.log. Writing the last error+ next to the heartbeat markers gives the CLI something concrete to show.++ Best-effort: a write failure must never disrupt the tick loop.+ """+ store = _current_cron_store()+ path = store.cron_dir / "ticker_last_error"+ try:+ ensure_dirs()+ fd, tmp_path = tempfile.mkstemp(+ dir=str(path.parent), suffix=".tmp", prefix=".terr_"+ )+ try:+ with os.fdopen(fd, "w", encoding="utf-8") as f:+ f.write(f"{time.time()}\n{message.strip()}\n")+ f.flush()+ os.fsync(f.fileno())+ atomic_replace(tmp_path, path)+ except BaseException:+ try:+ os.unlink(tmp_path)+ except OSError:+ pass+ raise+ except Exception:+ pass+++def get_catch_up_occurrence_count() -> int:+ """Return the profile-local stale-schedule catch-up count."""+ path = _current_cron_store().cron_dir / "catch_up_occurrences"+ try:+ return max(0, int(path.read_text(encoding="utf-8").strip()))+ except (OSError, ValueError):+ return 0+++ def clear_ticker_error() -> None:+ """Remove the last-tick-error marker after a successful tick. Best-effort."""+ store = _current_cron_store()+ try:+ (store.cron_dir / "ticker_last_error").unlink()+ except OSError:+ pass+++ def get_ticker_last_error() -> Optional[str]:+ """Return the most recent recorded tick error message, or None."""+ store = _current_cron_store()+ try:+ raw = (store.cron_dir / "ticker_last_error").read_text(encoding="utf-8")+ except Exception:+ return None+ lines = raw.splitlines()+ if len(lines) < 2:+ return None+ message = "\n".join(lines[1:]).strip()+ return message or None++# =============================================================================# Job CRUD Operations# =============================================================================diff --cc gateway/run.pyindex 600c234537b,2297e264ff2..cd09c39363f--- a/gateway/run.py+++ b/gateway/run.py@@@ -24006,16 -24496,20 +24517,26 @@@ async def start_gateway(config: Optionalogger.debug("MCP tool discovery failed: %s", e)# Start the gateway- success = await runner.start()+ try:+ success = await runner.start()+ except BaseException:+ _shutdown_gateway_health_export(runner)+ raiseif not success:+ _shutdown_gateway_health_export(runner)return False+ # Recover any pending messages flushed during a previous shutdown (#72680).+ try:+ from gateway.shutdown_flush import recover_pending_to_db+ recovered = recover_pending_to_db()+ if recovered:+ logger.info(+ "Recovered %d pending message(s) from shutdown flush", recovered,+ )+ except Exception:+ passif runner.should_exit_cleanly:+ _shutdown_gateway_health_export(runner)if runner.exit_reason:logger.error("Gateway exiting cleanly: %s", runner.exit_reason)# A clean exit that carries an explicit exit code (e.g. a fataldiff --cc tools/async_delegation.pyindex 73b223bfcaf,dbe0b2f1074..702036df0c4--- a/tools/async_delegation.py+++ b/tools/async_delegation.py@@@ -473,41 -533,14 +533,44 @@@ def _get_executor(max_workers: int) ->def active_count() -> int:- """Number of async delegations currently running."""+ """Number of async delegation UNITS currently running.++ A unit is one dispatch: a single subagent OR a whole fan-out batch. A batch+ counts as ONE here because it occupies one async-pool slot (the capacity+ semantics ``dispatch_async_delegation_batch`` relies on). For the count of+ actual concurrent child subagents (batch expanded), use+ ``active_task_count()``.+ """with _records_lock:- return sum(1 for r in _records.values() if r.get("status") in {"running", "finalizing"})+ return sum(+ 1 for r in _records.values()+ if r.get("status") in {"running", "stalling", "finalizing"}+ )+def active_task_count() -> int:+ """Number of async delegation TASKS (child subagents) currently running.++ Unlike ``active_count()`` (units/slots), this expands a batch to its child+ count: a running batch of N tasks contributes N, a single subagent+ contributes 1. This is the truthful "how many subagents are actually+ working right now" figure for observability, where a 3-task batch shown as+ "1" undercounts real concurrent work. Falls back to counting a batch as 1+ if its goal list is missing.+ """+ with _records_lock:+ total = 0+ for r in _records.values():+ if r.get("status") not in {"running", "finalizing"}:+ continue+ if r.get("is_batch"):+ goals = r.get("goals")+ total += len(goals) if isinstance(goals, (list, tuple)) and goals else 1+ else:+ total += 1+ return total++def _new_delegation_id() -> str:return f"deleg_{uuid.uuid4().hex[:8]}"