The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(telemetry): gateway platform health, delivery, first-reply latency and cron run metrics
teknium1f4075a20d62f
diff --git a/cron/executions.py b/cron/executions.pyindex bac8fef9acc..f64945e5608 100644--- a/cron/executions.py+++ b/cron/executions.py@@ -21,6 +21,7 @@ from typing import Any, Dict, Iterator, List, Optionalfrom hermes_constants import get_hermes_homefrom hermes_time import now as _hermes_nowfrom cron.constants import CLAIM_TTL_INACTIVITY_HEADROOM+from hermes_cli.observability.shared_metrics_gateway import record_cron_finish# Optional test override. Production resolves the path at transaction time so dashboard operations# that temporarily enter another profile cannot leak that profile's records into the import-time@@ -303,6 +304,7 @@ def finish_execution(_prune_unlocked(conn)record = _fetch(conn, execution_id)_emit_execution_state(record, delivery_outcome=delivery_outcome)+ record_cron_finish(record, delivery_outcome)return recorddiff --git a/cron/jobs.py b/cron/jobs.pyindex db08e60db93..4ac2b23d680 100644--- a/cron/jobs.py+++ b/cron/jobs.py@@ -36,6 +36,7 @@ logger = logging.getLogger(__name__)from hermes_time import now as _hermes_nowfrom hermes_time import get_timezone+from hermes_cli.observability.shared_metrics_gateway import record_cron_missedfrom utils import atomic_replace, atomic_write_text, fsync_directory# croniter is imported lazily (slow import, only needed for cron exprs). HAS_CRONITER stays a@@ -3112,6 +3113,7 @@ def _fast_forward_missed_recurring(d: _DueJob, grace: int) -> bool:"Job '%s' missed its scheduled time (%s, grace=%ds). ""Skipping missed occurrence because cron.catch_up_missed is false; next run: %s",d.label, d.next_run, grace, new_next)+ record_cron_missed(d.job)return Truelogger.info("Job '%s' missed its scheduled time (%s, grace=%ds). "@@ -3133,6 +3135,7 @@ def _retire_expired_oneshot(d: _DueJob) -> bool:if not (d.job.get("run_claim") or d.job.get("fire_claim")):_write_missed_oneshot_diagnostic(d.job, d.next_run)d.scan.retire(d.job["id"])+ record_cron_missed(d.job)return Truediff --git a/cron/scheduler.py b/cron/scheduler.pyindex c8d5495ecfc..b22cabe2264 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -36,6 +36,7 @@ from typing import Any, Callable, Dict, List, Optional, Protocol, Unionsys.path.insert(0, str(Path(__file__).parent.parent))from hermes_constants import get_hermes_home, hermes_home_key+from hermes_cli.observability.shared_metrics_gateway import note_cron_execution, note_cron_skippedfrom cron.env_settings import cron_env_settingfrom hermes_cli._subprocess_compat import windows_hide_flagsfrom hermes_cli.config import (@@ -2216,6 +2217,7 @@ def _prepare_job_prompt(_ran_ok, _script_output = prerun_scriptif _ran_ok and not _parse_wake_gate(_script_output):logger.info("Job '%s' (ID: %s): wakeAgent=false, skipping agent run", job_name, job_id)+ note_cron_skipped(job)silent_doc = (f"# Cron Job: {job_name}\n\n"f"**Job ID:** {job_id}\n"@@ -2250,6 +2252,7 @@ def _prepare_job_prompt(return (False, blocked_doc, "", str(block_exc)), Noneif prompt is None:logger.info("Job '%s': script produced no output, skipping AI call.", job_name)+ note_cron_skipped(job)return (True, "", SILENT_MARKER, None), Nonereturn None, prompt@@ -2720,6 +2723,7 @@ def run_one_job(job["execution_id"] = execution["id"]execution_id = str(job["execution_id"])+ note_cron_execution(job)external_owner = os.environ.get("_HERMES_CRON_EXTERNAL_WORKER") == execution_idif not external_owner:try:@@ -4118,6 +4122,7 @@ def _submit_with_guard(job: dict, pool: concurrent.futures.ThreadPoolExecutor, pexecution = create_execution(job_id, source="builtin", scheduled_instant=job.get("_scheduled_instant"))dispatched_job = dict(job, execution_id=execution["id"])+ note_cron_execution(dispatched_job)_ctx = contextvars.copy_context()except Exception as execution_err:# Release the claim so the next tick retries instead of wedging "already running".diff --git a/gateway/platforms/base.py b/gateway/platforms/base.pyindex 1cbcb8969ba..e72d98b7aec 100644--- a/gateway/platforms/base.py+++ b/gateway/platforms/base.py@@ -423,6 +423,7 @@ from gateway.platforms.base_exec_approval import (EA_HEADER_TEXT, EA_REASON_LABEL_TEXT, approval_timeout_seconds, format_approval_deadline_line)from gateway.platforms.event import MessageEvent, MessageType, ProcessingOutcomefrom gateway.warning_notifications import diagnostic_wake_muted+from hermes_cli.observability.shared_metrics_gateway import records_delivery, stop_reply_clockfrom gateway.session import SessionSource, build_session_keyfrom gateway.session_transcript import TranscriptReadErrorfrom hermes_constants import get_default_hermes_root, get_hermes_dir, get_hermes_home@@ -3567,6 +3568,7 @@ class BasePlatformAdapter(ABC):return live_adapterreturn self+ @records_deliveryasync def _send_with_retry(self, chat_id: str, content: str, reply_to: Optional[str] = None, metadata: Any = None,max_retries: int = 2, base_delay: float = 2.0) -> "SendResult":@@ -4299,6 +4301,7 @@ class BasePlatformAdapter(ABC):await self._release_turn_marker(event) # the ledger now owns the crash recoveryresult = await delivery_adapter._send_with_retry(chat_id=event.source.chat_id, content=text_content, reply_to=reply_to, metadata=metadata)+ stop_reply_clock(delivery_adapter, event.source.chat_id, result)if obligation_id is not None:await self._finalize_delivery_obligation(obligation_id, result, event, delivery_adapter)return result, delivery_adapterdiff --git a/gateway/run_adapters.py b/gateway/run_adapters.pyindex c74fd180606..64d2659d459 100644--- a/gateway/run_adapters.py+++ b/gateway/run_adapters.py@@ -25,6 +25,7 @@ from gateway.platforms.helpers import carry_inbound_dedup, inbound_dedup_cachesfrom gateway.restart import is_global_startup_conflictfrom gateway.run_shutdown import _log_suppressedfrom gateway.session import SessionSource+from hermes_cli.observability.shared_metrics_gateway import record_platform_connect, record_platform_disconnectfrom pathlib import Pathfrom typing import Any, Awaitable, Callable, Dict, Optional@@ -174,6 +175,15 @@ class GatewayAdapterLifecycleMixin:``initial`` selects the capped cold-start budget for platforms whose full connect budget is too longto spend before the gateway reaches ``running`` (#85993 — Telegram's 180s)."""+ try:+ ok = await self._connect_adapter_bounded(adapter, platform, is_reconnect=is_reconnect, initial=initial)+ except Exception as exc:+ record_platform_connect(adapter, platform, is_reconnect=is_reconnect, ok=False, exc=exc)+ raise+ record_platform_connect(adapter, platform, is_reconnect=is_reconnect, ok=bool(ok))+ return ok++ async def _connect_adapter_bounded(self, adapter, platform, *, is_reconnect: bool, initial: bool) -> bool:timeout = self._platform_connect_timeout_secs(platform, initial=initial)if timeout <= 0:return await adapter.connect(is_reconnect=is_reconnect)@@ -340,6 +350,7 @@ class GatewayAdapterLifecycleMixin:error_message=adapter.fatal_error_message,)if existing is adapter:+ record_platform_disconnect(adapter)# Claim for teardown BEFORE awaiting disconnect(), else a second fatal disconnects it twice.self.adapters.pop(adapter.platform, None)self.delivery_router.adapters = self.adaptersdiff --git a/gateway/run_inbound.py b/gateway/run_inbound.pyindex 638960da4b3..a137e6324a8 100644--- a/gateway/run_inbound.py+++ b/gateway/run_inbound.py@@ -1389,6 +1389,8 @@ class GatewayInboundMixin:_claim_state.turn.agent = _AGENT_PENDING_SENTINEL_claim_state.turn.event = event_claim_state.turn.started_ts = time.time()+ from hermes_cli.observability.shared_metrics_gateway import start_reply_clock+ start_reply_clock(source, internal=is_internal)self._persist_active_agents()_run_generation = self._begin_session_run_generation(_quick_key)diff --git a/gateway/stream_consumer_transport.py b/gateway/stream_consumer_transport.pyindex 773099436b4..3be6b06a524 100644--- a/gateway/stream_consumer_transport.py+++ b/gateway/stream_consumer_transport.py@@ -13,6 +13,7 @@ from typing import Any, Optionalfrom gateway.platforms.base import BasePlatformAdapter as _BasePlatformAdapterfrom gateway.stream_consumer_fences import ensure_closed_code_fences+from hermes_cli.observability.shared_metrics_gateway import stops_reply_clocklogger = logging.getLogger("gateway.stream_consumer")@@ -308,6 +309,7 @@ class StreamTransportMixin:self._message_id = "__no_edit__"self._message_created_ts = None+ @stops_reply_clockasync def _send_or_edit(self, text: str, *, finalize: bool = False, is_turn_final: bool = True) -> bool:"""Send or edit the streaming message; True if delivered. ``finalize`` marks thediff --git a/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.json b/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.jsonindex db84302aab3..3e46c7e5498 100644--- a/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.json+++ b/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.json@@ -162,6 +162,18 @@},{"$ref": "#/$defs/execution_backend_counter"+ },+ {+ "$ref": "#/$defs/platform_health_counter"+ },+ {+ "$ref": "#/$defs/platform_delivery_counter"+ },+ {+ "$ref": "#/$defs/reply_latency_counter"+ },+ {+ "$ref": "#/$defs/cron_run_counter"}]}@@ -405,7 +417,7 @@"$ref": "#/$defs/execution_surface"},"platform": {- "$ref": "#/$defs/vocabulary_identifier"+ "$ref": "#/$defs/catalog_identifier"}}},@@ -496,7 +508,7 @@"$ref": "#/$defs/count_bucket"},"platform": {- "$ref": "#/$defs/vocabulary_identifier"+ "$ref": "#/$defs/catalog_identifier"},"failure_class": {"$ref": "#/$defs/vocabulary_identifier"@@ -1065,7 +1077,7 @@]},"platform": {- "$ref": "#/$defs/vocabulary_identifier"+ "$ref": "#/$defs/catalog_identifier"},"turn_count_bucket": {"$ref": "#/$defs/size_bucket"@@ -1735,6 +1747,210 @@"type": "string","pattern": "^[a-z0-9][a-z0-9_.-]{0,63}$","description": "A public name Nous publishes (slash-command registry, bundled/optional skills, optional-mcps/ and plugin-catalog/ entries, shipped locales), or the placeholder custom/plugin/skill/unknown/other."+ },+ "platform_health_counter": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "type",+ "dimensions",+ "value"+ ],+ "properties": {+ "name": {+ "const": "hermes.platform.health"+ },+ "type": {+ "const": "counter"+ },+ "dimensions": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "error_class",+ "event",+ "platform"+ ],+ "properties": {+ "error_class": {+ "enum": [+ "auth",+ "config",+ "network",+ "none",+ "other",+ "rate_limited"+ ]+ },+ "event": {+ "enum": [+ "connect_failed",+ "connect_ok",+ "disconnect",+ "reconnect"+ ]+ },+ "platform": {+ "$ref": "#/$defs/catalog_identifier"+ }+ }+ },+ "value": {+ "type": "integer",+ "minimum": 1+ }+ }+ },+ "platform_delivery_counter": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "type",+ "dimensions",+ "value"+ ],+ "properties": {+ "name": {+ "const": "hermes.platform.delivery"+ },+ "type": {+ "const": "counter"+ },+ "dimensions": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "failure_class",+ "outcome",+ "platform"+ ],+ "properties": {+ "failure_class": {+ "enum": [+ "auth",+ "forbidden",+ "network",+ "none",+ "other",+ "rate_limited",+ "too_long"+ ]+ },+ "outcome": {+ "enum": [+ "failed",+ "sent"+ ]+ },+ "platform": {+ "$ref": "#/$defs/catalog_identifier"+ }+ }+ },+ "value": {+ "type": "integer",+ "minimum": 1+ }+ }+ },+ "reply_latency_counter": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "type",+ "dimensions",+ "value"+ ],+ "properties": {+ "name": {+ "const": "hermes.gateway.reply_latency"+ },+ "type": {+ "const": "counter"+ },+ "dimensions": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "first_response_bucket",+ "platform"+ ],+ "properties": {+ "first_response_bucket": {+ "enum": [+ "15s_to_60s",+ "2s_to_5s",+ "5s_to_15s",+ "gte_60s",+ "lt_2s"+ ]+ },+ "platform": {+ "$ref": "#/$defs/catalog_identifier"+ }+ }+ },+ "value": {+ "type": "integer",+ "minimum": 1+ }+ }+ },+ "cron_run_counter": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "type",+ "dimensions",+ "value"+ ],+ "properties": {+ "name": {+ "const": "hermes.cron.run"+ },+ "type": {+ "const": "counter"+ },+ "dimensions": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "delivery_kind",+ "duration_bucket",+ "outcome"+ ],+ "properties": {+ "delivery_kind": {+ "enum": [+ "local",+ "none",+ "other",+ "platform",+ "webhook"+ ]+ },+ "duration_bucket": {+ "$ref": "#/$defs/duration_bucket"+ },+ "outcome": {+ "enum": [+ "failed",+ "missed",+ "skipped",+ "success"+ ]+ }+ }+ },+ "value": {+ "type": "integer",+ "minimum": 1+ }+ }}}}diff --git a/hermes_cli/observability/shared_metrics_catalog.py b/hermes_cli/observability/shared_metrics_catalog.pyindex cdbf0578c09..0f83ce8b998 100644--- a/hermes_cli/observability/shared_metrics_catalog.py+++ b/hermes_cli/observability/shared_metrics_catalog.py@@ -101,6 +101,68 @@ def user_named_model_providers() -> frozenset[str]:) | {CUSTOM}+# ---- v4 gateway ----+def bundled_platform_names() -> frozenset[str]:+ """Messaging platforms Hermes ships as ``plugins/platforms/<name>`` (the dir is the registered name)."""+ root = _REPO_ROOT / "plugins" / "platforms"+ try:+ return frozenset(p.name.lower() for p in root.iterdir() if (p / "plugin.yaml").is_file())+ except OSError:+ return frozenset()+++def catalog_platform_names() -> frozenset[str]:+ """``plugin-catalog/`` entries whose category is ``platform`` (in-tree only: never a network fetch)."""+ from hermes_cli.plugin_catalog import CATALOG_TIERS, load_catalog++ return frozenset(e.name for e in load_catalog() if e.category == "platform" and e.tier in CATALOG_TIERS)+++def platform_metric_name(raw: object, core: frozenset[str]) -> str:+ """A messaging platform's public name: a core or bundled platform's own name, the catalog entry+ name of the installed catalog plugin that registered it, else ``plugin``. ``core`` is the+ contract's static platform vocabulary."""+ name = _norm(getattr(raw, "value", raw))+ if name in core or name in _safe(bundled_platform_names):+ return name+ if not name:+ return "plugin"+ from hermes_constants import get_hermes_home++ return _catalog_platform_owner(str(get_hermes_home()), name) or "plugin"++[email protected]_cache(maxsize=64)+def _catalog_platform_owner(home: str, platform: str) -> str | None:+ """The catalog entry that installed the plugin registering ``platform`` in this profile. The+ plugin is located from where its adapter factory's code lives (not a name it could claim), and+ the catalog install is proven only by the installer-owned ``.install-metadata.json`` record,+ never by anything inside the plugin tree, so a URL install cannot claim a catalog name."""+ try:+ import inspect++ from gateway.platform_registry import platform_registry+ from hermes_cli.plugins_provenance import read_sidecar_rows++ entry = platform_registry.get(platform)+ if entry is None or getattr(entry, "source", "") != "plugin":+ return None+ plugins_dir = (Path(home) / "plugins").resolve()+ code_path = Path(inspect.getfile(entry.adapter_factory)).resolve()+ if not code_path.is_relative_to(plugins_dir) or code_path.parent == plugins_dir:+ return None+ row = read_sidecar_rows(plugins_dir).get(code_path.relative_to(plugins_dir).parts[0])+ row = row if isinstance(row, dict) else {}+ block = row.get("catalog")+ name = _norm(block.get("name") if isinstance(block, dict) else row.get("catalog_name"))+ return name if name in _safe(catalog_platform_names) else None+ except Exception:+ logger.debug("Shared-metrics platform provenance unavailable", exc_info=True)+ return None++def _norm(value: object) -> str:return value.strip().lower() if isinstance(value, str) else ""diff --git a/hermes_cli/observability/shared_metrics_contract.py b/hermes_cli/observability/shared_metrics_contract.pyindex 62f72c72345..9e8ee9cf9ee 100644--- a/hermes_cli/observability/shared_metrics_contract.py+++ b/hermes_cli/observability/shared_metrics_contract.py@@ -124,7 +124,7 @@ TASK_FAILURE_CLASSES = MODEL_ERROR_CLASSES | frozenset({"repeated_errors", "restart_limit", "session_busy", "shutdown",})# Surfaces that are not messaging platforms keep their own execution_surface value.-GATEWAY_PLATFORMS = (frozenset(PLATFORMS) - {"api_server", "cli", "cron"}) | {"none", "plugin"}+_CORE_GATEWAY_PLATFORMS = (frozenset(PLATFORMS) - {"api_server", "cli", "cron"}) | {"none", "plugin"}TOOL_NAMES = BUILTIN_TOOL_NAMES | {"mcp", "plugin", "unknown"}TOOL_ERROR_CLASSES = frozenset({"blocked", "contract_violation", "exception", "interrupted", "invalid_arguments", "none",@@ -216,6 +216,24 @@ EXECUTION_BACKENDS_BY_KIND = {EXECUTION_BACKENDS = BROWSER_BACKENDS | CODE_BACKENDS | TERMINAL_BACKENDSEXECUTION_OUTCOMES = frozenset({"failed", "success"})# ---- end v4 loop ----+# ---- v4 gateway ----+PLATFORM_HEALTH_MARK = PLATFORM_HEALTH_METRIC = "hermes.platform.health"+PLATFORM_DELIVERY_MARK = PLATFORM_DELIVERY_METRIC = "hermes.platform.delivery"+REPLY_LATENCY_MARK = REPLY_LATENCY_METRIC = "hermes.gateway.reply_latency"+CRON_RUN_MARK = CRON_RUN_METRIC = "hermes.cron.run"+# Plugin platforms are named only when Nous ships them (plugins/platforms/) or the installer proved a+# plugin-catalog install (shared_metrics_catalog.platform_metric_name); every other one is ``plugin``.+_PLATFORM_CATALOGS = ("bundled_platform_names", "catalog_platform_names")+GATEWAY_PLATFORMS = _CatalogValues(*_PLATFORM_CATALOGS, extra=_CORE_GATEWAY_PLATFORMS)+# The API server is an adapter the gateway connects and delivers through, but not a messaging surface.+ADAPTER_PLATFORMS = _CatalogValues(*_PLATFORM_CATALOGS, extra=_CORE_GATEWAY_PLATFORMS | {"api_server"})+PLATFORM_HEALTH_EVENTS = frozenset({"connect_ok", "connect_failed", "reconnect", "disconnect"})+PLATFORM_ERROR_CLASSES = frozenset({"none", "auth", "network", "rate_limited", "config", "other"})+DELIVERY_OUTCOMES = frozenset({"sent", "failed"})+DELIVERY_FAILURE_CLASSES = frozenset({"none", "rate_limited", "too_long", "auth", "network", "forbidden", "other"})+REPLY_LATENCY_BUCKETS = frozenset({"lt_2s", "2s_to_5s", "5s_to_15s", "15s_to_60s", "gte_60s"})+CRON_RUN_OUTCOMES = frozenset({"success", "failed", "missed", "skipped"})+CRON_DELIVERY_KINDS = frozenset({"local", "platform", "webhook", "none", "other"})_ARCHITECTURE_ALIASES = {"amd64": "x86_64", "x64": "x86_64", "x86_64": "x86_64",@@ -374,6 +392,17 @@ _COUNTER_DIMENSION_VALUES: dict[str, dict[str, frozenset[str]]] = {"outcome": EXECUTION_OUTCOMES,},# ---- end v4 loop ----+ # ---- v4 gateway ----+ PLATFORM_HEALTH_METRIC: {+ "error_class": PLATFORM_ERROR_CLASSES, "event": PLATFORM_HEALTH_EVENTS, "platform": ADAPTER_PLATFORMS,+ },+ PLATFORM_DELIVERY_METRIC: {+ "failure_class": DELIVERY_FAILURE_CLASSES, "outcome": DELIVERY_OUTCOMES, "platform": ADAPTER_PLATFORMS,+ },+ REPLY_LATENCY_METRIC: {"first_response_bucket": REPLY_LATENCY_BUCKETS, "platform": ADAPTER_PLATFORMS},+ CRON_RUN_METRIC: {+ "delivery_kind": CRON_DELIVERY_KINDS, "duration_bucket": DURATION_BUCKETS, "outcome": CRON_RUN_OUTCOMES,+ },}_MODEL_ROUTE_MAX_LENGTHS = {"model": MODEL_IDENTIFIER_MAX_LENGTH, "provider": PROVIDER_IDENTIFIER_MAX_LENGTH,@@ -421,6 +450,9 @@ _DECISION_MARK_METRICS = {MEMORY_OP_MARK: MEMORY_OP_METRIC, CURATOR_RUN_MARK: CURATOR_RUN_METRIC,DELEGATION_RUN_MARK: DELEGATION_RUN_METRIC, EXECUTION_BACKEND_MARK: EXECUTION_BACKEND_METRIC,# ---- end v4 loop ----+ # ---- v4 gateway ----+ PLATFORM_HEALTH_MARK: PLATFORM_HEALTH_METRIC, PLATFORM_DELIVERY_MARK: PLATFORM_DELIVERY_METRIC,+ REPLY_LATENCY_MARK: REPLY_LATENCY_METRIC, CRON_RUN_MARK: CRON_RUN_METRIC,}@@ -718,11 +750,19 @@ def task_start_fields(kwargs: dict[str, Any]) -> dict[str, str]:def gateway_platform(kwargs: dict[str, Any], surface: str | None = None) -> str:- """The built-in messaging platform for a gateway task; plugin platforms stay anonymous."""+ """The messaging platform for a gateway task: core, bundled or proven catalog plugin platforms+ by name, every other plugin platform anonymous."""if (surface or execution_surface(kwargs)) != "gateway":return "none"- value = _norm(kwargs.get("platform"))- return value if value in GATEWAY_PLATFORMS else "plugin"+ name = adapter_platform(kwargs.get("platform"))+ return name if name in GATEWAY_PLATFORMS else "plugin"+++def adapter_platform(value: Any) -> str:+ """Public name of a gateway adapter's platform (Platform enum or its value)."""+ from .shared_metrics_catalog import platform_metric_name++ return platform_metric_name(value, _CORE_GATEWAY_PLATFORMS | {"api_server"})_SURFACE_ENTRYPOINTS = {diff --git a/hermes_cli/observability/shared_metrics_gateway.py b/hermes_cli/observability/shared_metrics_gateway.pynew file mode 100644index 00000000000..b38fa108112--- /dev/null+++ b/hermes_cli/observability/shared_metrics_gateway.py@@ -0,0 +1,377 @@+"""Call-site API for messaging-gateway and cron shared metrics.++Platform connection health, outbound delivery outcomes, first-reply latency and cron runs happen on+the gateway event loop, adapter tasks or the cron ticker, never inside a model or tool call. Every+recorder takes RAW runtime objects, derives only closed classes / buckets / public platform names,+and hands the recording to one background worker so the caller's loop never waits on the first+runtime build or a config read. The worker runs in a copy of the caller's context, so the profile+the caller was scoped to (gateway multiplex, cron ``_profile_cron_scope``) owns the row.++This module is imported by ``gateway/platforms/base.py`` at class-definition time: keep imports lazy.+"""++from __future__ import annotations++import contextvars+import functools+import logging+import threading+import time+from collections import OrderedDict+from concurrent.futures import Future, ThreadPoolExecutor+from datetime import datetime+from typing import Any, Callable++logger = logging.getLogger(__name__)++_executor: ThreadPoolExecutor | None = None+_executor_lock = threading.Lock()+++def _submit(fn: Callable[..., Any], *args: Any, **kwargs: Any) -> Future | None:+ """Fire-and-forget: run ``fn`` on the metrics worker in the caller's context (profile scope)."""+ global _executor+ try:+ with _executor_lock:+ if _executor is None:+ _executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="hermes-gateway-metrics")+ return _executor.submit(contextvars.copy_context().run, _guarded, fn, *args, **kwargs)+ except Exception: # interpreter shutdown refuses new work: the metric is simply dropped+ logger.debug("Gateway shared metric not scheduled", exc_info=True)+ return None+++def _guarded(fn: Callable[..., Any], *args: Any, **kwargs: Any) -> None:+ try:+ fn(*args, **kwargs)+ except Exception:+ logger.debug("Gateway shared metric not recorded", exc_info=True)+++def drain(timeout: float = 5.0) -> None:+ """Wait for queued recordings (tests and live probes; the worker is FIFO)."""+ future = _submit(lambda: None)+ if future is not None:+ future.result(timeout=timeout)+++def _emit(mark_name: str, build: Callable[..., dict[str, str] | None], **raw: Any) -> None:+ from . import shared_metrics_contract as contract+ from .shared_metrics_events import _emit as emit++ emit(getattr(contract, mark_name), build, **raw)+++def _platform(value: Any) -> str:+ from .shared_metrics_contract import adapter_platform++ return adapter_platform(getattr(value, "platform", value))+++# ---- classification (closed classes from exception types, HTTP statuses and Hermes's own codes) ----++_STATUS_CLASSES = {401: "auth", 403: "forbidden", 413: "too_long", 429: "rate_limited"}+# Adapter fatal codes are Hermes-authored identifiers (``telegram_auth_error``); first match wins, so+# "missing credentials" reads as configuration, not a rejected credential.+_CODE_CLASSES = (+ (("missing", "dependency", "npm", "config", "conflict", "lock", "bind"), "config"),+ (("auth", "credential", "token", "unauthor", "forbidden", "login"), "auth"),+ (("ratelimit", "rate_limit", "flood", "too_many", "toomany", "429"), "rate_limited"),+ (("network", "connect", "timeout", "socket", "dns", "ssl", "lost", "exited", "stream"), "network"),+)+_SEND_KIND_CLASSES = {+ "too_long": "too_long", "forbidden": "forbidden", "rate_limited": "rate_limited", "transient": "network",+}+++def _status_code(exc: BaseException | None) -> int | None:+ for holder in (exc, getattr(exc, "response", None)):+ for attr in ("status_code", "status", "code"):+ value = getattr(holder, attr, None)+ if isinstance(value, int) and not isinstance(value, bool) and 100 <= value <= 599:+ return value+ return None+++def _code_class(code: Any) -> str | None:+ text = str(code or "").strip().lower()+ if not text:+ return None+ return next((cls for needles, cls in _CODE_CLASSES if any(n in text for n in needles)), "other")+++def _exception_class(exc: BaseException | None) -> str:+ """Connection error class from the exception's type and HTTP status only (never its message)."""+ if exc is None:+ return "other"+ status = _status_code(exc)+ if status in (401, 403):+ return "auth"+ if status == 429:+ return "rate_limited"+ if isinstance(exc, ImportError):+ return "config"+ if isinstance(exc, (TimeoutError, ConnectionError)):+ return "network"+ names = "".join(cls.__name__.lower() for cls in type(exc).__mro__[:-1])+ # Type names say auth / rate / network; "configuration" is only ever a Hermes fatal code.+ return next((cls for needles, cls in _CODE_CLASSES[1:] if any(n in names for n in needles)), "other")+++def connect_error_class(*, exc: BaseException | None = None, fatal_code: Any = None) -> str:+ if fatal_code:+ return _code_class(fatal_code) or "other"+ return _exception_class(exc)+++def delivery_failure_class(result: Any = None, exc: BaseException | None = None) -> str:+ """Why an outbound delivery failed, from the SendResult's typed fields or the exception type."""+ if exc is not None:+ status = _STATUS_CLASSES.get(_status_code(exc) or 0)+ if status is not None:+ return status+ cls = _exception_class(exc)+ return cls if cls in {"auth", "network", "rate_limited"} else "other"+ raw = getattr(result, "raw_response", None)+ status = raw.get("status_code", raw.get("status")) if isinstance(raw, dict) else None+ if isinstance(status, int) and status in _STATUS_CLASSES:+ return _STATUS_CLASSES[status]+ if getattr(result, "retry_after", None) is not None:+ return "rate_limited"+ kind = getattr(result, "error_kind", None)+ if kind is None:+ from gateway.platforms.base import classify_send_error++ kind = classify_send_error(None, str(getattr(result, "error", "") or ""))+ if kind in _SEND_KIND_CLASSES:+ return _SEND_KIND_CLASSES[kind]+ return "network" if getattr(result, "retryable", False) else "other"+++# ---- hermes.platform.health ----++def platform_health_fields(*, platform: Any, event: str, error_class: str) -> dict[str, str] | None:+ from . import shared_metrics_contract as contract++ if event not in contract.PLATFORM_HEALTH_EVENTS:+ return None+ ok = event in {"connect_ok", "reconnect"}+ return {+ "error_class": "none" if ok else error_class if error_class in contract.PLATFORM_ERROR_CLASSES else "other",+ "event": event,+ "platform": _platform(platform),+ }+++def record_platform_connect(+ adapter: Any, platform: Any, *, is_reconnect: bool, ok: bool, exc: BaseException | None = None,+) -> None:+ """One adapter connect attempt (cold start or reconnect watcher), from the runner's single+ connect seam. A failed attempt is ``connect_failed`` whichever path made it."""+ event = ("reconnect" if is_reconnect else "connect_ok") if ok else "connect_failed"+ error_class = "none" if ok else connect_error_class(+ exc=exc, fatal_code=None if exc is not None else getattr(adapter, "fatal_error_code", None))+ _submit(_emit, "PLATFORM_HEALTH_MARK", platform_health_fields,+ platform=platform, event=event, error_class=error_class)+++def record_platform_disconnect(adapter: Any) -> None:+ """A live adapter lost its connection after startup (its fatal-error handler owned it)."""+ _submit(_emit, "PLATFORM_HEALTH_MARK", platform_health_fields, platform=adapter, event="disconnect",+ error_class=connect_error_class(fatal_code=getattr(adapter, "fatal_error_code", None)))+++# ---- hermes.platform.delivery + hermes.gateway.reply_latency ----++def delivery_fields(*, platform: Any, failure_class: str) -> dict[str, str]:+ from . import shared_metrics_contract as contract++ return {+ "failure_class": failure_class if failure_class in contract.DELIVERY_FAILURE_CLASSES else "other",+ "outcome": "sent" if failure_class == "none" else "failed",+ "platform": _platform(platform),+ }+++def records_delivery(send: Callable[..., Any]) -> Callable[..., Any]:+ """Count one logical outbound delivery (all retries and the plain-text fallback included) per+ call of the wrapped ``_send_with_retry`` (replies, busy acks, command replies alike)."""++ @functools.wraps(send)+ async def wrapper(self, *args: Any, **kwargs: Any) -> Any:+ try:+ result = await send(self, *args, **kwargs)+ except Exception as exc:+ _submit(_emit, "PLATFORM_DELIVERY_MARK", delivery_fields,+ platform=self, failure_class=delivery_failure_class(exc=exc))+ raise+ success = getattr(result, "success", None)+ if isinstance(success, bool):+ _submit(_emit, "PLATFORM_DELIVERY_MARK", delivery_fields, platform=self,+ failure_class="none" if success else delivery_failure_class(result))+ return result++ return wrapper+++def stops_reply_clock(send_or_edit: Callable[..., Any]) -> Callable[..., Any]:+ """Stream consumer transport: the first delivered visible text (frame, draft or message)."""++ @functools.wraps(send_or_edit)+ async def wrapper(self, *args: Any, **kwargs: Any) -> Any:+ ok = await send_or_edit(self, *args, **kwargs)+ if ok is True and getattr(self, "_last_sent_text", None):+ stop_reply_clock(getattr(self, "adapter", None), getattr(self, "chat_id", None))+ return ok++ return wrapper+++_REPLY_THRESHOLDS = ((2.0, "lt_2s"), (5.0, "2s_to_5s"), (15.0, "5s_to_15s"), (60.0, "15s_to_60s"))+_REPLY_CLOCK_MAX = 1024+_REPLY_CLOCK_MAX_AGE = 3600.0+# (platform value, chat id) -> (monotonic start, owning Hermes home). Keyed without the profile: the+# send side may run outside the turn's scope, so the start side records whose row it is.+_reply_clocks: OrderedDict[tuple[str, str], tuple[float, str]] = OrderedDict()+_reply_lock = threading.Lock()+++def _clock_key(platform: Any, chat_id: Any) -> tuple[str, str] | None:+ value = str(getattr(platform, "value", platform) or "")+ return (value, str(chat_id)) if value and chat_id not in (None, "") else None+++def start_reply_clock(source: Any, *, internal: bool = False) -> None:+ """An inbound user message was accepted as a new agent turn (internal events never are)."""+ key = None if internal else _clock_key(getattr(source, "platform", None), getattr(source, "chat_id", None))+ if key is None:+ return+ from hermes_constants import get_hermes_home++ with _reply_lock:+ _reply_clocks.pop(key, None)+ _reply_clocks[key] = (time.monotonic(), str(get_hermes_home()))+ while len(_reply_clocks) > _REPLY_CLOCK_MAX:+ _reply_clocks.popitem(last=False)+++def stop_reply_clock(adapter: Any, chat_id: Any, result: Any = None) -> None:+ """First outbound text for the chat's pending turn (stream first chunk or the final reply; busy+ acks and command replies never stop it). ``result``: a failed send is not a reply."""+ key = _clock_key(getattr(adapter, "platform", None), chat_id)+ if key is None or (result is not None and getattr(result, "success", False) is not True):+ return+ with _reply_lock:+ started = _reply_clocks.pop(key, None)+ # A turn that ended without a reply leaves its clock behind; an unrelated send hours later+ # must not be read as that turn's reply.+ if started is not None and time.monotonic() - started[0] <= _REPLY_CLOCK_MAX_AGE:+ _submit(_record_reply_latency, adapter, time.monotonic() - started[0], started[1])+++def reply_latency_fields(*, platform: Any, seconds: float) -> dict[str, str]:+ from .shared_metrics_contract import _bucket++ return {+ "first_response_bucket": _bucket(max(0.0, seconds), _REPLY_THRESHOLDS, "gte_60s"),+ "platform": _platform(platform),+ }+++def _record_reply_latency(adapter: Any, seconds: float, home: str) -> None:+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override++ token = set_hermes_home_override(home)+ try:+ _emit("REPLY_LATENCY_MARK", reply_latency_fields, platform=adapter, seconds=seconds)+ finally:+ reset_hermes_home_override(token)+++# ---- hermes.cron.run ----++_CRON_NOTES_MAX = 512+# execution id -> delivery kind, noted where the job dict is in hand; popped once at the terminal write.+_cron_delivery: OrderedDict[str, str] = OrderedDict()+_cron_skipped: set[str] = set()+_cron_lock = threading.Lock()+_LOCAL_DELIVERY = frozenset({"local", ""})+++def cron_delivery_kind(job: Any) -> str:+ """Where a job's output goes, as a closed kind; targets themselves never leave the machine."""+ if not isinstance(job, dict):+ return "other"+ deliver = job.get("deliver")+ parts = deliver if isinstance(deliver, (list, tuple)) else str(deliver or "").split(",")+ kinds = {str(p).strip().lower().split(":", 1)[0] for p in parts} - {""}+ if not kinds or kinds <= _LOCAL_DELIVERY:+ return "local"+ if kinds & {"none", "off"}:+ return "none"+ return "webhook" if kinds == {"webhook"} else "platform"+++def note_cron_execution(job: Any) -> None:+ """Remember the delivery kind of an execution about to run (or be refused) in this process."""+ execution_id = job.get("execution_id") if isinstance(job, dict) else None+ if not execution_id:+ return+ with _cron_lock:+ _cron_delivery[str(execution_id)] = cron_delivery_kind(job)+ while len(_cron_delivery) > _CRON_NOTES_MAX:+ _cron_delivery.popitem(last=False)+++def note_cron_skipped(job: Any) -> None:+ """A gate (pre-run script ``wakeAgent=false`` / no output) decided this run does no agent work."""+ execution_id = job.get("execution_id") if isinstance(job, dict) else None+ if execution_id:+ with _cron_lock:+ if len(_cron_skipped) < _CRON_NOTES_MAX:+ _cron_skipped.add(str(execution_id))+++def _iso_seconds(start: Any, end: Any) -> float:+ try:+ return max(0.0, (datetime.fromisoformat(str(end)) - datetime.fromisoformat(str(start))).total_seconds())+ except (TypeError, ValueError):+ return 0.0+++def cron_run_fields(*, outcome: str, delivery_kind: str, seconds: float) -> dict[str, str]:+ from . import shared_metrics_contract as contract++ return {+ "delivery_kind": delivery_kind if delivery_kind in contract.CRON_DELIVERY_KINDS else "other",+ "duration_bucket": contract.duration_bucket(int(seconds * 1000)),+ "outcome": outcome if outcome in contract.CRON_RUN_OUTCOMES else "failed",+ }+++def record_cron_finish(record: Any, delivery_outcome: Any = None) -> None:+ """One execution reached its (write-once) terminal row. A row that never started running was+ refused before any side effect (claim lost, dispatch limit, executor shutdown): ``skipped``,+ unless a failure notice was delivered for it."""+ if not isinstance(record, dict) or not record.get("id"):+ return+ execution_id = str(record["id"])+ with _cron_lock:+ delivery_kind = _cron_delivery.pop(execution_id, "other")+ gated = execution_id in _cron_skipped+ _cron_skipped.discard(execution_id)+ started = record.get("started_at")+ success = record.get("status") == "completed"+ if gated or (not started and not success and delivery_outcome is None):+ outcome = "skipped"+ else:+ outcome = "success" if success else "failed"+ _submit(_emit, "CRON_RUN_MARK", cron_run_fields, outcome=outcome, delivery_kind=delivery_kind,+ seconds=_iso_seconds(started, record.get("finished_at")) if started else 0.0)+++def record_cron_missed(job: Any) -> None:+ """A scheduled occurrence the scheduler dropped without running it (catch-up disabled after+ downtime, or a one-shot past its grace window)."""+ _submit(_emit, "CRON_RUN_MARK", cron_run_fields, outcome="missed",+ delivery_kind=cron_delivery_kind(job), seconds=0.0)diff --git a/tests/cron/test_cron_run_metrics.py b/tests/cron/test_cron_run_metrics.pynew file mode 100644index 00000000000..9be34cd5786--- /dev/null+++ b/tests/cron/test_cron_run_metrics.py@@ -0,0 +1,61 @@+"""hermes.cron.run: one row per terminal execution and per dropped occurrence."""++from datetime import timedelta++import pytest++from cron import executions, jobs+from hermes_cli.observability import relay_shared_metrics as rsm+from hermes_cli.observability import shared_metrics_contract as contract+from hermes_cli.observability import shared_metrics_gateway as smg+++def cron_rows(tmp_path, monkeypatch):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ got = []+ monkeypatch.setattr(rsm, "enabled", lambda: True)+ monkeypatch.setattr(rsm, "record_process_mark", lambda mark, data: got.append((mark, dict(data))))++ def read():+ smg.drain()+ found = [data for mark, data in got if mark == contract.CRON_RUN_MARK]+ assert all(contract.counter_dimensions_are_valid(contract.CRON_RUN_METRIC, d) for d in found)+ return found++ return read+++def _execution(job_id, deliver, *, start=True):+ row = executions.create_execution(job_id, source="builtin")+ smg.note_cron_execution({"execution_id": row["id"], "deliver": deliver})+ if start:+ executions.mark_execution_running(row["id"])+ return row["id"]+++def test_each_terminal_execution_is_one_row_classified_without_job_details(cron_rows):+ ok = _execution("job1", "telegram:-100555")+ executions.finish_execution(ok, success=True, delivery_outcome="delivered")+ executions.finish_execution(ok, success=False, error="late duplicate") # write-once: no second row+ executions.finish_execution(_execution("job2", "local"), success=False, error="boom")+ refused = _execution("job3", "webhook", start=False) # claim lost before any side effect+ executions.finish_execution(refused, success=False, error="Fire claim lost; execution was not started.")+ gated = _execution("job4", "origin")+ smg.note_cron_skipped({"execution_id": gated}) # pre-run script said wakeAgent=false+ executions.finish_execution(gated, success=True, delivery_outcome="suppressed")+ assert [(r["outcome"], r["delivery_kind"]) for r in cron_rows()] == [+ ("success", "platform"), ("failed", "local"), ("skipped", "webhook"), ("skipped", "platform"),+ ]+++def test_an_occurrence_dropped_after_downtime_is_one_missed_row(tmp_path, cron_rows):+ (tmp_path / "config.yaml").write_text("cron:\n catch_up_missed: false\n", encoding="utf-8")+ with jobs.use_cron_store(tmp_path / "cron"):+ jobs.create_job(prompt="secret prompt", schedule="every 1h", model="fixture", deliver="local")+ stored = jobs.load_jobs()+ stored[0]["next_run_at"] = (jobs._hermes_now() - timedelta(hours=4)).isoformat()+ jobs.save_jobs(stored)+ assert jobs.get_due_jobs() == []+ assert jobs.get_due_jobs() == []+ assert cron_rows() == [{"delivery_kind": "local", "duration_bucket": "lt_1s", "outcome": "missed"}]diff --git a/tests/gateway/test_platform_shared_metrics.py b/tests/gateway/test_platform_shared_metrics.pynew file mode 100644index 00000000000..83724eb43d2--- /dev/null+++ b/tests/gateway/test_platform_shared_metrics.py@@ -0,0 +1,107 @@+"""Gateway platform health / delivery / first-reply shared metrics through the real runner seams."""++import asyncio+from types import SimpleNamespace++import pytest++from gateway.platforms.base import BasePlatformAdapter, Platform, PlatformConfig, SendResult+from gateway.platforms.event import MessageEvent, MessageType+from gateway.run_adapters import GatewayAdapterLifecycleMixin+from gateway.stream_consumer import GatewayStreamConsumer, StreamConsumerConfig+from hermes_cli.observability import relay_shared_metrics as rsm+from hermes_cli.observability import shared_metrics_contract as contract+from hermes_cli.observability import shared_metrics_gateway as smg+++def rows(monkeypatch):+ got = []+ monkeypatch.setattr(rsm, "enabled", lambda: True)+ monkeypatch.setattr(rsm, "record_process_mark", lambda mark, data: got.append((mark, dict(data))))+ monkeypatch.setattr("gateway.platforms.base.random.uniform", lambda *_: 0.0)+ smg._reply_clocks.clear()++ def read(metric):+ smg.drain()+ found = [data for mark, data in got if contract._DECISION_MARK_METRICS[mark] == metric]+ assert all(contract.counter_dimensions_are_valid(metric, data) for data in found)+ return found++ return read+++class _Adapter(BasePlatformAdapter):+ def __init__(self, results=(), connect: object = True):+ super().__init__(PlatformConfig(enabled=True, token="test"), Platform.TELEGRAM)+ self.results, self._connect = list(results), connect++ async def connect(self, *, is_reconnect: bool = False) -> bool:+ if isinstance(self._connect, BaseException):+ raise self._connect+ if not self._connect:+ self._set_fatal_error("telegram_missing_dependency", "python-telegram-bot missing", retryable=False)+ return self._connect++ async def disconnect(self) -> None:+ self._mark_disconnected()++ async def send(self, chat_id, content, reply_to=None, metadata=None):+ return self.results.pop(0) if self.results else SendResult(success=True, message_id="m1")++ async def get_chat_info(self, chat_id):+ return {"id": chat_id, "type": "dm"}+++class _Runner(GatewayAdapterLifecycleMixin):+ def _platform_connect_timeout_secs(self, platform=None, *, initial=False):+ return 5.0+++def _connect(adapter, **kw):+ try:+ return asyncio.run(_Runner()._connect_adapter_with_timeout(adapter, Platform.TELEGRAM, **kw))+ except Exception as exc:+ return type(exc).__name__+++def test_every_connect_attempt_records_one_health_row_with_a_closed_error_class(rows):+ assert _connect(_Adapter()) is True+ assert _connect(_Adapter(), is_reconnect=True) is True+ assert _connect(_Adapter(connect=False)) is False+ assert _connect(_Adapter(connect=ConnectionResetError("peer reset by 10.0.0.1"))) == "ConnectionResetError"+ assert rows("hermes.platform.health") == [+ {"error_class": "none", "event": "connect_ok", "platform": "telegram"},+ {"error_class": "none", "event": "reconnect", "platform": "telegram"},+ {"error_class": "config", "event": "connect_failed", "platform": "telegram"},+ {"error_class": "network", "event": "connect_failed", "platform": "telegram"},+ ]+++def test_one_logical_delivery_is_one_row_whatever_the_retries(rows):+ flaky = _Adapter([SendResult(success=False, error="ConnectionError: reset", retryable=True)])+ assert asyncio.run(flaky._send_with_retry("42", "hi", base_delay=0)).success+ blocked = _Adapter([SendResult(success=False, error="Forbidden: bot was blocked", error_kind="forbidden")] * 3)+ assert not asyncio.run(blocked._send_with_retry("42", "hi", base_delay=0)).success+ assert rows("hermes.platform.delivery") == [+ {"failure_class": "none", "outcome": "sent", "platform": "telegram"},+ {"failure_class": "forbidden", "outcome": "failed", "platform": "telegram"},+ ]+++def test_first_reply_latency_is_one_row_per_turn_stopped_only_by_reply_text(rows):+ adapter = _Adapter()+ smg.start_reply_clock(SimpleNamespace(platform=Platform.TELEGRAM, chat_id="42"))+ asyncio.run(adapter._send_with_retry("42", "⏳ still working on the previous message")) # busy ack+ assert rows("hermes.gateway.reply_latency") == []+ consumer = GatewayStreamConsumer(adapter, "42", StreamConsumerConfig(cursor=""))+ assert asyncio.run(consumer._send_or_edit("first streamed chunk"))+ asyncio.run(consumer._send_or_edit("first streamed chunk, more")) # later edits are not the first reply++ event = MessageEvent(text="hi", message_type=MessageType.TEXT, message_id="in-1",+ source=adapter.build_source(chat_id="8", user_id="u1"))+ smg.start_reply_clock(event.source)+ asyncio.run(adapter.send_final_ledgered(event, "k", "final answer", {}, reply_to=None))+ smg.start_reply_clock(SimpleNamespace(platform=Platform.TELEGRAM, chat_id="7"), internal=True)+ asyncio.run(adapter.send_final_ledgered(event, "k", "background notice", {}, reply_to=None))+ assert rows("hermes.gateway.reply_latency") == [{"first_response_bucket": "lt_2s", "platform": "telegram"}] * 2diff --git a/tests/hermes_cli/test_shared_metrics_gateway.py b/tests/hermes_cli/test_shared_metrics_gateway.pynew file mode 100644index 00000000000..af796a524f1--- /dev/null+++ b/tests/hermes_cli/test_shared_metrics_gateway.py@@ -0,0 +1,95 @@+"""Invariants for gateway / cron shared metrics: bounded platform names with proven catalog provenance,+opt-in gating, and contract-valid rows."""++import json+import textwrap++import pytest++from hermes_cli.observability import relay_shared_metrics as rsm+from hermes_cli.observability import shared_metrics_catalog as catalog+from hermes_cli.observability import shared_metrics_contract as contract+from hermes_cli.observability import shared_metrics_gateway as smg+++def marks(monkeypatch):+ got = []+ monkeypatch.setattr(rsm, "enabled", lambda: True)+ monkeypatch.setattr(rsm, "record_process_mark", lambda mark, data: got.append((mark, dict(data))))++ def read():+ smg.drain()+ return [(contract._DECISION_MARK_METRICS[mark], data) for mark, data in got]++ return read+++def _install_platform_plugin(home, monkeypatch, *, dir_name, platform, catalog_name=None):+ """A user plugin under $HERMES_HOME/plugins registering ``platform``; ``catalog_name`` writes the+ installer-owned record a plugin-catalog install leaves (a URL install writes none)."""+ from gateway.platform_registry import PlatformEntry, platform_registry++ plugin_dir = home / "plugins" / dir_name+ plugin_dir.mkdir(parents=True)+ (plugin_dir / "adapter.py").write_text(textwrap.dedent("""+ def make_adapter(config):+ return None+ """), encoding="utf-8")+ # Anything inside the tree is the repo's to write: it must never prove a catalog install.+ (plugin_dir / ".hermes-catalog.json").write_text(json.dumps({"catalog_name": "sendblue"}), encoding="utf-8")+ namespace = {}+ exec(compile((plugin_dir / "adapter.py").read_text(), str(plugin_dir / "adapter.py"), "exec"), namespace)+ if catalog_name:+ (home / "plugins" / ".install-metadata.json").write_text(json.dumps({+ dir_name: {"source": "https://example.invalid/repo", "catalog": {"name": catalog_name, "tier": "official"}},+ }), encoding="utf-8")+ platform_registry.register(PlatformEntry(+ name=platform, label=platform, adapter_factory=namespace["make_adapter"], check_fn=lambda: True,+ source="plugin", plugin_name="sendblue"))+ monkeypatch.setattr(catalog, "catalog_platform_names", lambda: frozenset({"sendblue", "vk-platform"}))+ catalog._catalog_platform_owner.cache_clear()+ return lambda: platform_registry.unregister(platform)+++def test_platform_names_are_published_or_proven_by_the_installer_record(tmp_path, monkeypatch):+ home = tmp_path / ".hermes"+ monkeypatch.setenv("HERMES_HOME", str(home))+ cleanup = [+ _install_platform_plugin(home, monkeypatch, dir_name="vk", platform="vk", catalog_name="vk-platform"),+ # A URL install claiming a catalog name everywhere it can (tree sidecar, manifest name) stays anonymous.+ _install_platform_plugin(tmp_path / "other", monkeypatch, dir_name="x", platform="sneaky"),+ ]+ try:+ assert contract.adapter_platform("telegram") == "telegram"+ assert contract.adapter_platform("irc") == "irc" # bundled plugins/platforms/irc+ assert contract.adapter_platform("vk") == "vk-platform"+ assert contract.adapter_platform("sneaky") == "plugin"+ assert contract.adapter_platform("my-private-bridge") == "plugin"+ assert contract.gateway_platform({"platform": "vk", "surface": "gateway"}, "gateway") == "vk-platform"+ assert "vk-platform" in contract.GATEWAY_PLATFORMS+ finally:+ for undo in cleanup:+ undo()+ catalog._catalog_platform_owner.cache_clear()+++def test_every_gateway_row_is_contract_valid_and_disabled_config_records_nothing(marks, monkeypatch):+ class Adapter:+ platform = "telegram"+ fatal_error_code = "telegram_auth_error"++ smg.record_platform_connect(Adapter(), "telegram", is_reconnect=False, ok=False, exc=TimeoutError("x"))+ smg.record_platform_disconnect(Adapter())+ smg.record_cron_missed({"deliver": "telegram:-100123"})+ rows = marks()+ assert rows == [+ ("hermes.platform.health", {"error_class": "network", "event": "connect_failed", "platform": "telegram"}),+ ("hermes.platform.health", {"error_class": "auth", "event": "disconnect", "platform": "telegram"}),+ ("hermes.cron.run", {"delivery_kind": "platform", "duration_bucket": "lt_1s", "outcome": "missed"}),+ ]+ assert all(contract.counter_dimensions_are_valid(name, dims) for name, dims in rows)++ monkeypatch.setattr(rsm, "enabled", lambda: False)+ smg.record_platform_disconnect(Adapter())+ assert len(marks()) == 3diff --git a/website/docs/developer-guide/relay-shared-metrics.md b/website/docs/developer-guide/relay-shared-metrics.mdindex 3a9bf0c1ef3..aeae5d8ee64 100644--- a/website/docs/developer-guide/relay-shared-metrics.md+++ b/website/docs/developer-guide/relay-shared-metrics.md@@ -195,8 +195,10 @@ mark again, but the subscriber suppresses it until the rolling window expires.Each task run is a Relay `Function` scope named `hermes.task_run`, parented tothe owning Hermes session. The start counter contains only bounded executionsurface and entrypoint values plus, for gateway tasks, the built-in messaging-`platform` (`telegram`, `discord`, `slack`, ...; plugin platforms report-`plugin`, every other surface `none`). The terminal counter contains bounded+`platform` (`telegram`, `discord`, `slack`, ...; platforms Hermes ships under+`plugins/platforms/` by name, a `plugin-catalog/` platform by its catalog entry+name only when the installer's own record proves a catalog install, every other+plugin platform `plugin`, every other surface `none`). The terminal counter contains boundedoutcome, end reason, termination status, duration, logical model-call count,terminal tool-call count, and provider-retry count buckets, and a`failure_class` for failed tasks: the provider `FailoverReason` when the turn@@ -282,6 +284,10 @@ itself ships.| `hermes.curator.run.count` | trigger (`scheduled`/`manual`), outcome (`success`/`failed`/`skipped`), archived/merged/patched/created buckets | Does the skill curator run, and does it actually consolidate anything. Dry runs and passes another process already holds report `skipped`. Never skill names. || `hermes.delegation.run.count` | subagent-count bucket, depth (`1`–`3`, `gte_4`), mode (`foreground`/`background`), outcome (`success`/`partial`/`failed`/`cancelled`) | How wide and deep delegate_task fan-outs go and how often every child finishes. One row per call, however many completion units it splits into. || `hermes.execution_backend.count` | kind (`terminal`/`browser`/`code`), backend, outcome, error class | Which sandboxes carry real work and how reliable each is. Terminal backends are the `terminal.backend` values (else `other`); browser backends are `local`, `lightpanda`, `cdp`, `camofox`, `extension` or a bundled cloud provider (else `other`); execute_code is `local` or `remote`. A command's own nonzero exit is still a backend success; terminal and execute_code calls a guard refuses before they reach the backend are not counted. |+| `hermes.platform.health` | platform, event (`connect_ok`/`connect_failed`/`reconnect`/`disconnect`), error class (`auth`/`network`/`rate_limited`/`config`/`other`) | Which messaging platforms fail to connect or drop, and why. Classified from exception types, HTTP statuses and Hermes's own fatal codes, never error text. |+| `hermes.platform.delivery` | platform, outcome (`sent`/`failed`), failure class (`rate_limited`/`too_long`/`auth`/`network`/`forbidden`/`other`) | How often replies fail to reach the user per platform (one count per logical reply, retries included). |+| `hermes.gateway.reply_latency` | platform, first-response bucket (`lt_2s` … `gte_60s`) | Time from an accepted inbound message to the first visible reply text (stream first chunk or final message). |+| `hermes.cron.run` | outcome (`success`/`failed`/`missed`/`skipped`), delivery kind (`local`/`platform`/`webhook`/`none`/`other`), duration bucket | Do scheduled jobs run, fail, get skipped by a gate or overlap, or get missed while Hermes was down. Job names, prompts, schedules and targets are never included. |Sessions are summarized when they close (finalize, reset or process exit);delegated child sessions are not counted separately. Milestones latch in the