The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(agent/runtime): monitoring — shared OTLP plumbing in otlp_exporter, event base class, EmitterStreamer, dedupe health export
Teknium7eb8ccc3157e
diff --git a/agent/monitoring/__init__.py b/agent/monitoring/__init__.pyindex ee45ff01649..20b4dc40f4d 100644--- a/agent/monitoring/__init__.py+++ b/agent/monitoring/__init__.py@@ -1,17 +1,10 @@-"""Hermes gateway monitoring.+"""Hermes gateway monitoring: service health + redacted diagnostics over OTLP.-Service health monitoring plus redacted operational diagnostics for the-gateway daemon, exported over OTLP to an operator-configured endpoint.--``emitter`` is the in-process event bus: producers (gateway status hooks,-the diagnostic log handler) hand typed events to a fire-and-forget queue,-and subscribers (the OTLP streamers) consume them off the hot path. The-emitter never blocks or raises into gateway code (the hot-path invariant),-and nothing is persisted locally — monitoring is an egress path, not a store.--Deliberately out of scope here: run/model/tool trajectory capture, usage-analytics, and any content-bearing signal. Those planes are served by the-NeMo Relay integration and its Hermes-owned subscribers.+``emitter`` is the in-process event bus: producers hand typed events to a+fire-and-forget queue that never blocks or raises into gateway code, and OTLP+subscribers consume them off the hot path. Nothing is persisted locally.+Out of scope: trajectory capture, usage analytics, any content-bearing signal+(those belong to the NeMo Relay integration)."""from __future__ import annotationsdiff --git a/agent/monitoring/cron_health.py b/agent/monitoring/cron_health.pyindex 2c4fe8d35ff..04e5122f76b 100644--- a/agent/monitoring/cron_health.py+++ b/agent/monitoring/cron_health.py@@ -2,15 +2,18 @@from __future__ import annotations-import hashlibimport loggingimport refrom dataclasses import dataclassfrom datetime import datetime-from typing import Any, Optional+from typing import Any, Callable, Optionalfrom agent.monitoring.events import CronExecutionEvent-from agent.monitoring.gateway_health import GatewayHealthSnapshot, GatewayMetric+from agent.monitoring.gateway_health import (+ GatewayMetric,+ _contains_any,+ _safe_instance_id,+)from cron.jobs import (_compute_grace_seconds,get_catch_up_occurrence_count,@@ -19,7 +22,7 @@ from cron.jobs import (load_jobs,)from cron.scheduler import get_running_job_ids-from hermes_time import now as _hermes_now+from hermes_time import now as _nowlogger = logging.getLogger(__name__)_KNOWN_STATUSES = {"claimed", "running", "completed", "failed", "unknown"}@@ -27,6 +30,7 @@ _KNOWN_SOURCES = {"builtin", "direct", "external"}_KNOWN_DELIVERY_OUTCOMES = {"delivered", "failed", "suppressed", "suppressed_acked", "not_configured",}+_TERMINAL_STATUSES = {"completed", "failed", "unknown"}@dataclass(frozen=True, slots=True)@@ -35,39 +39,32 @@ class CronHealthSnapshot:events: list[CronExecutionEvent]-def _now() -> datetime:- return _hermes_now()+# Opaque job key: same sha256:<24 hex> shape as service.instance.id — never the raw id.+_job_key = _safe_instance_id++_AUTH_RE = re.compile(+ r"\b(?:authentication|authenticated|authenticate|authorization|authorized|authorize"+ r"|unauthorized|forbidden|bearer|401|403)\b|\b(?:access|api|refresh) token\b"+)-def _job_key(raw: Any) -> str:- value = str(raw or "unknown").encode("utf-8", errors="replace")- return f"sha256:{hashlib.sha256(value).hexdigest()[:24]}"+# Ordered (predicate, class) rules; first match wins. Auth uses word boundaries so+# "oauth"/"tokenizer"/"HTTP 4015" do not false-positive.+_CRON_ERROR_RULES: tuple[tuple[Callable[[str], bool], str], ...] = (+ (lambda s: _AUTH_RE.search(s) is not None, "auth_failed"),+ (_contains_any("rate limit", "429", "quota"), "rate_limited"),+ (_contains_any("timeout", "timed out"), "timeout"),+ (_contains_any("network", "connection", "dns", "socket", "unreachable"), "network_error"),+ (_contains_any("dispatch", "executor"), "dispatch_failed"),+ (_contains_any("interrupt", "owner exited", "restarted"), "interrupted"),+ (_contains_any("empty response"), "empty_response"),+ (_contains_any("config", "missing", "invalid"), "invalid_config"),+)def classify_cron_error(raw: Any) -> str:text = str(raw or "").lower()- if (- re.search(r"\b(?:authentication|authenticated|authenticate|authorization|authorized|authorize|unauthorized|forbidden)\b", text)- or re.search(r"\bbearer\b", text)- or re.search(r"\b(?:access|api|refresh) token\b", text)- or re.search(r"\b(?:401|403)\b", text)- ):- return "auth_failed"- if "rate limit" in text or "429" in text or "quota" in text:- return "rate_limited"- if "timeout" in text or "timed out" in text:- return "timeout"- if any(value in text for value in ("network", "connection", "dns", "socket", "unreachable")):- return "network_error"- if "dispatch" in text or "executor" in text:- return "dispatch_failed"- if "interrupt" in text or "owner exited" in text or "restarted" in text:- return "interrupted"- if "empty response" in text:- return "empty_response"- if any(value in text for value in ("config", "missing", "invalid")):- return "invalid_config"- return "unknown"+ return next((label for match, label in _CRON_ERROR_RULES if match(text)), "unknown")def _parse_time(raw: Any) -> Optional[datetime]:@@ -94,13 +91,12 @@ def project_execution_event() -> CronExecutionEvent:status = str(record.get("status") or "unknown").lower()source = str(record.get("source") or "unknown").lower()- if source not in _KNOWN_SOURCES and source != "unknown":- source = "external"outcome = str(delivery_outcome).lower() if delivery_outcome is not None else Nonereturn CronExecutionEvent(status=status if status in _KNOWN_STATUSES else "unknown",job_key=_job_key(record.get("job_id")),- source=source if source in _KNOWN_SOURCES else "unknown",+ # Unknown non-empty sources are bucketed as "external" (not dropped to unknown).+ source=source if source in _KNOWN_SOURCES or source == "unknown" else "external",duration_ms=_duration_ms(record),delivery_outcome=(outcome if outcome in _KNOWN_DELIVERY_OUTCOMES else None@@ -125,7 +121,7 @@ def emit_execution_state(event = project_execution_event(record, delivery_outcome=delivery_outcome)target = emitter.get_emitter()target.emit(event)- if event.status in {"completed", "failed", "unknown"}:+ if event.status in _TERMINAL_STATUSES:target.flush(timeout=1.0)except Exception:logger.debug("cron execution telemetry emit failed", exc_info=True)@@ -147,50 +143,50 @@ def _is_overdue(job: dict[str, Any], now: datetime) -> bool:return False+def _job_metrics(metrics: list[GatewayMetric]) -> None:+ enabled = [job for job in load_jobs() if job.get("enabled", True)]+ metrics.append(GatewayMetric("hermes.cron.jobs.enabled", len(enabled), {}))+ metrics.append(GatewayMetric(+ "hermes.cron.jobs.overdue",+ sum(1 for job in enabled if _is_overdue(job, _now())),+ {},+ ))+++def _freshness_metric(name: str, reader: Callable[[], Optional[float]]) -> Callable[[list[GatewayMetric]], None]:+ def build(metrics: list[GatewayMetric]) -> None:+ value = reader()+ if value is not None:+ metrics.append(GatewayMetric(name, max(0.0, float(value)), {}))+ return build+++def _single_metric(name: str, reader: Callable[[], Any]) -> Callable[[list[GatewayMetric]], None]:+ return lambda metrics: metrics.append(GatewayMetric(name, reader(), {}))+++# Each group is independently fail-open so one unavailable source never hides the rest.+# Readers are wrapped in lambdas so monkeypatching this module's names still takes effect.+_METRIC_GROUPS: tuple[tuple[Callable[[list[GatewayMetric]], None], str], ...] = (+ (_freshness_metric("hermes.cron.scheduler.heartbeat_age_seconds", lambda: get_ticker_heartbeat_age()),+ "cron freshness metric unavailable"),+ (_freshness_metric("hermes.cron.scheduler.last_success_age_seconds", lambda: get_ticker_success_age()),+ "cron freshness metric unavailable"),+ (_single_metric("hermes.cron.scheduler.catch_up_occurrences", lambda: get_catch_up_occurrence_count()),+ "cron catch-up metric unavailable"),+ (_job_metrics, "cron job metrics unavailable"),+ (_single_metric("hermes.cron.jobs.running", lambda: len(get_running_job_ids())),+ "cron running-job metric unavailable"),+)++def build_cron_health_snapshot() -> CronHealthSnapshot:metrics: list[GatewayMetric] = []- for name, reader in (- ("hermes.cron.scheduler.heartbeat_age_seconds", get_ticker_heartbeat_age),- ("hermes.cron.scheduler.last_success_age_seconds", get_ticker_success_age),- ):+ for build, failure_msg in _METRIC_GROUPS:try:- value = reader()- if value is not None:- metrics.append(GatewayMetric(name, max(0.0, float(value)), {}))+ build(metrics)except Exception:- logger.debug("cron freshness metric unavailable", exc_info=True)-- try:- metrics.append(- GatewayMetric(- "hermes.cron.scheduler.catch_up_occurrences",- get_catch_up_occurrence_count(),- {},- )- )- except Exception:- logger.debug("cron catch-up metric unavailable", exc_info=True)-- try:- jobs = load_jobs()- enabled = [job for job in jobs if job.get("enabled", True)]- metrics.append(GatewayMetric("hermes.cron.jobs.enabled", len(enabled), {}))- metrics.append(- GatewayMetric(- "hermes.cron.jobs.overdue",- sum(1 for job in enabled if _is_overdue(job, _now())),- {},- )- )- except Exception:- logger.debug("cron job metrics unavailable", exc_info=True)-- try:- metrics.append(- GatewayMetric("hermes.cron.jobs.running", len(get_running_job_ids()), {})- )- except Exception:- logger.debug("cron running-job metric unavailable", exc_info=True)+ logger.debug(failure_msg, exc_info=True)return CronHealthSnapshot(metrics=metrics, events=[])diff --git a/agent/monitoring/emitter.py b/agent/monitoring/emitter.pyindex 18a0d4851ae..d63ebb73acb 100644--- a/agent/monitoring/emitter.py+++ b/agent/monitoring/emitter.py@@ -1,22 +1,11 @@"""Monitoring emitter: fire-and-forget queue + background dispatcher.-The emitter is the single seam between producers (gateway status hooks, the-diagnostic log handler) and consumers (the OTLP streamers). Its contract is-the hot-path invariant:-- ``emit()`` MUST return in O(microseconds), MUST NOT block on disk/network,- and MUST NEVER raise into the caller. A monitoring failure is logged- locally and dropped — it can never affect the gateway or a session.--Mechanism:- * ``emit(event)`` does a non-blocking ``queue.put_nowait`` wrapped in a bare- except. On a full queue it drops the *oldest* event and counts the drop.- * A daemon thread drains the queue and fans each batch out to subscribers- (the OTLP metric/span/log streamers). Each subscriber is fail-isolated —- a slow or raising subscriber never affects the hot path or its peers.--Nothing is persisted here. Monitoring is an egress path, not a local store;-if no subscriber is attached, events simply age out of the ring buffer.+The single seam between producers (gateway status hooks, diagnostic log handler)+and consumers (OTLP streamers). Hot-path invariant: ``emit()`` MUST return in+O(microseconds), MUST NOT block on disk/network, and MUST NEVER raise into the+caller — a monitoring failure is logged locally and dropped. On a full queue the+*oldest* event is dropped. A daemon thread fans batches out to fail-isolated+subscribers. Nothing is persisted: monitoring is an egress path, not a store."""from __future__ import annotations@@ -45,16 +34,12 @@ class MonitoringEmitter:self._started = Falseself._lock = threading.Lock()self._thread: Optional[threading.Thread] = None- # Live subscribers (the OTLP streamers). Called from the dispatcher- # thread, fully fail-isolated. Each subscriber is callable(batch: list[dict]).+ # Subscribers are callable(batch: list[dict]), invoked on the dispatcher thread.self._subscribers: list = []# ── public API (hot path) ───────────────────────────────────────────────def emit(self, event: Any) -> None:- """Enqueue an event. Never blocks, never raises.-- ``event`` may be a dataclass with ``to_dict()`` or a plain dict.- """+ """Enqueue a dataclass with ``to_dict()`` or a plain dict. Never blocks, never raises."""if not self._enabled:returntry:@@ -107,7 +92,6 @@ class MonitoringEmitter:self._q.task_done()def _dispatch(self, batch) -> None:- # Fan-out to subscribers (OTLP streamers) — fully fail-isolated.for sub in list(self._subscribers):try:sub(batch)@@ -116,7 +100,7 @@ class MonitoringEmitter:self._dispatched += len(batch)def subscribe(self, callback) -> None:- """Register a live batch subscriber (callable(batch: list[dict]))."""+ """Register a live batch subscriber; the first subscriber enables collection."""if callback not in self._subscribers:self._subscribers.append(callback)self._enabled = True@@ -176,8 +160,7 @@ def get_emitter() -> MonitoringEmitter:return _EMITTERwith _EMITTER_LOCK:if _EMITTER is None:- # Collection is opt-in. A plane exporter enables the singleton by- # attaching its first subscriber; until then producers are no-ops.+ # Collection is opt-in: disabled until a plane exporter attaches its first subscriber._EMITTER = MonitoringEmitter(enabled=False)return _EMITTER@@ -199,12 +182,8 @@ def reset_emitter_for_tests(emitter: Optional[MonitoringEmitter] = None) -> None_EMITTER = emitter-# Back-compat alias for the salvaged class name used in emozilla's tests.-TelemetryEmitter = MonitoringEmitter-__all__ = ["MonitoringEmitter",- "TelemetryEmitter","get_emitter","emit","reset_emitter_for_tests",diff --git a/agent/monitoring/events.py b/agent/monitoring/events.pyindex a17f4a49425..ee51d7ba287 100644--- a/agent/monitoring/events.py+++ b/agent/monitoring/events.py@@ -1,25 +1,32 @@"""Typed gateway monitoring events.Content-free service-health and redacted diagnostic events for the gateway-daemon. These are the only event shapes the monitoring plane emits: no-prompts, messages, tool args/results, session history, or usage analytics.+daemon — the only shapes the monitoring plane emits: no prompts, messages,+tool args/results, session history, or usage analytics. Field order is wire+order (``asdict``); never reorder."""from __future__ import annotationsimport timefrom dataclasses import dataclass, field, asdict-from typing import Any, Dict, Optional+from typing import Any, ClassVar, Dict, Optional-def _now_ns() -> int:- return time.time_ns()+class _MonitoringEvent:+ __slots__ = ()+ EVENT: ClassVar[str]++ def to_dict(self) -> Dict[str, Any]:+ return {"event": self.EVENT, **asdict(self)}@dataclass(slots=True)-class GatewayHealthEvent:+class GatewayHealthEvent(_MonitoringEvent):"""Content-free gateway health snapshot or lifecycle event."""+ EVENT: ClassVar[str] = "gateway_health"+name: strgateway_state: Optional[str] = Noneold_state: Optional[str] = None@@ -36,16 +43,15 @@ class GatewayHealthEvent:version: Optional[str] = Nonesupervision_mode: Optional[str] = Nonepid: Optional[int] = None- ts_ns: int = field(default_factory=_now_ns)-- def to_dict(self) -> Dict[str, Any]:- return {"event": "gateway_health", **asdict(self)}+ ts_ns: int = field(default_factory=time.time_ns)@dataclass(slots=True)-class GatewayDiagnosticEvent:+class GatewayDiagnosticEvent(_MonitoringEvent):"""Redacted gateway diagnostic event for operator-owned observability."""+ EVENT: ClassVar[str] = "gateway_diagnostic"+name: strsubsystem: strerror_class: str = "unknown"@@ -56,27 +62,23 @@ class GatewayDiagnosticEvent:profile: Optional[str] = Noneversion: Optional[str] = Noneseverity: str = "warning"- ts_ns: int = field(default_factory=_now_ns)+ ts_ns: int = field(default_factory=time.time_ns)source_logger: Optional[str] = None- def to_dict(self) -> Dict[str, Any]:- return {"event": "gateway_diagnostic", **asdict(self)}-@dataclass(slots=True)-class CronExecutionEvent:+class CronExecutionEvent(_MonitoringEvent):"""Content-free durable cron execution lifecycle projection."""+ EVENT: ClassVar[str] = "cron_execution"+status: strjob_key: strsource: str = "unknown"duration_ms: Optional[int] = Nonedelivery_outcome: Optional[str] = Noneerror_class: Optional[str] = None- ts_ns: int = field(default_factory=_now_ns)-- def to_dict(self) -> Dict[str, Any]:- return {"event": "cron_execution", **asdict(self)}+ ts_ns: int = field(default_factory=time.time_ns)__all__ = [diff --git a/agent/monitoring/gateway_health.py b/agent/monitoring/gateway_health.pyindex 752473fe31b..f3ac45f8f3d 100644--- a/agent/monitoring/gateway_health.py+++ b/agent/monitoring/gateway_health.py@@ -1,9 +1,8 @@"""Gateway health and diagnostics signal producer.-This module keeps the plane narrow: service health monitoring plus-redacted operational diagnostics. It reuses the existing gateway runtime-status-contract and emits content-free metrics/events. No prompts, messages, tool args,-session history, audit records, or product analytics belong here.+Keeps the plane narrow: service health plus redacted operational diagnostics,+derived from the existing gateway runtime-status contract. No prompts,+messages, tool args, session history, audit records, or product analytics."""from __future__ import annotations@@ -12,9 +11,13 @@ import hashlibimport loggingimport refrom dataclasses import dataclass-from typing import Any, Dict, List, Optional+from typing import Any, Callable, Dict, List, Optional+from agent.monitoring import emitterfrom agent.monitoring.events import GatewayDiagnosticEvent, GatewayHealthEvent+from agent.monitoring.redaction import redact_bounded++logger = logging.getLogger(__name__)@dataclass(frozen=True, slots=True)@@ -42,61 +45,34 @@ _SUPERVISION_MODES = {"systemd", "s6", "container", "launchd", "manual", "unknow_SOURCE_LOGGER_RE = re.compile(r"^gateway(?:\.[A-Za-z_][A-Za-z0-9_]*)*$")-def _allowed_logger(name: str) -> bool:- return name == "gateway" or name.startswith("gateway.")--def source_logger_for_export(name: Any) -> Optional[str]:"""Return a bounded source-controlled gateway logger name for OTLP scope."""value = str(name or "")return value if len(value) <= 128 and _SOURCE_LOGGER_RE.fullmatch(value) else None-def redact_gateway_message(message: Any) -> str:- """Redact gateway diagnostic free text for operator-owned export.+def _contains_any(*needles: str) -> Callable[[str], bool]:+ return lambda text: any(needle in text for needle in needles)- Single scrub path: everything goes through- ``agent.monitoring.redaction.redact_for_export`` (unconditional- secrets + PII), then is length-bounded.- """- try:- from agent.monitoring.redaction import redact_for_export- redacted = redact_for_export(str(message or "")) or ""- except Exception:- redacted = "[redaction-unavailable]"- return redacted[:500]++# Ordered (predicate, class) rules; first match wins, so auth outranks rate-limit etc.+_GATEWAY_ERROR_RULES: tuple[tuple[Callable[[str], bool], str], ...] = (+ (_contains_any("auth", "token", "unauthorized", "forbidden", "401", "403"), "auth_failed"),+ (lambda s: "rate" in s and "limit" in s, "rate_limited"),+ (_contains_any("timeout", "timed out"), "timeout"),+ (_contains_any(+ "network", "connection", "dns", "socket", "connect call failed",+ "failed to connect", "cannot connect", "unreachable", "name resolution",+ ), "network_error"),+ (_contains_any("config", "missing", "invalid"), "invalid_config"),+ (_contains_any("startup"), "startup_failed"),+ (_contains_any("fatal"), "platform_fatal"),+)def classify_gateway_error(raw: Any) -> str:s = str(raw or "").lower()- if any(k in s for k in ("auth", "token", "unauthorized", "forbidden", "401", "403")):- return "auth_failed"- if "rate" in s and "limit" in s:- return "rate_limited"- if "timeout" in s or "timed out" in s:- return "timeout"- if any(- k in s- for k in (- "network",- "connection",- "dns",- "socket",- "connect call failed",- "failed to connect",- "cannot connect",- "unreachable",- "name resolution",- )- ):- return "network_error"- if any(k in s for k in ("config", "missing", "invalid")):- return "invalid_config"- if "startup" in s:- return "startup_failed"- if "fatal" in s:- return "platform_fatal"- return "unknown"+ return next((label for match, label in _GATEWAY_ERROR_RULES if match(s)), "unknown")def classify_exit_reason(@@ -124,13 +100,13 @@ def _bounded_state(raw: Any, *, allowed: set[str]) -> str:return state if state in allowed else "unknown"+def _optional_state(raw: Any, *, allowed: set[str]) -> Optional[str]:+ """``_bounded_state`` that preserves "absent" (None) instead of coercing to unknown."""+ return None if raw is None else _bounded_state(raw, allowed=allowed)++def _safe_metric_value(raw: Any, *, limit: int = 128) -> str:- try:- from agent.monitoring.redaction import redact_for_export- value = redact_for_export(str(raw or "")) or "unknown"- except Exception:- return "unknown"- return value[:limit]+ return redact_bounded(raw, limit=limit, empty="unknown", unavailable="unknown")def _safe_instance_id(raw: Any) -> str:@@ -140,23 +116,16 @@ def _safe_instance_id(raw: Any) -> str:def subsystem_for_logger(logger_name: str) -> str:- if logger_name == "gateway.relay" or logger_name.startswith("gateway.relay."):+ parts = logger_name.split(".")+ if parts[:2] == ["gateway", "relay"]:return "platform.relay"- if logger_name.startswith("gateway.platforms."):- parts = logger_name.split(".")- if len(parts) >= 3 and parts[2]:- return f"platform.{parts[2]}"- if logger_name.startswith("gateway.platforms"):- return "platform"- if logger_name.startswith("gateway"):- return "gateway"- return "gateway"+ if parts[:2] == ["gateway", "platforms"] and len(parts) >= 3 and parts[2]:+ return f"platform.{parts[2]}"+ return "platform" if logger_name.startswith("gateway.platforms") else "gateway"def platform_for_subsystem(subsystem: str) -> Optional[str]:- if subsystem.startswith("platform."):- return subsystem.split(".", 1)[1] or None- return None+ return (subsystem.split(".", 1)[1] or None) if subsystem.startswith("platform.") else Nonedef _parse_active_agents(raw: Any) -> int:@@ -174,9 +143,7 @@ def _derive_busy(gateway_running: bool, gateway_state: Any, active_agents: Any)try:from gateway.status import derive_gateway_busyreturn derive_gateway_busy(- gateway_running=gateway_running,- gateway_state=gateway_state,- active_agents=active_agents,+ gateway_running=gateway_running, gateway_state=gateway_state, active_agents=active_agents)except Exception:return bool(gateway_running and gateway_state == "running" and _parse_active_agents(active_agents) > 0)@@ -190,7 +157,7 @@ def _derive_drainable(gateway_running: bool, gateway_state: Any) -> bool:return bool(gateway_running and gateway_state == "running")-def _base_attrs(*, profile: str, install_id: str, version: str, supervision_mode: str) -> Dict[str, str]:+def _base_attrs(*, install_id: str, version: str, supervision_mode: str) -> Dict[str, str]:mode = str(supervision_mode or "unknown").lower()return {"service.instance.id": _safe_instance_id(install_id),@@ -207,6 +174,11 @@ def _metric(name: str, value: int | float, attrs: Dict[str, str], **extra: str)return GatewayMetric(name=name, value=value, attributes=out)+def _platforms_of(runtime: Optional[dict[str, Any]]) -> dict[str, Any]:+ raw = (runtime or {}).get("platforms")+ return raw if isinstance(raw, dict) else {}++def build_gateway_health_snapshot(runtime: Optional[dict[str, Any]],*,@@ -218,14 +190,12 @@ def build_gateway_health_snapshot() -> GatewayHealthSnapshot:"""Convert gateway_state.json-compatible runtime state into P0 signals."""runtime = runtime or {}- gateway_state = _bounded_state(- runtime.get("gateway_state"), allowed=_KNOWN_GATEWAY_STATES- )+ gateway_state = _bounded_state(runtime.get("gateway_state"), allowed=_KNOWN_GATEWAY_STATES)active_agents = _parse_active_agents(runtime.get("active_agents", 0))busy = _derive_busy(gateway_running, gateway_state, active_agents)drainable = _derive_drainable(gateway_running, gateway_state)- platforms = runtime.get("platforms") if isinstance(runtime.get("platforms"), dict) else {}- base = _base_attrs(profile=profile, install_id=install_id, version=version, supervision_mode=supervision_mode)+ platforms = _platforms_of(runtime)+ base = _base_attrs(install_id=install_id, version=version, supervision_mode=supervision_mode)metrics: list[GatewayMetric] = [_metric("hermes.gateway.up", 1 if gateway_running else 0, base),@@ -233,34 +203,23 @@ def build_gateway_health_snapshot(_metric("hermes.gateway.busy", 1 if busy else 0, base),_metric("hermes.gateway.drainable", 1 if drainable else 0, base),_metric("hermes.gateway.restart_requested", 1 if runtime.get("restart_requested") else 0, base),+ _metric("hermes.gateway.state", 1, base, **{"hermes.gateway.state": gateway_state}),]- if gateway_state:- metrics.append(_metric("hermes.gateway.state", 1, base, **{"hermes.gateway.state": str(gateway_state)}))fatal_count = 0events: list[GatewayHealthEvent | GatewayDiagnosticEvent] = []for platform, pdata in platforms.items():pdata = pdata if isinstance(pdata, dict) else {}- state = _bounded_state(- pdata.get("state"), allowed=_KNOWN_PLATFORM_STATES- )- raw_error = pdata.get("error_code") or pdata.get("error_message")- error_code = classify_gateway_error(raw_error)- is_up = state in _RUNNING_PLATFORM_STATES+ state = _bounded_state(pdata.get("state"), allowed=_KNOWN_PLATFORM_STATES)+ # classify_* is idempotent on its own labels, so error_class == error_code here.+ error_code = classify_gateway_error(pdata.get("error_code") or pdata.get("error_message"))is_degraded = state in _FATAL_PLATFORM_STATESif is_degraded:fatal_count += 1+ pattrs = {"hermes.platform": str(platform), "hermes.platform.state": state}+ metrics.append(_metric("hermes.platform.up", 1 if state in _RUNNING_PLATFORM_STATES else 0, base, **pattrs))metrics.append(_metric(- "hermes.platform.up",- 1 if is_up else 0,- base,- **{"hermes.platform": str(platform), "hermes.platform.state": state},- ))- metrics.append(_metric(- "hermes.platform.degraded",- 1 if is_degraded else 0,- base,- **{"hermes.platform": str(platform), "hermes.platform.state": state, "hermes.error_code": error_code},+ "hermes.platform.degraded", 1 if is_degraded else 0, base, **pattrs, **{"hermes.error_code": error_code}))if is_degraded:events.append(GatewayDiagnosticEvent(@@ -268,7 +227,7 @@ def build_gateway_health_snapshot(subsystem=f"platform.{platform}",platform=str(platform),error_code=error_code,- error_class=classify_gateway_error(error_code or pdata.get("error_message")),+ error_class=error_code,profile=profile,version=version,severity="error" if state == "fatal" else "warning",@@ -276,7 +235,7 @@ def build_gateway_health_snapshot(events.insert(0, GatewayHealthEvent(name="gateway.health_snapshot",- gateway_state=str(gateway_state) if gateway_state is not None else None,+ gateway_state=gateway_state,active_agents=active_agents,gateway_busy=busy,gateway_drainable=drainable,@@ -307,6 +266,81 @@ def _safe_version() -> str:return "unknown"+def _lifecycle_events(+ previous: Optional[dict[str, Any]], current: dict[str, Any], *, profile: str, version: str+) -> list[GatewayHealthEvent | GatewayDiagnosticEvent]:+ """Gateway-level transition events: lifecycle, startup_failed diagnostic, exit."""+ old_state = _optional_state((previous or {}).get("gateway_state"), allowed=_KNOWN_GATEWAY_STATES)+ new_state = _optional_state(current.get("gateway_state"), allowed=_KNOWN_GATEWAY_STATES)+ if old_state == new_state or not new_state:+ return []+ restart_requested = bool(current.get("restart_requested"))++ def health(name: str) -> GatewayHealthEvent:+ return GatewayHealthEvent(+ name=name,+ gateway_state=new_state,+ old_state=old_state,+ new_state=new_state,+ exit_reason=classify_exit_reason(+ current.get("exit_reason"), state=new_state, restart_requested=restart_requested+ ),+ restart_requested=restart_requested,+ active_agents=_parse_active_agents(current.get("active_agents", 0)),+ profile=profile,+ version=version,+ pid=_coerce_pid(current.get("pid")),+ )++ out: list[GatewayHealthEvent | GatewayDiagnosticEvent] = [health("gateway.lifecycle")]+ if new_state == "startup_failed":+ error_class = classify_gateway_error(current.get("exit_reason") or "startup_failed")+ out.append(GatewayDiagnosticEvent(+ name="gateway.startup_failed",+ subsystem="gateway",+ error_class=error_class,+ error_code=error_class,+ profile=profile,+ version=version,+ severity="error",+ ))+ if new_state == "stopped":+ out.append(health("gateway.exit"))+ return out+++def _platform_events(+ previous: Optional[dict[str, Any]], current: dict[str, Any], *, profile: str, version: str+) -> list[GatewayDiagnosticEvent]:+ """Per-platform state_change diagnostics, plus platform.fatal when the new state is fatal."""+ old_platforms = _platforms_of(previous)+ out: list[GatewayDiagnosticEvent] = []+ for platform, pdata in _platforms_of(current).items():+ pdata = pdata if isinstance(pdata, dict) else {}+ prev_raw = old_platforms.get(platform, {})+ prev = prev_raw if isinstance(prev_raw, dict) else {}+ old_state = _optional_state(prev.get("state"), allowed=_KNOWN_PLATFORM_STATES)+ new_state = _optional_state(pdata.get("state"), allowed=_KNOWN_PLATFORM_STATES)+ if old_state == new_state or not new_state:+ continue+ error_code = classify_gateway_error(pdata.get("error_code") or pdata.get("error_message"))+ common: dict[str, Any] = dict(+ subsystem=f"platform.{platform}",+ platform=str(platform),+ error_code=error_code,+ error_class=error_code,+ profile=profile,+ version=version,+ severity="error" if new_state in {"fatal", "failed", "error"} else "warning",+ )+ out.append(GatewayDiagnosticEvent(+ name="platform.state_change", old_state=old_state, new_state=new_state, **common+ ))+ if new_state in _FATAL_PLATFORM_STATES:+ out.append(GatewayDiagnosticEvent(name="platform.fatal", **common))+ return out++def emit_runtime_status_transition(previous: Optional[dict[str, Any]], current: dict[str, Any]) -> None:"""Emit immediate content-free gateway events for runtime status changes.@@ -314,106 +348,11 @@ def emit_runtime_status_transition(previous: Optional[dict[str, Any]], current:Fully fail-open: failures never affect gateway status writes."""try:- from agent.monitoring import emitter- out: list[GatewayHealthEvent | GatewayDiagnosticEvent] = []- profile = _safe_profile()- version = _safe_version()- old_gateway_state = _bounded_state(- (previous or {}).get("gateway_state"), allowed=_KNOWN_GATEWAY_STATES- ) if (previous or {}).get("gateway_state") is not None else None- new_gateway_state = _bounded_state(- current.get("gateway_state"), allowed=_KNOWN_GATEWAY_STATES- ) if current.get("gateway_state") is not None else None- if old_gateway_state != new_gateway_state and new_gateway_state:- out.append(GatewayHealthEvent(- name="gateway.lifecycle",- gateway_state=new_gateway_state,- old_state=old_gateway_state,- new_state=new_gateway_state,- exit_reason=classify_exit_reason(- current.get("exit_reason"),- state=new_gateway_state,- restart_requested=bool(current.get("restart_requested")),- ),- restart_requested=bool(current.get("restart_requested")),- active_agents=_parse_active_agents(current.get("active_agents", 0)),- profile=profile,- version=version,- pid=_coerce_pid(current.get("pid")),- ))- if new_gateway_state == "startup_failed":- out.append(GatewayDiagnosticEvent(- name="gateway.startup_failed",- subsystem="gateway",- error_class=classify_gateway_error(current.get("exit_reason") or "startup_failed"),- error_code=classify_gateway_error(current.get("exit_reason") or "startup_failed"),- profile=profile,- version=version,- severity="error",- ))- if new_gateway_state == "stopped":- out.append(GatewayHealthEvent(- name="gateway.exit",- gateway_state=new_gateway_state,- old_state=old_gateway_state,- new_state=new_gateway_state,- exit_reason=classify_exit_reason(- current.get("exit_reason"),- state=new_gateway_state,- restart_requested=bool(current.get("restart_requested")),- ),- restart_requested=bool(current.get("restart_requested")),- active_agents=_parse_active_agents(current.get("active_agents", 0)),- profile=profile,- version=version,- pid=_coerce_pid(current.get("pid")),- ))-- old_platforms_raw = (previous or {}).get("platforms")- new_platforms_raw = current.get("platforms")- old_platforms = old_platforms_raw if isinstance(old_platforms_raw, dict) else {}- new_platforms = new_platforms_raw if isinstance(new_platforms_raw, dict) else {}- for platform, pdata in new_platforms.items():- pdata = pdata if isinstance(pdata, dict) else {}- prev_raw = old_platforms.get(platform, {})- prev = prev_raw if isinstance(prev_raw, dict) else {}- old_state = _bounded_state(- prev.get("state"), allowed=_KNOWN_PLATFORM_STATES- ) if prev.get("state") is not None else None- new_state = _bounded_state(- pdata.get("state"), allowed=_KNOWN_PLATFORM_STATES- ) if pdata.get("state") is not None else None- if old_state == new_state or not new_state:- continue- error_code = classify_gateway_error(pdata.get("error_code") or pdata.get("error_message"))- severity = "error" if new_state.lower() in {"fatal", "failed", "error"} else "warning"- out.append(GatewayDiagnosticEvent(- name="platform.state_change",- subsystem=f"platform.{platform}",- platform=str(platform),- old_state=old_state,- new_state=new_state,- error_code=error_code,- error_class=error_code,- profile=profile,- version=version,- severity=severity,- ))- if new_state.lower() in _FATAL_PLATFORM_STATES:- out.append(GatewayDiagnosticEvent(- name="platform.fatal",- subsystem=f"platform.{platform}",- platform=str(platform),- error_code=error_code,- error_class=error_code,- profile=profile,- version=version,- severity=severity,- ))- for ev in out:+ ctx = dict(profile=_safe_profile(), version=_safe_version())+ for ev in _lifecycle_events(previous, current, **ctx) + _platform_events(previous, current, **ctx):emitter.emit(ev)except Exception:- logging.getLogger(__name__).debug("gateway runtime status transition emit failed", exc_info=True)+ logger.debug("gateway runtime status transition emit failed", exc_info=True)def _coerce_pid(raw: Any) -> Optional[int]:@@ -436,11 +375,10 @@ class GatewayDiagnosticLogHandler(logging.Handler):try:if record.levelno < logging.WARNING:return- if not _allowed_logger(record.name):+ if not (record.name == "gateway" or record.name.startswith("gateway.")):returnsubsystem = subsystem_for_logger(record.name)- message = record.getMessage()- error_class = classify_gateway_error(message)+ error_class = classify_gateway_error(record.getMessage())event = GatewayDiagnosticEvent(name=f"gateway.log.{record.levelname.lower()}",subsystem=subsystem,@@ -452,10 +390,9 @@ class GatewayDiagnosticLogHandler(logging.Handler):version=self.version,severity=record.levelname.lower(),)- from agent.monitoring import emitteremitter.get_emitter().emit(event)except Exception:- logging.getLogger(__name__).debug("gateway diagnostic emit failed", exc_info=True)+ logger.debug("gateway diagnostic emit failed", exc_info=True)__all__ = [@@ -465,5 +402,4 @@ __all__ = ["build_gateway_health_snapshot","classify_gateway_error","source_logger_for_export",- "redact_gateway_message",]diff --git a/agent/monitoring/gateway_health_export.py b/agent/monitoring/gateway_health_export.pyindex 0a377c99ab3..fa7d1daee10 100644--- a/agent/monitoring/gateway_health_export.py+++ b/agent/monitoring/gateway_health_export.py@@ -1,101 +1,74 @@"""Gateway Health & Diagnostics OTLP export runtime.-This exporter emits operator-owned gateway service-health metrics plus-narrow redacted diagnostic events. It is deliberately in-process and fail-open so-it works under systemd, launchd, s6, containers, tmux, nohup, or a simple shell-without a sidecar/watchdog dependency.+Emits operator-owned gateway service-health metrics plus narrow redacted+diagnostic events. Deliberately in-process and fail-open so it works under+systemd, launchd, s6, containers, tmux, nohup, or a plain shell without a+sidecar/watchdog dependency."""from __future__ import annotations+import importlibimport loggingimport os-import reimport threadingfrom dataclasses import dataclass-from typing import Any, Dict, Optional+from typing import Any, Callable, Dict, Optional++from agent.monitoring import emitter, otlp_exporter+from agent.monitoring.gateway_health import (+ GatewayDiagnosticLogHandler,+ GatewayMetric,+ _safe_profile as _profile,+ _safe_version as _version,+ build_gateway_health_snapshot,+ source_logger_for_export,+)+from agent.monitoring.otlp_exporter import (+ EmitterStreamer,+ _allowlisted_attrs,+ _install_id,+ _monitoring_section,+ _otlp_config,+ _resolve_headers,+ _runtime_resource_attributes,+ _safe_resource_attributes, # noqa: F401 — re-exported for tests+ _signal_endpoint,+)+from agent.monitoring.redaction import redact_boundedlogger = logging.getLogger(__name__)_DEFAULT_DIAGNOSTIC_SCOPE = "hermes.gateway.diagnostics"--_RESOURCE_ATTRIBUTE_KEYS = frozenset({- "service.name",- "service.namespace",- "service.version",- "service.instance.id",- "deployment.environment.name",- "cloud.provider",- "cloud.platform",- "cloud.region",- "telemetry.scope",-})-_DIAGNOSTIC_ATTRIBUTE_KEYS = frozenset({- "name",- "subsystem",- "error_class",- "error_code",- "platform",- "old_state",- "new_state",- "version",- "severity",-})-_SAFE_RESOURCE_VALUE = re.compile(r"^[A-Za-z0-9._:/-]{1,128}$")---def _redact_string(raw: Any, *, limit: int = 500) -> str:- try:- from agent.monitoring.redaction import redact_for_export- return (redact_for_export(str(raw or "")) or "[redacted]")[:limit]- except Exception:- return "[redaction-unavailable]"---def _safe_resource_attributes(raw: Any) -> Dict[str, str]:- """Allowlist bounded resource labels and reject values changed by redaction."""- attrs: Dict[str, str] = {}- if not isinstance(raw, dict):- return attrs- for key, value in raw.items():- key = str(key)- if key not in _RESOURCE_ATTRIBUTE_KEYS or value is None:- continue- if key == "service.instance.id":- from agent.monitoring.gateway_health import _safe_instance_id- attrs[key] = _safe_instance_id(value)- continue- text = str(value)- if not _SAFE_RESOURCE_VALUE.fullmatch(text):- continue- if _redact_string(text, limit=128) != text:- continue- attrs[key] = text- return attrs---def _runtime_resource_attributes(- config: Dict[str, Any], *, telemetry_scope: str-) -> Dict[str, str]:- """Build the safe OTLP resource shared by metrics and diagnostic logs."""- gh = _gateway_health_config(config)- attrs = _safe_resource_attributes(gh.get("resource_attributes"))- from agent.monitoring.gateway_health import _safe_instance_id-- attrs["service.name"] = "hermes-gateway"- attrs["service.instance.id"] = _safe_instance_id(_install_id(config))- attrs["telemetry.scope"] = telemetry_scope- return attrs+_METRICS_SDK = (+ "OTLPLogExporter", "OTLPMetricExporter", "Observation", "LogRecord", "LoggerProvider",+ "INVALID_SPAN_ID", "INVALID_TRACE_ID", "TraceFlags", "SeverityNumber",+ "BatchLogRecordProcessor", "MeterProvider", "PeriodicExportingMetricReader", "Resource",+)+# Every gauge the runtime snapshot can emit MUST be listed here or it is silently dropped.+_OBSERVABLE_METRIC_NAMES = (+ "hermes.gateway.up",+ "hermes.gateway.state",+ "hermes.gateway.active_agents",+ "hermes.gateway.busy",+ "hermes.gateway.drainable",+ "hermes.gateway.restart_requested",+ "hermes.gateway.background_work",+ "hermes.gateway.background_delegations",+ "hermes.platform.up",+ "hermes.platform.degraded",+ "hermes.cron.scheduler.heartbeat_age_seconds",+ "hermes.cron.scheduler.last_success_age_seconds",+ "hermes.cron.scheduler.catch_up_occurrences",+ "hermes.cron.jobs.enabled",+ "hermes.cron.jobs.running",+ "hermes.cron.jobs.overdue",+)def _diagnostic_log_attributes(event: Dict[str, Any]) -> Dict[str, Any]:- attrs: Dict[str, Any] = {}- for key in _DIAGNOSTIC_ATTRIBUTE_KEYS:- value = event.get(key)- if value is None:- continue- attrs[f"hermes.{key}"] = _redact_string(value) if isinstance(value, str) else value- return attrs+ # Same allowlist as the span mapping: profile/install_id/ts never egress as attributes.+ return _allowlisted_attrs(event, otlp_exporter._KEEP_BY_KIND["gateway_diagnostic"])@dataclass(slots=True)@@ -120,26 +93,20 @@ class GatewayHealthExportRuntime:except Exception:pass- # All producers above are now stopped. Drain queued and in-flight- # events before detaching subscribers so the terminal lifecycle event- # cannot race exporter shutdown. The barrier is bounded and fail-open.+ # Producers are stopped; drain queued/in-flight events BEFORE detaching subscribers+ # so the terminal lifecycle event cannot race exporter shutdown. Bounded, fail-open.+ subscribers = [item for item in (self.streamer, self.log_streamer) if item is not None]try:- from agent.monitoring.emitter import get_emitter- emitter = get_emitter()- emitter.flush(timeout=1.0)- if self.streamer is not None:- emitter.unsubscribe(self.streamer)- if self.log_streamer is not None:- emitter.unsubscribe(self.log_streamer)+ bus = emitter.get_emitter()+ bus.flush(timeout=1.0)+ for sub in subscribers:+ bus.unsubscribe(sub)except Exception:pass- # Network flush/close runs under one bounded daemon-thread deadline and- # can never delay gateway teardown indefinitely.- closeables = [- item for item in (self.streamer, self.log_streamer, self.metric_provider)- if item is not None- ]+ # Network flush/close runs under one bounded daemon-thread deadline so it can+ # never delay gateway teardown indefinitely.+ closeables = subscribers + ([self.metric_provider] if self.metric_provider is not None else [])def _close() -> None:for item in closeables:@@ -150,136 +117,55 @@ class GatewayHealthExportRuntime:if closeables:worker = threading.Thread(- target=_close,- name="hermes-gateway-health-export-shutdown",- daemon=True,+ target=_close, name="hermes-gateway-health-export-shutdown", daemon=True)worker.start()worker.join(timeout=2.0)- self.streamer = None- self.log_streamer = None- self.metric_provider = None- self.thread = None- self.stop_event = None+ self.streamer = self.log_streamer = self.metric_provider = self.thread = self.stop_event = Nonedef _gateway_health_config(config: Dict[str, Any]) -> Dict[str, Any]:- mon = (config or {}).get("monitoring") or {}- return mon.get("gateway_health_export") or {}---def _otlp_config(config: Dict[str, Any]) -> Dict[str, Any]:- mon = (config or {}).get("monitoring") or {}- export = mon.get("export") or {}- return export.get("otlp") or {}+ return _monitoring_section(config, "gateway_health_export")def _enabled(config: Dict[str, Any]) -> bool:- gh = _gateway_health_config(config)- otlp = _otlp_config(config)- return bool(gh.get("enabled") and otlp.get("enabled") and otlp.get("endpoint"))+ return bool(_gateway_health_config(config).get("enabled") and otlp_exporter.is_enabled(config))def _require_metrics_sdk(*, auto_install: bool = True, prompt: bool = False) -> Dict[str, Any]:- if auto_install:- try:- from tools.lazy_deps import ensure as _lazy_ensure- _lazy_ensure("export.otlp", prompt=prompt)- except Exception:- passtry:- from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter- from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter- from opentelemetry.metrics import Observation- from opentelemetry.trace import INVALID_SPAN_ID, INVALID_TRACE_ID, TraceFlags- from opentelemetry._logs import LogRecord- from opentelemetry._logs.severity import SeverityNumber- from opentelemetry.sdk._logs import LoggerProvider- from opentelemetry.sdk._logs.export import BatchLogRecordProcessor- from opentelemetry.sdk.metrics import MeterProvider- from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader- from opentelemetry.sdk.resources import Resource- return {- "OTLPLogExporter": OTLPLogExporter,- "OTLPMetricExporter": OTLPMetricExporter,- "Observation": Observation,- "LogRecord": LogRecord,- "LoggerProvider": LoggerProvider,- "INVALID_SPAN_ID": INVALID_SPAN_ID,- "INVALID_TRACE_ID": INVALID_TRACE_ID,- "TraceFlags": TraceFlags,- "SeverityNumber": SeverityNumber,- "BatchLogRecordProcessor": BatchLogRecordProcessor,- "MeterProvider": MeterProvider,- "PeriodicExportingMetricReader": PeriodicExportingMetricReader,- "Resource": Resource,- }+ return otlp_exporter._require_sdk(_METRICS_SDK, auto_install=auto_install, prompt=prompt)except Exception as exc:raise RuntimeError(f"OTLP metrics SDK unavailable: {exc}") from exc-def _resolve_headers(headers_env: Optional[Dict[str, str]]) -> Dict[str, str]:- resolved: Dict[str, str] = {}- for header_name, env_name in (headers_env or {}).items():- val = os.environ.get(str(env_name))- if val:- resolved[str(header_name)] = val- return resolved---def _metric_endpoint(endpoint: str) -> str:- if endpoint.endswith("/v1/traces"):- return endpoint[: -len("/v1/traces")] + "/v1/metrics"- return endpoint---def _logs_endpoint(endpoint: str) -> str:- if endpoint.endswith("/v1/traces"):- return endpoint[: -len("/v1/traces")] + "/v1/logs"- if endpoint.endswith("/v1/metrics"):- return endpoint[: -len("/v1/metrics")] + "/v1/logs"- return endpoint-+def _exporter_kwargs(config: Dict[str, Any], signal: str) -> Dict[str, Any]:+ otlp = _otlp_config(config)+ return {+ "endpoint": _signal_endpoint(str(otlp.get("endpoint")), signal),+ "headers": _resolve_headers(otlp.get("headers_env")) or None,+ }-def _version() -> str:- try:- from hermes_cli import __version__- return str(__version__)- except Exception:- return "unknown"+def _resource(config: Dict[str, Any], sdk: Dict[str, Any], telemetry_scope: str) -> Any:+ return sdk["Resource"].create(_runtime_resource_attributes(config, telemetry_scope=telemetry_scope))-def _profile() -> str:- try:- from hermes_cli.profiles import get_active_profile_name- return str(get_active_profile_name() or "default")- except Exception:- return "default"--def _install_id(config: Dict[str, Any]) -> str:- try:- from agent.monitoring.policy import ensure_install_id- return str(ensure_install_id(config))- except Exception:- return "unknown"+# Ordered detection: systemd > s6 > container > launchd > manual (first match wins).+_SUPERVISION_DETECTORS: tuple[tuple[str, Callable[[], Any]], ...] = (+ ("systemd", lambda: os.environ.get("INVOCATION_ID")),+ ("s6", lambda: os.environ.get("S6_CMD_ARG0") or os.environ.get("S6_VERSION")),+ ("container", lambda: os.environ.get("container") or os.path.exists("/.dockerenv")),+ ("launchd", lambda: os.environ.get("LAUNCHD_SOCKET")),+)def _supervision_mode() -> str:- if os.environ.get("INVOCATION_ID"):- return "systemd"- if os.environ.get("S6_CMD_ARG0") or os.environ.get("S6_VERSION"):- return "s6"- if os.environ.get("container") or os.path.exists("/.dockerenv"):- return "container"- if os.environ.get("LAUNCHD_SOCKET"):- return "launchd"- return "manual"+ return next((mode for mode, detect in _SUPERVISION_DETECTORS if detect()), "manual")def _read_gateway_snapshot(config: Dict[str, Any]):- from agent.monitoring.gateway_health import build_gateway_health_snapshottry:from gateway.status import read_runtime_statusruntime = read_runtime_status() or {}@@ -301,83 +187,51 @@ def _read_cron_snapshot():return build_cron_health_snapshot()-def _read_background_work_count() -> int:- """Count live background/subagent work that ``active_agents`` does NOT include.-- ``hermes.gateway.active_agents`` counts foreground turns + in-flight cron- jobs + API runs, but deliberately excludes backgrounded ``delegate_task``- subagents, ``terminal(background=true)`` processes, kanban workers, and the- runner's own background tasks (they are tracked only for the scale-to-zero- suspend guard, ``_scale_to_zero_has_live_background_work``). Without this- metric a peer churning through delegated subagents shows ``active_agents=0``- on the fleet dashboard. Best-effort and content-free: a single integer,- no job/task identity. Returns 0 if a source can't be imported.-- Delegation is counted TASK-granular (``active_task_count``): a fan-out batch- of N subagents contributes N, not 1, so the metric reflects real concurrent- subagent load rather than dispatch-unit/pool-slot count. This intentionally- differs from the async pool's capacity accounting (one batch = one slot).- """- total = 0+def _count(failure_msg: str, module: str, read: Callable[[Any], Any]) -> int:+ """Best-effort non-negative count read from a lazily imported module; 0 when it can't be imported/read."""try:- from tools.async_delegation import active_task_count-- total += max(0, int(active_task_count()))+ return max(0, int(read(importlib.import_module(module))))except Exception:- logger.debug("background-work async-delegation count failed", exc_info=True)- try:- from tools.process_registry import process_registry+ logger.debug(failure_msg, exc_info=True)+ return 0- total += max(0, int(process_registry.count_running()))- except Exception:- logger.debug("background-work process-registry count failed", exc_info=True)- return total+def _read_background_work_count() -> int:+ """Live background/subagent work that ``active_agents`` deliberately does NOT include.-def _read_background_delegations_count() -> int:- """Count live async delegation UNITS (dispatch/pool slots).-- Complements ``_read_background_work_count`` (which is task-granular): this- counts each ``delegate_task`` dispatch as ONE regardless of fan-out width,- matching the async pool's capacity accounting (a batch = one slot). Together- the two metrics let an operator see both slot pressure- (``background_delegations``, alert vs ``max_concurrent_children``) and real- concurrent subagent load (``background_work``). Delegations only — it does- not include ``terminal(background)`` / kanban work, which are already folded- into ``background_work``. Best-effort; 0 if the source can't be imported.+ ``active_agents`` counts foreground turns + in-flight cron + API runs; backgrounded+ ``delegate_task`` subagents, ``terminal(background=true)`` processes and kanban workers+ are tracked only by the scale-to-zero guard, so without this a peer churning through+ subagents shows ``active_agents=0``. TASK-granular: a fan-out batch of N contributes N+ (real concurrent load), unlike the pool's one-slot-per-batch accounting. Content-free."""- try:- from tools.async_delegation import active_count+ return (+ _count("background-work async-delegation count failed", "tools.async_delegation",+ lambda m: m.active_task_count())+ + _count("background-work process-registry count failed", "tools.process_registry",+ lambda m: m.process_registry.count_running())+ )- return max(0, int(active_count()))- except Exception:- logger.debug("background-delegations count failed", exc_info=True)- return 0++def _read_background_delegations_count() -> int:+ """Live async delegation UNITS (dispatch/pool slots): a batch counts ONE regardless of+ fan-out width, matching the pool's capacity accounting — so operators can see slot+ pressure (alert vs ``max_concurrent_children``) alongside ``background_work``'s real load.+ Delegations only; terminal/kanban work is already folded into ``background_work``."""+ return _count("background-delegations count failed", "tools.async_delegation", lambda m: m.active_count())def _read_runtime_snapshot(config: Dict[str, Any]):gateway_snapshot = _read_gateway_snapshot(config)- # Background/subagent work — a distinct metric from active_agents (which- # never counts it). Appended to the gateway snapshot so it rides the same- # base resource attributes (service.instance.id etc.).+ # Background/subagent work is appended to the gateway snapshot so it rides the same base+ # resource attributes (service.instance.id etc.).try:- from agent.monitoring.gateway_health import GatewayMetric-base = dict(gateway_snapshot.metrics[0].attributes) if gateway_snapshot.metrics else {}- gateway_snapshot.metrics.append(- GatewayMetric(- name="hermes.gateway.background_work",- value=_read_background_work_count(),- attributes=base,- )- )- gateway_snapshot.metrics.append(- GatewayMetric(- name="hermes.gateway.background_delegations",- value=_read_background_delegations_count(),- attributes=base,- )- )+ for name, read in (+ ("hermes.gateway.background_work", _read_background_work_count),+ ("hermes.gateway.background_delegations", _read_background_delegations_count),+ ):+ gateway_snapshot.metrics.append(GatewayMetric(name=name, value=read(), attributes=base))except Exception as exc:logger.warning("background-work snapshot unavailable; metric not exported (error_type=%s)",@@ -387,10 +241,8 @@ def _read_runtime_snapshot(config: Dict[str, Any]):try:cron_snapshot = _read_cron_snapshot()except Exception as exc:- # Content-free visibility: cron telemetry silently dropping out is a- # release-relevant regression, so surface it at WARNING with only the- # exception *type* name (never the message, which could carry paths or- # other environment detail). exc_info stays on the DEBUG record.+ # Cron telemetry silently dropping out is a release-relevant regression: WARN with only+ # the exception *type* (the message could carry paths); exc_info stays on DEBUG.logger.warning("cron health snapshot unavailable; cron telemetry not exported (error_type=%s)",type(exc).__name__,@@ -402,13 +254,10 @@ def _read_runtime_snapshot(config: Dict[str, Any]):def _emit_snapshot_events(config: Dict[str, Any]) -> None:- gh = _gateway_health_config(config)- if not gh.get("diagnostic_events_enabled", True):+ if not _gateway_health_config(config).get("diagnostic_events_enabled", True):returntry:- from agent.monitoring import emitter- snapshot = _read_runtime_snapshot(config)- for event in snapshot.events:+ for event in _read_runtime_snapshot(config).events:emitter.emit(event)except Exception:logger.debug("gateway health snapshot emit failed", exc_info=True)@@ -416,43 +265,15 @@ def _emit_snapshot_events(config: Dict[str, Any]) -> None:def _start_metric_provider(config: Dict[str, Any], sdk: Dict[str, Any]) -> Any:gh = _gateway_health_config(config)- if not gh.get("metrics_enabled", True):- return None- otlp = _otlp_config(config)- endpoint = _metric_endpoint(str(otlp.get("endpoint")))- headers = _resolve_headers(otlp.get("headers_env"))- exporter = sdk["OTLPMetricExporter"](endpoint=endpoint, headers=headers or None)+ exporter = sdk["OTLPMetricExporter"](**_exporter_kwargs(config, "metrics"))interval_ms = max(5, int(gh.get("export_interval_seconds", 60))) * 1000reader = sdk["PeriodicExportingMetricReader"](exporter, export_interval_millis=interval_ms)- resource_attrs = _runtime_resource_attributes(- config, telemetry_scope="gateway_health"- )provider = sdk["MeterProvider"](- metric_readers=[reader],- resource=sdk["Resource"].create(resource_attrs),+ metric_readers=[reader], resource=_resource(config, sdk, "gateway_health"))meter = provider.get_meter("hermes.gateway.health")Observation = sdk["Observation"]- metric_names = [- "hermes.gateway.up",- "hermes.gateway.state",- "hermes.gateway.active_agents",- "hermes.gateway.busy",- "hermes.gateway.drainable",- "hermes.gateway.restart_requested",- "hermes.gateway.background_work",- "hermes.gateway.background_delegations",- "hermes.platform.up",- "hermes.platform.degraded",- "hermes.cron.scheduler.heartbeat_age_seconds",- "hermes.cron.scheduler.last_success_age_seconds",- "hermes.cron.scheduler.catch_up_occurrences",- "hermes.cron.jobs.enabled",- "hermes.cron.jobs.running",- "hermes.cron.jobs.overdue",- ]-def callback(name: str):def _cb(_options=None):try:@@ -463,98 +284,61 @@ def _start_metric_provider(config: Dict[str, Any], sdk: Dict[str, Any]) -> Any:return []return _cb- for metric_name in metric_names:+ for metric_name in _OBSERVABLE_METRIC_NAMES:meter.create_observable_gauge(metric_name, callbacks=[callback(metric_name)])return provider+_SEVERITY_NAMES = {+ "critical": "FATAL",+ "fatal": "FATAL",+ "error": "ERROR",+ "info": "INFO",+ "information": "INFO",+ "debug": "DEBUG",+}++def _severity_number(sdk: Dict[str, Any], severity: Any) -> Any:- SeverityNumber = sdk["SeverityNumber"]sev = str(severity or "warning").lower()- if sev in {"critical", "fatal"}:- return SeverityNumber.FATAL- if sev == "error":- return SeverityNumber.ERROR- if sev in {"info", "information"}:- return SeverityNumber.INFO- if sev == "debug":- return SeverityNumber.DEBUG- return SeverityNumber.WARN---class GatewayDiagnosticLogStreamer:+ return getattr(sdk["SeverityNumber"], _SEVERITY_NAMES.get(sev, "WARN"))+++class GatewayDiagnosticLogStreamer(EmitterStreamer):"""Emitter subscriber that sends gateway diagnostic events as OTLP logs."""def __init__(self, config: Dict[str, Any], sdk: Dict[str, Any]):- otlp = _otlp_config(config)- headers = _resolve_headers(otlp.get("headers_env"))- endpoint = _logs_endpoint(str(otlp.get("endpoint")))- resource_attrs = _runtime_resource_attributes(- config, telemetry_scope="gateway_diagnostics"- )- self._provider = sdk["LoggerProvider"](resource=sdk["Resource"].create(resource_attrs))+ self._provider = sdk["LoggerProvider"](resource=_resource(config, sdk, "gateway_diagnostics"))self._processor = sdk["BatchLogRecordProcessor"](- sdk["OTLPLogExporter"](endpoint=endpoint, headers=headers or None)+ sdk["OTLPLogExporter"](**_exporter_kwargs(config, "logs")))self._provider.add_log_record_processor(self._processor)self._logger = self._provider.get_logger(_DEFAULT_DIAGNOSTIC_SCOPE)- self._LogRecord = sdk["LogRecord"]self._sdk = sdkself.exported = 0def __call__(self, batch: list[Dict[str, Any]]) -> None:- from agent.monitoring.gateway_health import source_logger_for_export-+ sdk = self._sdkfor ev in batch:if ev.get("event") != "gateway_diagnostic":continue- attrs = _diagnostic_log_attributes(ev)- # Preserve the source-controlled Python logger as the OTel- # instrumentation scope. This adds precise code attribution without- # turning a fluid module layout into a maintained subsystem enum.- # Rendered messages stay out because they may contain arbitrary IDs,- # names, paths, or configured strings. A future, separately gated- # ``diagnostic_detail: redacted_message`` mode may add best-effort- # free text when an observability plane defines that privacy policy.+ # The source-controlled Python logger becomes the OTel instrumentation scope:+ # precise code attribution without maintaining a subsystem enum. Rendered+ # messages stay out (they may carry IDs, names, paths, configured strings).source_logger = source_logger_for_export(ev.get("source_logger"))- otel_logger = (- self._provider.get_logger(source_logger)- if source_logger is not None- else self._logger- )- body = "gateway diagnostic"- record = self._LogRecord(+ otel_logger = self._provider.get_logger(source_logger) if source_logger is not None else self._logger+ otel_logger.emit(sdk["LogRecord"](timestamp=ev.get("ts_ns"),- trace_id=self._sdk["INVALID_TRACE_ID"],- span_id=self._sdk["INVALID_SPAN_ID"],- trace_flags=self._sdk["TraceFlags"].DEFAULT,+ trace_id=sdk["INVALID_TRACE_ID"],+ span_id=sdk["INVALID_SPAN_ID"],+ trace_flags=sdk["TraceFlags"].DEFAULT,severity_text=str(ev.get("severity") or "warning").upper(),- severity_number=_severity_number(self._sdk, ev.get("severity")),- body=_redact_string(body),- attributes=attrs,- )- otel_logger.emit(record)+ severity_number=_severity_number(sdk, ev.get("severity")),+ body=redact_bounded("gateway diagnostic"),+ attributes=_diagnostic_log_attributes(ev),+ ))self.exported += 1- def shutdown(self) -> None:- try:- from agent.monitoring.emitter import get_emitter- get_emitter().unsubscribe(self)- except Exception:- pass- try:- self._processor.force_flush()- self._provider.shutdown()- except Exception:- pass---def _start_diagnostic_log_streamer(config: Dict[str, Any], sdk: Dict[str, Any]) -> GatewayDiagnosticLogStreamer:- from agent.monitoring.emitter import get_emitter- streamer = GatewayDiagnosticLogStreamer(config, sdk)- get_emitter().subscribe(streamer)- return streamer-def _start_snapshot_thread(config: Dict[str, Any], stop_event: threading.Event) -> threading.Thread:interval = max(5, int(_gateway_health_config(config).get("logs_export_interval_seconds", 5)))@@ -572,7 +356,6 @@ def _attach_log_handler(config: Dict[str, Any]) -> Any:gh = _gateway_health_config(config)if not gh.get("diagnostic_events_enabled", True) or not gh.get("warning_error_events_enabled", True):return None- from agent.monitoring.gateway_health import GatewayDiagnosticLogHandlerhandler = GatewayDiagnosticLogHandler(profile=_profile(), version=_version())root = logging.getLogger()if handler not in root.handlers:@@ -589,10 +372,12 @@ def start_gateway_health_export(config: Dict[str, Any]) -> GatewayHealthExportRuif not _enabled(config):return GatewayHealthExportRuntime(enabled=False, reason="disabled")gh = _gateway_health_config(config)+ metrics_on = gh.get("metrics_enabled", True)+ diagnostics_on = gh.get("diagnostic_events_enabled", True)runtime = GatewayHealthExportRuntime(enabled=True, reason="enabled")sdk: Optional[Dict[str, Any]] = None- if gh.get("metrics_enabled", True) or gh.get("diagnostic_events_enabled", True):+ if metrics_on or diagnostics_on:try:sdk = _require_metrics_sdk(prompt=False)except Exception:@@ -603,7 +388,7 @@ def start_gateway_health_export(config: Dict[str, Any]) -> GatewayHealthExportRu)return GatewayHealthExportRuntime(enabled=False, reason="otlp_unavailable")- if gh.get("metrics_enabled", True) and sdk is not None:+ if metrics_on and sdk is not None:try:runtime.metric_provider = _start_metric_provider(config, sdk)except Exception:@@ -611,13 +396,14 @@ def start_gateway_health_export(config: Dict[str, Any]) -> GatewayHealthExportRuruntime.shutdown()return GatewayHealthExportRuntime(enabled=False, reason="metrics_start_failed")- if gh.get("diagnostic_events_enabled", True) and sdk is not None:+ if diagnostics_on and sdk is not None:try:- from agent.monitoring import otlp_exporterruntime.streamer = otlp_exporter.start_streaming(config, event_filter=_gateway_health_event)if runtime.streamer is None:raise RuntimeError("gateway health span streamer did not start")- runtime.log_streamer = _start_diagnostic_log_streamer(config, sdk)+ log_streamer = GatewayDiagnosticLogStreamer(config, sdk)+ emitter.get_emitter().subscribe(log_streamer)+ runtime.log_streamer = log_streamerexcept Exception:logger.debug("gateway diagnostic OTLP export failed to start", exc_info=True)runtime.shutdown()@@ -627,7 +413,7 @@ def start_gateway_health_export(config: Dict[str, Any]) -> GatewayHealthExportRuruntime.log_handler = _attach_log_handler(config)except Exception:logger.debug("gateway diagnostic log handler failed to attach", exc_info=True)- if gh.get("diagnostic_events_enabled", True):+ if diagnostics_on:try:_emit_snapshot_events(config)runtime.stop_event = threading.Event()diff --git a/agent/monitoring/otlp_exporter.py b/agent/monitoring/otlp_exporter.pyindex 17c85cb8b6a..f1c12fa4dcd 100644--- a/agent/monitoring/otlp_exporter.py+++ b/agent/monitoring/otlp_exporter.py@@ -1,31 +1,30 @@"""Export monitoring events to an OpenTelemetry Collector over OTLP/HTTP.-Maps gateway monitoring events to OTel spans and sends them to the endpoint-configured under ``monitoring.export.otlp``. Lets an operator stream Hermes-gateway health into their own observability stack (OTEL Collector, DataDog,-and similar).--Notes:- * The destination is operator-configured; this module only sends to that- endpoint. No default destination ships.- * ``opentelemetry-sdk`` + ``opentelemetry-exporter-otlp-proto-http`` are an- optional extra (``pip install hermes-agent[otlp]``), imported lazily so the- dependency is only required when OTLP export is actually used.- * ``headers_env`` maps a header name to an environment variable name; values- are read from the environment at export time and never logged or stored.- * The continuous subscriber runs in the emitter's dispatcher thread and is- fail-isolated, so an export error cannot affect the gateway.--Only monitoring events (gateway_health / gateway_diagnostic) exist on this-plane; the ``event_filter`` seam is kept so future planes sharing the emitter-cannot silently ride along on this exporter.+Maps gateway monitoring events to OTel spans and sends them to the operator+configured ``monitoring.export.otlp`` endpoint (no default destination ships).+Also hosts the OTLP plumbing shared with ``gateway_health_export`` (SDK loading,+header resolution, resource attributes, endpoint mapping).++* The OTel SDK is an optional extra (``pip install hermes-agent[otlp]``),+ imported lazily so it is only required when export is actually used.+* ``headers_env`` maps a header name to an environment variable name; values+ are read from the environment at export time and never logged or stored.+* The continuous subscriber runs in the emitter's dispatcher thread and is+ fail-isolated, so an export error cannot affect the gateway. The+ ``event_filter`` seam keeps future planes sharing the emitter from silently+ riding along on this exporter."""from __future__ import annotations+import importlibimport loggingimport os-from typing import Any, Callable, Dict, List, Optional+import re+from typing import Any, Callable, Dict, Iterable, List, Optional++from agent.monitoring.gateway_health import _safe_instance_id+from agent.monitoring.redaction import redact_boundedlogger = logging.getLogger(__name__)@@ -34,43 +33,49 @@ class OTLPUnavailable(RuntimeError):"""Raised when the optional OpenTelemetry SDK isn't installed."""-def _require_sdk(*, auto_install: bool = True, prompt: bool = True):- """Import the OTel SDK, lazily installing it on first use if needed.-- Routes through tools.lazy_deps (feature 'export.otlp') so a missing SDK- triggers the standard venv install flow — same as every other optional- backend — gated by security.allow_lazy_installs and TTY-prompted. Falls back- to OTLPUnavailable (with a manual install hint) when the SDK can't be made- importable (lazy installs disabled, install failed, or auto_install=False).-- ``auto_install``: attempt the lazy install when missing (default True).- ``prompt``: ask before installing when interactive (default True); pass- False from non-interactive contexts like the continuous streamer.+# ── SDK loading ──────────────────────────────────────────────────────────────+_SDK_SYMBOLS: Dict[str, str] = {+ "TracerProvider": "opentelemetry.sdk.trace",+ "BatchSpanProcessor": "opentelemetry.sdk.trace.export",+ "Resource": "opentelemetry.sdk.resources",+ "OTLPSpanExporter": "opentelemetry.exporter.otlp.proto.http.trace_exporter",+ "SpanKind": "opentelemetry.trace",+ "OTLPLogExporter": "opentelemetry.exporter.otlp.proto.http._log_exporter",+ "OTLPMetricExporter": "opentelemetry.exporter.otlp.proto.http.metric_exporter",+ "Observation": "opentelemetry.metrics",+ "INVALID_SPAN_ID": "opentelemetry.trace",+ "INVALID_TRACE_ID": "opentelemetry.trace",+ "TraceFlags": "opentelemetry.trace",+ "LogRecord": "opentelemetry._logs",+ "SeverityNumber": "opentelemetry._logs.severity",+ "LoggerProvider": "opentelemetry.sdk._logs",+ "BatchLogRecordProcessor": "opentelemetry.sdk._logs.export",+ "MeterProvider": "opentelemetry.sdk.metrics",+ "PeriodicExportingMetricReader": "opentelemetry.sdk.metrics.export",+}+_SPAN_SDK = ("TracerProvider", "BatchSpanProcessor", "Resource", "OTLPSpanExporter", "SpanKind")+++def _require_sdk(+ names: Iterable[str] = _SPAN_SDK, *, auto_install: bool = True, prompt: bool = True+) -> Dict[str, Any]:+ """Import the named OTel SDK symbols, lazily installing the extra on first use.++ Routes through tools.lazy_deps (feature 'export.otlp') — gated by+ security.allow_lazy_installs and TTY-prompted (``prompt=False`` from+ non-interactive contexts). Any lazy-install failure falls through to the+ import attempt, which raises OTLPUnavailable with a manual install hint."""if auto_install:try:from tools.lazy_deps import ensure as _lazy_ensure_lazy_ensure("export.otlp", prompt=prompt)- except ImportError:- pass # lazy_deps unavailable — fall through to the import attemptexcept Exception:- # FeatureUnavailable (lazy installs disabled / declined / failed) —- # fall through; the import below raises OTLPUnavailable with the hint.passtry:- from opentelemetry.sdk.trace import TracerProvider- from opentelemetry.sdk.trace.export import BatchSpanProcessor- from opentelemetry.sdk.resources import Resource- from opentelemetry.exporter.otlp.proto.http.trace_exporter import (- OTLPSpanExporter,- )- from opentelemetry.trace import SpanKindreturn {- "TracerProvider": TracerProvider,- "BatchSpanProcessor": BatchSpanProcessor,- "Resource": Resource,- "OTLPSpanExporter": OTLPSpanExporter,- "SpanKind": SpanKind,+ name: getattr(importlib.import_module(_SDK_SYMBOLS[name]), name)+ for name in names}except Exception as e: # ImportError or partial installraise OTLPUnavailable(@@ -80,28 +85,89 @@ def _require_sdk(*, auto_install: bool = True, prompt: bool = True):)-def _resolve_headers(headers_env: Optional[Dict[str, str]]) -> Dict[str, str]:- """Resolve {header_name: ENV_VAR_NAME} -> {header_name: value} from env.+# ── config + connection plumbing ─────────────────────────────────────────────+def _monitoring_section(config: Dict[str, Any], *path: str) -> Dict[str, Any]:+ node: Any = (config or {}).get("monitoring") or {}+ for key in path:+ node = node.get(key) or {}+ return node- The config stores environment variable names, not secret values; values are- read from the environment here. Missing variables are skipped (and noted at- debug level without the value).- """++def _otlp_config(config: Dict[str, Any]) -> Dict[str, Any]:+ return _monitoring_section(config, "export", "otlp")+++def _resolve_headers(headers_env: Optional[Dict[str, str]]) -> Dict[str, str]:+ """Resolve {header_name: ENV_VAR_NAME} -> {header_name: value}; missing vars skipped."""resolved: Dict[str, str] = {}for header_name, env_name in (headers_env or {}).items():val = os.environ.get(str(env_name))if val:resolved[str(header_name)] = valelse:- logger.debug("OTLP header %s: env var %s not set; skipping",- header_name, env_name)+ logger.debug("OTLP header %s: env var %s not set; skipping", header_name, env_name)return resolved-def _otlp_config(config: Dict[str, Any]) -> Dict[str, Any]:- mon = (config or {}).get("monitoring") or {}- export = mon.get("export") or {}- return export.get("otlp") or {}+_SIGNAL_SUFFIXES = ("/v1/traces", "/v1/metrics")+++def _signal_endpoint(endpoint: str, signal: str) -> str:+ """Rewrite a traces/metrics OTLP path to ``/v1/<signal>``; other paths pass through."""+ target = f"/v1/{signal}"+ for suffix in _SIGNAL_SUFFIXES:+ if suffix != target and endpoint.endswith(suffix):+ return endpoint[: -len(suffix)] + target+ return endpoint+++_RESOURCE_ATTRIBUTE_KEYS = frozenset({+ "service.name",+ "service.namespace",+ "service.version",+ "service.instance.id",+ "deployment.environment.name",+ "cloud.provider",+ "cloud.platform",+ "cloud.region",+ "telemetry.scope",+})+_SAFE_RESOURCE_VALUE = re.compile(r"^[A-Za-z0-9._:/-]{1,128}$")+++def _install_id(config: Dict[str, Any]) -> str:+ try:+ from agent.monitoring.policy import ensure_install_id+ return str(ensure_install_id(config))+ except Exception:+ return "unknown"+++def _safe_resource_attributes(raw: Any) -> Dict[str, str]:+ """Allowlist bounded resource labels and reject values changed by redaction."""+ attrs: Dict[str, str] = {}+ for key, value in (raw.items() if isinstance(raw, dict) else ()):+ key = str(key)+ if key not in _RESOURCE_ATTRIBUTE_KEYS or value is None:+ continue+ text = str(value)+ if key == "service.instance.id":+ attrs[key] = _safe_instance_id(value)+ elif _SAFE_RESOURCE_VALUE.fullmatch(text) and redact_bounded(text, limit=128) == text:+ attrs[key] = text+ return attrs+++def _runtime_resource_attributes(+ config: Dict[str, Any], *, telemetry_scope: str+) -> Dict[str, str]:+ """Build the safe OTLP resource shared by spans, metrics and diagnostic logs."""+ gh = _monitoring_section(config, "gateway_health_export")+ attrs = _safe_resource_attributes(gh.get("resource_attributes"))+ attrs["service.name"] = "hermes-gateway"+ attrs["service.instance.id"] = _safe_instance_id(_install_id(config))+ attrs["telemetry.scope"] = telemetry_scope+ return attrsdef build_exporter(config: Dict[str, Any]):@@ -116,11 +182,6 @@ def build_exporter(config: Dict[str, Any]):def _resource_attributes(config: Dict[str, Any]) -> Dict[str, str]:- # Lazy import: gateway_health_export imports this module back (for- # start_streaming), so the dependency must resolve at call time, not- # at module load, to avoid a circular import.- from agent.monitoring.gateway_health_export import _runtime_resource_attributes-return _runtime_resource_attributes(config, telemetry_scope="gateway_monitoring")@@ -134,32 +195,36 @@ def _make_provider(config: Dict[str, Any]):# ── event -> span attribute mapping ──────────────────────────────────────────+# Per-kind attribute allowlists: everything else (profile, install_id, ...) never egresses.+_KEEP_BY_KIND: Dict[str, tuple[str, ...]] = {+ "gateway_health": ("name", "gateway_state", "old_state", "new_state",+ "exit_reason", "restart_requested", "active_agents",+ "gateway_busy", "gateway_drainable", "platform_count",+ "fatal_platform_count", "version",+ "supervision_mode", "pid"),+ "gateway_diagnostic": ("name", "subsystem", "error_class", "error_code",+ "platform", "old_state", "new_state",+ "version", "severity"),+ "cron_execution": ("status", "job_key", "source", "duration_ms",+ "delivery_outcome", "error_class"),+}+++def _allowlisted_attrs(ev: Dict[str, Any], keys: Iterable[str]) -> Dict[str, Any]:+ """``hermes.<key>`` attributes for present keys; string values are redacted and bounded."""+ attrs: Dict[str, Any] = {}+ for col in keys:+ v = ev.get(col)+ if v is not None:+ attrs[f"hermes.{col}"] = redact_bounded(v) if isinstance(v, str) else v+ return attrs++def _span_attrs(ev: Dict[str, Any]) -> Dict[str, Any]:"""Span attributes for a monitoring event (content-free by construction)."""kind = ev.get("event")attrs: Dict[str, Any] = {"hermes.event": kind or "unknown"}- keep_by_kind = {- "gateway_health": ("name", "gateway_state", "old_state", "new_state",- "exit_reason", "restart_requested", "active_agents",- "gateway_busy", "gateway_drainable", "platform_count",- "fatal_platform_count", "version",- "supervision_mode", "pid"),- "gateway_diagnostic": ("name", "subsystem", "error_class", "error_code",- "platform", "old_state", "new_state",- "version", "severity"),- "cron_execution": ("status", "job_key", "source", "duration_ms",- "delivery_outcome", "error_class"),- }- for col in keep_by_kind.get(kind, ()): # type: ignore[arg-type]- v = ev.get(col)- if v is not None:- if isinstance(v, str):- try:- from agent.monitoring.redaction import redact_for_export- v = (redact_for_export(v) or "[redacted]")[:500]- except Exception:- v = "[redaction-unavailable]"- attrs[f"hermes.{col}"] = v+ attrs.update(_allowlisted_attrs(ev, _KEEP_BY_KIND.get(kind, ()))) # type: ignore[arg-type]return attrs@@ -178,13 +243,33 @@ def export_batch(provider, batch: List[Dict[str, Any]]) -> int:return n-# ── continuous streaming subscriber ─────────────────────────────────────────-class OTLPStreamer:- """A live subscriber that pushes each emitter batch to OTLP as it lands.+# ── continuous streaming subscribers ─────────────────────────────────────────+class EmitterStreamer:+ """Base for emitter subscribers owning an OTel provider + batch processor.Register with ``emitter.subscribe(streamer)``. Fail-isolated by the emitter."""+ _provider: Any+ _processor: Any+ exported: int = 0++ def shutdown(self) -> None:+ try:+ from agent.monitoring.emitter import get_emitter+ get_emitter().unsubscribe(self)+ except Exception:+ pass+ try:+ self._processor.force_flush()+ self._provider.shutdown()+ except Exception:+ pass+++class OTLPStreamer(EmitterStreamer):+ """A live subscriber that pushes each emitter batch to OTLP as spans."""+def __init__(self,config: Dict[str, Any],@@ -202,22 +287,9 @@ class OTLPStreamer:returnself.exported += export_batch(self._provider, batch)- def shutdown(self) -> None:- try:- from agent.monitoring.emitter import get_emitter- get_emitter().unsubscribe(self)- except Exception:- pass- try:- self._processor.force_flush()- self._provider.shutdown()- except Exception:- pass-def is_available() -> bool:- """True when the OTel SDK is already importable. Does NOT auto-install —- this is a pure check (e.g. for status display)."""+ """True when the OTel SDK is already importable (pure check, no auto-install)."""try:_require_sdk(auto_install=False)return True@@ -237,13 +309,10 @@ def start_streaming() -> Optional[OTLPStreamer]:"""If OTLP is enabled, attach a streamer to the singleton emitter.- ``event_filter`` scopes the exporter to its plane, e.g. gateway-health- export, so enabling one plane cannot silently export unrelated events.-- Non-interactive context (startup): attempts a lazy install with prompt=False- so a configured-but-missing SDK is installed once (gated by- security.allow_lazy_installs), then streams. If it still can't load, logs and- no-ops — never blocks or raises into startup.+ ``event_filter`` scopes the exporter to its plane. Startup is non-interactive:+ a configured-but-missing SDK is lazily installed once (prompt=False, gated by+ security.allow_lazy_installs); if it still can't load, log and no-op — never+ raise into startup."""if not is_enabled(config):return Nonediff --git a/agent/monitoring/policy.py b/agent/monitoring/policy.pyindex 1a42ce195ca..0939fbbc67a 100644--- a/agent/monitoring/policy.py+++ b/agent/monitoring/policy.py@@ -1,9 +1,8 @@"""Install identity for gateway monitoring.-The install id is a stable, resettable pseudonymous identifier attached to-exported health signals so an operator can tell instances apart in their-collector. It carries no account identity and can be rotated by clearing-``monitoring.install_id`` in config.+A stable, resettable pseudonymous id attached to exported health signals so an+operator can tell instances apart. Carries no account identity; rotate by+clearing ``monitoring.install_id`` in config."""from __future__ import annotations@@ -18,14 +17,9 @@ logger = logging.getLogger(__name__)def ensure_install_id(config: Dict[str, Any]) -> str:"""Return a stable install id, minting and persisting one when empty.- The id must survive gateway restarts (it becomes ``service.instance.id``- on exported signals), so a freshly minted UUID is written back to- config.yaml immediately. The write is fail-open: if persisting fails- (read-only home, managed scope), the ephemeral id is still returned and- a new one is minted next start.-- Clearing ``monitoring.install_id`` (e.g. ``hermes config set- monitoring.install_id ""``) rotates the id on the next gateway start.+ The id becomes ``service.instance.id`` and must survive restarts, so a fresh+ UUID is written to config.yaml immediately. Fail-open: if persisting fails+ (read-only home, managed scope) the ephemeral id is still returned."""mon = config.get("monitoring") if isinstance(config, dict) else Noneexisting = (mon or {}).get("install_id") if isinstance(mon, dict) else Nonediff --git a/agent/monitoring/redaction.py b/agent/monitoring/redaction.pyindex 312875901e6..22ae1c09049 100644--- a/agent/monitoring/redaction.py+++ b/agent/monitoring/redaction.py@@ -1,24 +1,17 @@"""Redaction applied to monitoring data before egress.One unconditional scrub, no modes, no knobs. Every string that leaves the-process passes through ``redact_for_export``:-- * Secrets first — wraps ``agent/redact.py::redact_sensitive_text(force=True)``- plus bearer/token-shape patterns, and fails CLOSED: if the redactor cannot- run, the raw string is never emitted.- * PII second — e-mail addresses, phone numbers, and UUID-shaped identifiers- are rewritten to ``[email]`` / ``[phone]`` / ``[id]``.--There is deliberately no setting to weaken this. The monitoring plane is-content-free by design: rendered log messages are not exported, and bounded-structured strings are still scrubbed as defense-in-depth. This redactor also-remains available for a future, explicitly gated redacted-message detail mode.+process passes through ``redact_for_export``: secrets first (wraps+``agent/redact.py::redact_sensitive_text(force=True)`` plus bearer/token+shapes, failing CLOSED so a broken redactor never emits the raw string), then+PII (e-mail, phone, UUID-shaped ids -> ``[email]`` / ``[phone]`` / ``[id]``).+There is deliberately no setting to weaken this."""from __future__ import annotationsimport re-from typing import Optional+from typing import Any, Optional# ── secret shapes (belt-and-suspenders on top of agent/redact.py) ───────────_BEARER_RE = re.compile(r"\bBearer\s+[A-Za-z0-9._~+\-/]+=*", re.IGNORECASE)@@ -34,11 +27,12 @@ _EMAIL_RE = re.compile(r"[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}")_PHONE_RE = re.compile(r"(?<!\w)(?:\+?\d{1,3}[\s.\-]?)?(?:\(\d{2,4}\)[\s.\-]?)?\d{3}[\s.\-]?\d{3,4}(?:[\s.\-]?\d{2,4})?(?!\w)")-# Long opaque hex/uuid-ish user identifiers._UUID_RE = re.compile(r"\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b")+UNAVAILABLE = "[redaction-unavailable]"+def _secret_redact(text: str) -> str:"""Always-on secret redaction. force=True so user config can't disable it."""@@ -47,11 +41,9 @@ def _secret_redact(text: str) -> str:out = redact_sensitive_text(text, force=True)except Exception:# Fail CLOSED: if the redactor can't run, do not emit the raw string.- return "[redaction-unavailable]"- out = _BEARER_RE.sub("[redacted]", out)- out = _TOKEN_RE.sub("[redacted]", out)- out = _SECRET_LITERAL_RE.sub("[redacted]", out)- out = _BEARER_RESIDUE_RE.sub("[redacted]", out)+ return UNAVAILABLE+ for pattern in (_BEARER_RE, _TOKEN_RE, _SECRET_LITERAL_RE, _BEARER_RESIDUE_RE):+ out = pattern.sub("[redacted]", out)return out@@ -66,6 +58,22 @@ def redact_for_export(text: Optional[str]) -> Optional[str]:return out+def redact_bounded(+ raw: Any,+ *,+ limit: int = 500,+ empty: str = "[redacted]",+ unavailable: str = UNAVAILABLE,+) -> str:+ """Redact ``str(raw or "")`` and length-bound it; ``empty`` replaces an empty+ result, ``unavailable`` is returned if redaction itself raises."""+ try:+ return (redact_for_export(str(raw or "")) or empty)[:limit]+ except Exception:+ return unavailable++__all__ = ["redact_for_export",+ "redact_bounded",]diff --git a/tests/monitoring/test_cron_health_export.py b/tests/monitoring/test_cron_health_export.pyindex 67200f31300..abfa396b9bd 100644--- a/tests/monitoring/test_cron_health_export.py+++ b/tests/monitoring/test_cron_health_export.py@@ -1,6 +1,5 @@from __future__ import annotations-from datetime import datetime, timedelta, timezoneimport pytest@@ -92,7 +91,6 @@ def test_registered_observable_metric_names_cover_snapshot_metrics(monkeypatch):docs/observability/monitoring.md: an emitted-but-unregistered gauge issilently dropped. Regression guard for background_work / cron additions."""- import inspectfrom agent.monitoring import gateway_health_export# Build a representative snapshot (gateway + cron + background_work) without@@ -121,9 +119,7 @@ def test_registered_observable_metric_names_cover_snapshot_metrics(monkeypatch):snapshot_names = {m.name for m in gateway_health_export._read_runtime_snapshot({}).metrics}- # Extract the registered metric_names list literal from _start_metric_provider.- src = inspect.getsource(gateway_health_export._start_metric_provider)- registered = {n for n in snapshot_names if f'"{n}"' in src}+ registered = set(gateway_health_export._OBSERVABLE_METRIC_NAMES)missing = snapshot_names - registeredassert not missing, f"gauges emitted but NOT registered in metric_names (will be silently dropped): {sorted(missing)}"diff --git a/tests/monitoring/test_emitter.py b/tests/monitoring/test_emitter.pyindex 3fc621bd416..6c4883072c4 100644--- a/tests/monitoring/test_emitter.py+++ b/tests/monitoring/test_emitter.py@@ -3,10 +3,8 @@from __future__ import annotationsimport time-import threadingfrom agent.monitoring.emitter import MonitoringEmitter-from agent.monitoring.events import GatewayHealthEventdef test_emit_never_raises_when_disabled():diff --git a/tests/monitoring/test_gateway_health_export.py b/tests/monitoring/test_gateway_health_export.pyindex 24ff1f468ef..8c8190f7f1a 100644--- a/tests/monitoring/test_gateway_health_export.py+++ b/tests/monitoring/test_gateway_health_export.py@@ -1,8 +1,6 @@from __future__ import annotations-import logging-import pytest