The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(telemetry): shared metrics v3 with failure classes, tool usage, platform and daily snapshot
teknium1b8732b768e38
diff --git a/hermes_cli/observability/relay_shared_metrics.py b/hermes_cli/observability/relay_shared_metrics.pyindex 58a39e84477..257462cfc2e 100644--- a/hermes_cli/observability/relay_shared_metrics.py+++ b/hermes_cli/observability/relay_shared_metrics.py@@ -27,6 +27,8 @@ _RUNTIMES: dict[str, _Runtime | object] = {}_RUNTIME_LOCK = threading.RLock()_ABORTED = {"failed": True, "turn_exit_reason": "system_aborted"}+# The store latch allows one snapshot per 24h; re-reading it hourly keeps task starts cheap.+_SNAPSHOT_RECHECK_NS = 3_600 * 1_000_000_000def _text(event: dict[str, Any], key: str) -> str:@@ -103,12 +105,14 @@ class _ModelCall:handle: Anytask_id: strfields: dict[str, str]+ error_class: str = "none"@dataclassclass _ToolCall:handle: Anycategory: str+ tool_name: strstarted_ns: intapproval_outcome: str = "not_required"@@ -160,6 +164,7 @@ class _Runtime:# Guards the opt-in send pass: at most one in flight per process.self._send_lock = threading.RLock()self._send_thread: threading.Thread | None = None+ self._snapshot_checked_ns: int | None = Noneself._subscriber_name = f"{SUBSCRIBER_NAME}.{self.host.runtime_id}"self.subscriber = SharedMetricsSubscriber(SharedMetricsStore(), get_version_info().base_version, runtime_id=self.host.runtime_id@@ -196,6 +201,19 @@ class _Runtime:with session.lock:if not session.closing:self._mark(session, None, contract.CLIENT_ACTIVE_MARK, {})+ self._safe(self._emit_install_snapshot_if_due, session)++ def _emit_install_snapshot_if_due(self, session: _MetricsSession) -> None:+ now = monotonic_ns()+ if self._snapshot_checked_ns is not None and now - self._snapshot_checked_ns < _SNAPSHOT_RECHECK_NS:+ return+ self._snapshot_checked_ns = now+ if not self.subscriber.store.install_snapshot_due():+ return+ from .shared_metrics_snapshot import collect_install_snapshot++ fields = collect_install_snapshot(_raw_config())+ self._mark(session, None, contract.INSTALL_SNAPSHOT_MARK, fields)def _mark(self, session: _MetricsSession, task: _TaskRun | None, name: str, data: dict[str, str]@@ -324,7 +342,9 @@ class _Runtime:returnmodel_call.fields = contract.model_call_fields(event)if finish:- self._finish_model_call(session, model_call_key)+ self._finish_model_call(session, model_call_key, "success")+ else:+ model_call.error_class = contract.model_error_class(event)def start_tool_call(self, event: dict[str, Any]) -> None:"""Open one privacy-safe Relay tool lifecycle under its task."""@@ -667,14 +687,16 @@ class _Runtime:task, self.relay.tools.call, contract.TOOL_CALL_SCOPE, {},handle=task.handle, metadata=self._event_metadata(),)- return _ToolCall(handle, contract.tool_category(event), monotonic_ns())+ return _ToolCall(+ handle, contract.tool_category(event), contract.tool_metric_name(event), monotonic_ns()+ )def _finish_tool_call(self, task: _TaskRun, tool_call: _ToolCall, event: dict[str, Any]) -> None:fields = contract.tool_terminal_fields(event, category=tool_call.category, approval_outcome=tool_call.approval_outcome,- fallback_duration_ms=_elapsed_ms(tool_call.started_ns),+ fallback_duration_ms=_elapsed_ms(tool_call.started_ns), tool_name=tool_call.tool_name,)self._guarded("Hermes shared-metrics tool call close failed",@@ -693,22 +715,32 @@ class _Runtime:for key in [key for key in session.tool_calls if key[0] == task.task_id]:self._finish_tool_call(task, session.tool_calls.pop(key), {**event, "status": status})- def _finish_model_call(self, session: _MetricsSession, model_call_key: tuple[str, str]) -> None:+ def _finish_model_call(+ self, session: _MetricsSession, model_call_key: tuple[str, str], outcome: str+ ) -> None:model_call = session.model_calls.pop(model_call_key, None)if model_call is None:return+ error_class = model_call.error_class+ if outcome == "failed" and error_class == "none":+ error_class = "unknown"+ fields = contract.model_route_fields(+ model_call.fields, call_role="primary", outcome=outcome, error_class=error_class+ )self._guarded("Hermes shared-metrics model call close failed",self._run_scoped, session, session.tasks.get(model_call.task_id),- self.relay.llm.call_end, model_call.handle, model_call.fields,+ self.relay.llm.call_end, model_call.handle, fields,metadata=self._event_metadata(),)def _end_pending_model_calls(self, session: _MetricsSession, event: dict[str, Any]) -> None:+ """Close calls that never saw a successful response as failed or cancelled."""task_id = _text(event, "task_id")+ cancelled = contract.task_terminal_state(event)[0] == "cancelled"pending = [k for k, c in session.model_calls.items() if not task_id or c.task_id == task_id]for key in pending:- self._finish_model_call(session, key)+ self._finish_model_call(session, key, "cancelled" if cancelled else "failed")@staticmethoddef _existing_model_call_key(@@ -1001,7 +1033,7 @@ def _terminal_flags(result: dict[str, Any] | None, error: BaseException | None)reason = "timed_out" if isinstance(error, TimeoutError) else "system_aborted"return {"completed": False, "failed": not interrupted, "interrupted": interrupted,- "turn_exit_reason": reason,+ "turn_exit_reason": reason, "failure_class": "exception",}terminal = result if isinstance(result, dict) else {}failed = terminal.get("failed") is True@@ -1011,6 +1043,8 @@ def _terminal_flags(result: dict[str, Any] | None, error: BaseException | None)"failed": failed,"interrupted": terminal.get("interrupted") is True,"turn_exit_reason": reason or ("failed" if failed else "unknown"),+ # Classified in the contract against a closed set; the raw string never leaves.+ "failure_reason": str(terminal.get("failure_reason") or ""),}diff --git a/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.json b/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.jsonnew file mode 100644index 00000000000..bf88950d0e6--- /dev/null+++ b/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.json@@ -0,0 +1,912 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "urn:hermes-agent:schema:shared-metrics:v3",+ "title": "Hermes Shared Metrics Package v3",+ "type": "object",+ "additionalProperties": false,+ "required": [+ "schema_version",+ "package_id",+ "install_id",+ "period_start",+ "period_end",+ "generated_at",+ "resource",+ "metrics"+ ],+ "properties": {+ "schema_version": {+ "const": "hermes.shared_metrics.v3"+ },+ "package_id": {+ "$ref": "#/$defs/uuid"+ },+ "install_id": {+ "description": "Random persistent identifier scoped to one HERMES_HOME.",+ "$ref": "#/$defs/uuid"+ },+ "period_start": {+ "type": "string",+ "format": "date-time"+ },+ "period_end": {+ "type": "string",+ "format": "date-time"+ },+ "generated_at": {+ "type": "string",+ "format": "date-time"+ },+ "resource": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "architecture",+ "hermes_version",+ "install_method",+ "os_family"+ ],+ "properties": {+ "architecture": {+ "type": "string",+ "enum": [+ "arm",+ "arm64",+ "unknown",+ "x86",+ "x86_64"+ ]+ },+ "hermes_version": {+ "type": "string",+ "minLength": 1,+ "maxLength": 64+ },+ "install_method": {+ "type": "string",+ "enum": [+ "apt",+ "docker",+ "git",+ "home-manager",+ "homebrew",+ "nixos",+ "pip",+ "unknown"+ ]+ },+ "os_family": {+ "type": "string",+ "enum": [+ "linux",+ "macos",+ "unknown",+ "windows"+ ]+ }+ }+ },+ "metrics": {+ "type": "array",+ "minItems": 1,+ "items": {+ "oneOf": [+ {+ "$ref": "#/$defs/client_active_counter"+ },+ {+ "$ref": "#/$defs/model_call_counter"+ },+ {+ "$ref": "#/$defs/model_route_counter"+ },+ {+ "$ref": "#/$defs/task_started_counter"+ },+ {+ "$ref": "#/$defs/task_finished_counter"+ },+ {+ "$ref": "#/$defs/tool_call_counter"+ },+ {+ "$ref": "#/$defs/tool_approval_counter"+ },+ {+ "$ref": "#/$defs/skill_lifecycle_counter"+ },+ {+ "$ref": "#/$defs/skill_load_counter"+ },+ {+ "$ref": "#/$defs/tool_usage_counter"+ },+ {+ "$ref": "#/$defs/install_snapshot_counter"+ }+ ]+ }+ }+ },+ "$defs": {+ "client_active_counter": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "type",+ "dimensions",+ "value"+ ],+ "properties": {+ "name": {+ "const": "hermes.client.active"+ },+ "type": {+ "const": "counter"+ },+ "dimensions": {+ "type": "object",+ "additionalProperties": false,+ "maxProperties": 0+ },+ "value": {+ "const": 1+ }+ }+ },+ "uuid": {+ "type": "string",+ "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"+ },+ "model_call_counter": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "type",+ "dimensions",+ "value"+ ],+ "properties": {+ "name": {+ "const": "hermes.model_call.count"+ },+ "type": {+ "const": "counter"+ },+ "dimensions": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "call_role",+ "locality",+ "model_family",+ "outcome",+ "provider_family"+ ],+ "properties": {+ "call_role": {+ "const": "primary"+ },+ "locality": {+ "enum": [+ "local",+ "remote",+ "unknown"+ ]+ },+ "model_family": {+ "enum": [+ "claude",+ "deepseek",+ "gemini",+ "gemma",+ "glm",+ "gpt",+ "grok",+ "kimi",+ "llama",+ "minimax",+ "mimo",+ "mistral",+ "nemotron",+ "nova",+ "o1",+ "o3",+ "o4",+ "qwen",+ "step",+ "trinity",+ "unknown"+ ]+ },+ "outcome": {+ "enum": [+ "cancelled",+ "failed",+ "success"+ ]+ },+ "provider_family": {+ "enum": [+ "aggregator",+ "custom",+ "direct",+ "local",+ "unknown"+ ]+ }+ }+ },+ "value": {+ "type": "integer",+ "minimum": 1+ }+ }+ },+ "model_route_counter": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "type",+ "dimensions",+ "value"+ ],+ "properties": {+ "name": {+ "const": "hermes.model_route.count"+ },+ "type": {+ "const": "counter"+ },+ "dimensions": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "model",+ "provider"+ ],+ "properties": {+ "model": {+ "type": "string",+ "minLength": 1,+ "maxLength": 256,+ "pattern": "^[a-z0-9][a-z0-9._:/@+\\-]*$"+ },+ "provider": {+ "type": "string",+ "minLength": 1,+ "maxLength": 64,+ "pattern": "^[a-z0-9][a-z0-9._:/@+\\-]*$"+ },+ "call_role": {+ "enum": [+ "auxiliary",+ "primary"+ ]+ },+ "error_class": {+ "$ref": "#/$defs/vocabulary_identifier"+ },+ "outcome": {+ "enum": [+ "cancelled",+ "failed",+ "success"+ ]+ }+ },+ "dependentRequired": {+ "call_role": [+ "call_role",+ "error_class",+ "outcome"+ ],+ "error_class": [+ "call_role",+ "error_class",+ "outcome"+ ],+ "outcome": [+ "call_role",+ "error_class",+ "outcome"+ ]+ },+ "description": "v3 rows carry call_role/error_class/outcome; rows counted by an older build carry only model/provider."+ },+ "value": {+ "type": "integer",+ "minimum": 1+ }+ }+ },+ "task_started_counter": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "type",+ "dimensions",+ "value"+ ],+ "properties": {+ "name": {+ "const": "hermes.task_run.started"+ },+ "type": {+ "const": "counter"+ },+ "dimensions": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "entrypoint",+ "execution_surface"+ ],+ "properties": {+ "entrypoint": {+ "$ref": "#/$defs/task_entrypoint"+ },+ "execution_surface": {+ "$ref": "#/$defs/execution_surface"+ },+ "platform": {+ "$ref": "#/$defs/vocabulary_identifier"+ }+ }+ },+ "value": {+ "type": "integer",+ "minimum": 1+ }+ }+ },+ "task_finished_counter": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "type",+ "dimensions",+ "value"+ ],+ "properties": {+ "name": {+ "const": "hermes.task_run.finished"+ },+ "type": {+ "const": "counter"+ },+ "dimensions": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "duration_bucket",+ "end_reason",+ "entrypoint",+ "execution_surface",+ "model_call_count_bucket",+ "outcome",+ "retry_count_bucket",+ "termination",+ "tool_call_count_bucket"+ ],+ "properties": {+ "duration_bucket": {+ "$ref": "#/$defs/duration_bucket"+ },+ "end_reason": {+ "enum": [+ "approval_denied",+ "completed",+ "failed",+ "guardrail_blocked",+ "iteration_limit",+ "system_aborted",+ "timed_out",+ "unknown",+ "user_cancelled"+ ]+ },+ "entrypoint": {+ "$ref": "#/$defs/task_entrypoint"+ },+ "execution_surface": {+ "$ref": "#/$defs/execution_surface"+ },+ "model_call_count_bucket": {+ "$ref": "#/$defs/count_bucket"+ },+ "outcome": {+ "enum": [+ "cancelled",+ "failed",+ "success",+ "timed_out",+ "unknown"+ ]+ },+ "retry_count_bucket": {+ "$ref": "#/$defs/count_bucket"+ },+ "termination": {+ "enum": [+ "none",+ "system_aborted",+ "timed_out",+ "unknown",+ "user_cancelled"+ ]+ },+ "tool_call_count_bucket": {+ "$ref": "#/$defs/count_bucket"+ },+ "platform": {+ "$ref": "#/$defs/vocabulary_identifier"+ },+ "failure_class": {+ "$ref": "#/$defs/vocabulary_identifier"+ }+ },+ "dependentRequired": {+ "failure_class": [+ "platform"+ ],+ "platform": [+ "failure_class"+ ]+ }+ },+ "value": {+ "type": "integer",+ "minimum": 1+ }+ }+ },+ "execution_surface": {+ "enum": [+ "acp",+ "api",+ "batch",+ "cli",+ "desktop",+ "gateway",+ "other",+ "python",+ "scheduled_task",+ "tui",+ "unknown"+ ]+ },+ "task_entrypoint": {+ "enum": [+ "api",+ "background",+ "batch",+ "delegated",+ "gateway_message",+ "interactive",+ "other",+ "python",+ "scheduled_task",+ "unknown"+ ]+ },+ "duration_bucket": {+ "enum": [+ "1s_to_5s",+ "2m_to_10m",+ "30s_to_2m",+ "5s_to_30s",+ "gte_10m",+ "lt_1s"+ ]+ },+ "count_bucket": {+ "enum": [+ "0",+ "1",+ "2",+ "3_to_5",+ "6_to_10",+ "gte_11"+ ]+ },+ "tool_latency_bucket": {+ "enum": [+ "100ms_to_250ms",+ "10s_to_30s",+ "1s_to_2s",+ "250ms_to_500ms",+ "2s_to_5s",+ "500ms_to_1s",+ "5s_to_10s",+ "gte_30s",+ "lt_100ms",+ "unknown"+ ]+ },+ "tool_retry_bucket": {+ "enum": [+ "0",+ "1",+ "2",+ "3_to_5",+ "6_to_10",+ "gte_11",+ "unknown"+ ]+ },+ "tool_call_counter": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "type",+ "dimensions",+ "value"+ ],+ "properties": {+ "name": {+ "const": "hermes.tool_call.count"+ },+ "type": {+ "const": "counter"+ },+ "dimensions": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "approval_outcome",+ "latency_bucket",+ "outcome",+ "retry_count_bucket",+ "tool_category"+ ],+ "properties": {+ "approval_outcome": {+ "enum": [+ "approved",+ "cancelled",+ "denied",+ "not_required",+ "timed_out",+ "unknown"+ ]+ },+ "latency_bucket": {+ "$ref": "#/$defs/tool_latency_bucket"+ },+ "outcome": {+ "enum": [+ "blocked",+ "cancelled",+ "failed",+ "success",+ "timed_out",+ "unknown"+ ]+ },+ "retry_count_bucket": {+ "$ref": "#/$defs/tool_retry_bucket"+ },+ "tool_category": {+ "enum": [+ "browser",+ "code_execution",+ "communication",+ "computer_use",+ "delegation",+ "file",+ "home_automation",+ "mcp",+ "media",+ "memory",+ "other",+ "planning",+ "project",+ "scheduler",+ "skill",+ "terminal",+ "unknown",+ "web"+ ]+ }+ }+ },+ "value": {+ "type": "integer",+ "minimum": 1+ }+ }+ },+ "tool_approval_counter": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "type",+ "dimensions",+ "value"+ ],+ "properties": {+ "name": {+ "const": "hermes.tool_approval.count"+ },+ "type": {+ "const": "counter"+ },+ "dimensions": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "attribution",+ "outcome"+ ],+ "properties": {+ "attribution": {+ "enum": [+ "tool_call",+ "unattributed"+ ]+ },+ "outcome": {+ "enum": [+ "approved",+ "cancelled",+ "denied",+ "timed_out",+ "unknown"+ ]+ }+ }+ },+ "value": {+ "type": "integer",+ "minimum": 1+ }+ }+ },+ "skill_lifecycle_counter": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "type",+ "dimensions",+ "value"+ ],+ "properties": {+ "name": {+ "const": "hermes.skill.lifecycle.count"+ },+ "type": {+ "const": "counter"+ },+ "dimensions": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "action",+ "provenance"+ ],+ "properties": {+ "action": {+ "enum": [+ "archived",+ "created",+ "edited",+ "installed",+ "patched",+ "restored",+ "stale"+ ]+ },+ "provenance": {+ "$ref": "#/$defs/skill_provenance"+ }+ }+ },+ "value": {+ "type": "integer",+ "minimum": 1+ }+ }+ },+ "skill_load_counter": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "type",+ "dimensions",+ "value"+ ],+ "properties": {+ "name": {+ "const": "hermes.skill.load.count"+ },+ "type": {+ "const": "counter"+ },+ "dimensions": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "post_patch_state",+ "provenance",+ "reuse_state",+ "use_count_bucket"+ ],+ "properties": {+ "post_patch_state": {+ "enum": [+ "no_new_patch",+ "not_applicable",+ "reused_after_patch"+ ]+ },+ "provenance": {+ "$ref": "#/$defs/skill_provenance"+ },+ "reuse_state": {+ "enum": [+ "first_use",+ "reused"+ ]+ },+ "use_count_bucket": {+ "$ref": "#/$defs/count_bucket"+ }+ }+ },+ "value": {+ "type": "integer",+ "minimum": 1+ }+ }+ },+ "skill_provenance": {+ "enum": [+ "agent_created",+ "external",+ "installed",+ "local",+ "unknown"+ ]+ },+ "vocabulary_identifier": {+ "type": "string",+ "pattern": "^[a-z0-9][a-z0-9_]{0,63}$",+ "description": "Closed vocabulary owned by hermes_cli/observability/shared_metrics_contract.py (derived from in-repo registries); values outside it are never emitted."+ },+ "tool_usage_counter": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "type",+ "dimensions",+ "value"+ ],+ "properties": {+ "name": {+ "const": "hermes.tool.usage.count"+ },+ "type": {+ "const": "counter"+ },+ "dimensions": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "error_class",+ "outcome",+ "tool_name"+ ],+ "properties": {+ "error_class": {+ "enum": [+ "blocked",+ "contract_violation",+ "exception",+ "interrupted",+ "invalid_arguments",+ "none",+ "timeout",+ "tool_error",+ "unknown"+ ]+ },+ "outcome": {+ "enum": [+ "blocked",+ "cancelled",+ "failed",+ "success",+ "timed_out",+ "unknown"+ ]+ },+ "tool_name": {+ "$ref": "#/$defs/vocabulary_identifier"+ }+ }+ },+ "value": {+ "type": "integer",+ "minimum": 1+ }+ }+ },+ "size_bucket": {+ "enum": [+ "0",+ "1",+ "2",+ "3_to_5",+ "6_to_10",+ "11_to_25",+ "26_to_100",+ "101_to_250",+ "gte_251"+ ]+ },+ "install_snapshot_counter": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "type",+ "dimensions",+ "value"+ ],+ "properties": {+ "name": {+ "const": "hermes.install.snapshot"+ },+ "type": {+ "const": "counter"+ },+ "dimensions": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "cron_job_count_bucket",+ "mcp_server_count_bucket",+ "memory_provider",+ "plugin_count_bucket",+ "profile_count_bucket",+ "skill_count_bucket"+ ],+ "properties": {+ "cron_job_count_bucket": {+ "$ref": "#/$defs/size_bucket"+ },+ "mcp_server_count_bucket": {+ "$ref": "#/$defs/size_bucket"+ },+ "memory_provider": {+ "$ref": "#/$defs/vocabulary_identifier"+ },+ "plugin_count_bucket": {+ "$ref": "#/$defs/size_bucket"+ },+ "profile_count_bucket": {+ "$ref": "#/$defs/size_bucket"+ },+ "skill_count_bucket": {+ "$ref": "#/$defs/size_bucket"+ }+ }+ },+ "value": {+ "const": 1+ }+ }+ }+ }+}diff --git a/hermes_cli/observability/shared_metrics.py b/hermes_cli/observability/shared_metrics.pyindex cc8a51d851f..cce1c5c8b20 100644--- a/hermes_cli/observability/shared_metrics.py+++ b/hermes_cli/observability/shared_metrics.py@@ -19,18 +19,20 @@ from utils import atomic_json_writefrom .shared_metrics_contract import (CLIENT_ACTIVE_METRIC,COUNTER_METRICS,+ INSTALL_SNAPSHOT_METRIC,MODEL_ROUTE_METRIC,client_resource_is_valid,counter_dimensions_are_valid,)-_PACKAGE_SCHEMA_VERSION = "hermes.shared_metrics.v2"+_PACKAGE_SCHEMA_VERSION = "hermes.shared_metrics.v3"_STORE_SCHEMA_VERSION = "2"_BUSY_TIMEOUT_MS = 250_SCHEMA_BUSY_TIMEOUT_MS = 5_000_LOCAL_HISTORY_RETENTION_DAYS = 30_ACTIVE_INSTALL_STATE_KEY = "client_active_recorded_at"+_INSTALL_SNAPSHOT_STATE_KEY = "install_snapshot_recorded_at"_ACTIVE_INSTALL_INTERVAL = timedelta(hours=24)# Column order of the client resource in every counter_aggregates statement._RESOURCE_COLUMNS = ("hermes_version", "os_family", "architecture", "install_method")@@ -190,13 +192,36 @@ class SharedMetricsStore:def record_client_active(self, resource: dict[str, str]) -> bool:"""Record this install at most once in any rolling 24-hour window."""- dimensions: dict[str, str] = {}- self._validate_counter(CLIENT_ACTIVE_METRIC, dimensions, resource)+ return self._record_once_per_interval(+ _ACTIVE_INSTALL_STATE_KEY, CLIENT_ACTIVE_METRIC, {}, resource+ )++ def record_install_snapshot(self, dimensions: dict[str, str], resource: dict[str, str]) -> bool:+ """Record the configuration snapshot at most once in any rolling 24-hour window."""+ return self._record_once_per_interval(+ _INSTALL_SNAPSHOT_STATE_KEY, INSTALL_SNAPSHOT_METRIC, dimensions, resource+ )++ def install_snapshot_due(self) -> bool:+ """Cheap read so the producer skips collecting a snapshot the latch would drop."""+ with self._connection() as connection:+ row = connection.execute(+ "SELECT value FROM telemetry_state WHERE key = ?", (_INSTALL_SNAPSHOT_STATE_KEY,)+ ).fetchone()+ last = self._parse_state_timestamp(row["value"]) if row is not None else None+ now = _utc_now()+ return last is None or last > now or now >= last + _ACTIVE_INSTALL_INTERVAL++ def _record_once_per_interval(+ self, state_key: str, metric_name: str, dimensions: dict[str, str],+ resource: dict[str, str],+ ) -> bool:+ """Transactional compare-and-set latch shared by concurrent Hermes processes."""+ self._validate_counter(metric_name, dimensions, resource)now = _utc_now()with self._write() as connection:row = connection.execute(- "SELECT value FROM telemetry_state WHERE key = ?",- (_ACTIVE_INSTALL_STATE_KEY,),+ "SELECT value FROM telemetry_state WHERE key = ?", (state_key,)).fetchone()last_recorded = self._parse_state_timestamp(row["value"]) if row is not None else Noneif last_recorded is not None and last_recorded > now:@@ -204,19 +229,19 @@ class SharedMetricsStore:# timestamp plus another full interval.connection.execute("UPDATE telemetry_state SET value = ? WHERE key = ?",- (_isoformat(now), _ACTIVE_INSTALL_STATE_KEY),+ (_isoformat(now), state_key),)return Falseif last_recorded is not None and now < last_recorded + _ACTIVE_INSTALL_INTERVAL:return Falseself._install_id(connection)self._record_counter_in_transaction(- connection, CLIENT_ACTIVE_METRIC, dimensions, resource, now.date().isoformat()+ connection, metric_name, dimensions, resource, now.date().isoformat())connection.execute("INSERT INTO telemetry_state(key, value) VALUES (?, ?)"" ON CONFLICT(key) DO UPDATE SET value = excluded.value",- (_ACTIVE_INSTALL_STATE_KEY, _isoformat(now)),+ (state_key, _isoformat(now)),)return Truediff --git a/hermes_cli/observability/shared_metrics_contract.py b/hermes_cli/observability/shared_metrics_contract.pyindex b28b8bd7524..3e700f39c20 100644--- a/hermes_cli/observability/shared_metrics_contract.py+++ b/hermes_cli/observability/shared_metrics_contract.py@@ -5,15 +5,18 @@ from __future__ import annotationsfrom math import isfinitefrom typing import Any+from agent.error_classifier import FailoverReasonfrom agent.relay_runtime import (LOGICAL_LLM_SCOPE,RUNTIME_INSTANCE_KEY,RUNTIME_SCHEMA_KEY,RUNTIME_SCHEMA_VERSION,)+from hermes_cli.platforms import PLATFORMS+from toolsets import BUILTIN_TOOL_NAMESSCHEMA_KEY = "hermes.metrics.schema_version"-SCHEMA_VERSION = "hermes.metrics.event.v2"+SCHEMA_VERSION = "hermes.metrics.event.v3"MODEL_CALL_SCOPE = "hermes.model_call"MODEL_CALL_PROFILE_MODEL = "unknown"TASK_SCOPE = "hermes.task_run"@@ -22,6 +25,7 @@ CLIENT_ACTIVE_MARK = "hermes.client.active"TOOL_APPROVAL_MARK = "hermes.tool_approval"SKILL_LIFECYCLE_MARK = "hermes.skill.lifecycle"SKILL_LOAD_MARK = "hermes.skill.load"+INSTALL_SNAPSHOT_MARK = "hermes.install.snapshot"SUBSCRIBER_NAME = "hermes.nemo_relay.shared_metrics"CLIENT_ACTIVE_METRIC = "hermes.client.active"LEGACY_MODEL_CALL_METRIC = "hermes.model_call.count"@@ -32,6 +36,8 @@ TOOL_CALL_METRIC = "hermes.tool_call.count"TOOL_APPROVAL_METRIC = "hermes.tool_approval.count"SKILL_LIFECYCLE_METRIC = "hermes.skill.lifecycle.count"SKILL_LOAD_METRIC = "hermes.skill.load.count"+TOOL_USAGE_METRIC = "hermes.tool.usage.count"+INSTALL_SNAPSHOT_METRIC = "hermes.install.snapshot"MODEL_IDENTIFIER_MAX_LENGTH = 256PROVIDER_IDENTIFIER_MAX_LENGTH = 64_METRIC_IDENTIFIER_CHARACTERS = frozenset("abcdefghijklmnopqrstuvwxyz0123456789._:/@+-")@@ -81,6 +87,39 @@ CLIENT_INSTALL_METHODS = frozenset({})CLIENT_RESOURCE_KEYS = frozenset({"architecture", "hermes_version", "install_method", "os_family"})+# ---- v3 taxonomies -------------------------------------------------------------------------+MODEL_CALL_ROLES = frozenset({"auxiliary", "primary"})+MODEL_OUTCOMES = frozenset({"cancelled", "failed", "success"})+# The classifier's own closed enum, so the exported vocabulary is exactly what recovery acts on.+MODEL_ERROR_CLASSES = frozenset(reason.value for reason in FailoverReason) | {"none"}+TASK_FAILURE_CLASSES = MODEL_ERROR_CLASSES | frozenset({+ "context_compression", "empty_response", "exception", "local_error", "other", "persistence",+ "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"}+TOOL_NAMES = BUILTIN_TOOL_NAMES | {"mcp", "plugin", "unknown"}+TOOL_ERROR_CLASSES = frozenset({+ "blocked", "contract_violation", "exception", "interrupted", "invalid_arguments", "none",+ "timeout", "tool_error", "unknown",+})+SIZE_BUCKETS = frozenset({+ "0", "1", "2", "3_to_5", "6_to_10", "11_to_25", "26_to_100", "101_to_250", "gte_251",+})+++def _bundled_memory_providers() -> frozenset[str]:+ from pathlib import Path++ root = Path(__file__).resolve().parents[2] / "plugins" / "memory"+ try:+ return frozenset(p.name for p in root.iterdir() if (p / "__init__.py").is_file())+ except OSError:+ return frozenset()+++MEMORY_PROVIDERS = _bundled_memory_providers() | {"builtin", "plugin"}+_ARCHITECTURE_ALIASES = {"amd64": "x86_64", "x64": "x86_64", "x86_64": "x86_64","aarch64": "arm64", "arm64": "arm64",@@ -160,11 +199,16 @@ _COUNTER_DIMENSION_VALUES: dict[str, dict[str, frozenset[str]]] = {"model_family": _LEGACY_MODEL_FAMILIES, "outcome": _LEGACY_MODEL_OUTCOMES,"provider_family": _LEGACY_PROVIDER_FAMILIES,},- TASK_STARTED_METRIC: {"entrypoint": TASK_ENTRYPOINTS, "execution_surface": EXECUTION_SURFACES},+ TASK_STARTED_METRIC: {+ "entrypoint": TASK_ENTRYPOINTS, "execution_surface": EXECUTION_SURFACES,+ "platform": GATEWAY_PLATFORMS,+ },TASK_FINISHED_METRIC: {"duration_bucket": DURATION_BUCKETS, "end_reason": TASK_END_REASONS,"entrypoint": TASK_ENTRYPOINTS, "execution_surface": EXECUTION_SURFACES,+ "failure_class": TASK_FAILURE_CLASSES,"model_call_count_bucket": COUNT_BUCKETS, "outcome": TASK_OUTCOMES,+ "platform": GATEWAY_PLATFORMS,"retry_count_bucket": COUNT_BUCKETS, "termination": TASK_TERMINATIONS,"tool_call_count_bucket": COUNT_BUCKETS,},@@ -173,6 +217,9 @@ _COUNTER_DIMENSION_VALUES: dict[str, dict[str, frozenset[str]]] = {"outcome": TOOL_OUTCOMES, "retry_count_bucket": TOOL_RETRY_BUCKETS,"tool_category": TOOL_CATEGORIES,},+ TOOL_USAGE_METRIC: {+ "error_class": TOOL_ERROR_CLASSES, "outcome": TOOL_OUTCOMES, "tool_name": TOOL_NAMES,+ },TOOL_APPROVAL_METRIC: {"attribution": TOOL_APPROVAL_ATTRIBUTIONS,"outcome": TOOL_APPROVAL_OUTCOMES - {"not_required"},@@ -182,14 +229,28 @@ _COUNTER_DIMENSION_VALUES: dict[str, dict[str, frozenset[str]]] = {"post_patch_state": SKILL_POST_PATCH_STATES, "provenance": SKILL_PROVENANCES,"reuse_state": SKILL_REUSE_STATES, "use_count_bucket": COUNT_BUCKETS,},+ INSTALL_SNAPSHOT_METRIC: {+ "cron_job_count_bucket": SIZE_BUCKETS, "mcp_server_count_bucket": SIZE_BUCKETS,+ "memory_provider": MEMORY_PROVIDERS, "plugin_count_bucket": SIZE_BUCKETS,+ "profile_count_bucket": SIZE_BUCKETS, "skill_count_bucket": SIZE_BUCKETS,+ },}_MODEL_ROUTE_MAX_LENGTHS = {"model": MODEL_IDENTIFIER_MAX_LENGTH, "provider": PROVIDER_IDENTIFIER_MAX_LENGTH,}-# metric -> closed dimension field set (model-route fields are validated by shape, not allowlist)+_MODEL_ROUTE_OUTCOME_VALUES = {+ "call_role": MODEL_CALL_ROLES, "error_class": MODEL_ERROR_CLASSES, "outcome": MODEL_OUTCOMES,+}+# metric -> closed dimension field set (model-route identifiers are validated by shape)_METRIC_FIELDS: dict[str, frozenset[str]] = {**{name: frozenset(contract) for name, contract in _COUNTER_DIMENSION_VALUES.items()},+ MODEL_ROUTE_METRIC: frozenset(_MODEL_ROUTE_MAX_LENGTHS) | frozenset(_MODEL_ROUTE_OUTCOME_VALUES),+}+# Older field sets still accepted at packaging so counters recorded before an upgrade drain.+_LEGACY_METRIC_FIELDS: dict[str, frozenset[str]] = {MODEL_ROUTE_METRIC: frozenset(_MODEL_ROUTE_MAX_LENGTHS),+ TASK_STARTED_METRIC: _METRIC_FIELDS[TASK_STARTED_METRIC] - {"platform"},+ TASK_FINISHED_METRIC: _METRIC_FIELDS[TASK_FINISHED_METRIC] - {"failure_class", "platform"},}COUNTER_METRICS = frozenset(_METRIC_FIELDS) - {LEGACY_MODEL_CALL_METRIC}_SKILL_MARK_METRICS = {@@ -198,18 +259,22 @@ _SKILL_MARK_METRICS = {def counter_dimensions_are_valid(metric_name: str, dimensions: dict[str, Any]) -> bool:- """Return whether dimensions match one closed shared-metric contract."""+ """Return whether dimensions match one closed shared-metric contract (current or legacy)."""+ fields = set(dimensions)+ if fields != _METRIC_FIELDS.get(metric_name) and fields != _LEGACY_METRIC_FIELDS.get(metric_name):+ return Falseif metric_name == MODEL_ROUTE_METRIC:- return set(dimensions) == _METRIC_FIELDS[metric_name] and all(+ return all(dimensions[field] == _metric_identifier(dimensions[field], max_length=max_length)for field, max_length in _MODEL_ROUTE_MAX_LENGTHS.items()+ ) and all(+ isinstance(dimensions[field], str) and dimensions[field] in _MODEL_ROUTE_OUTCOME_VALUES[field]+ for field in fields & set(_MODEL_ROUTE_OUTCOME_VALUES))- contract = _COUNTER_DIMENSION_VALUES.get(metric_name)- if contract is None or set(dimensions) != set(contract):- return False+ contract = _COUNTER_DIMENSION_VALUES[metric_name]return all(- isinstance(dimensions[field], str) and dimensions[field] in allowed_values- for field, allowed_values in contract.items()+ isinstance(dimensions[field], str) and dimensions[field] in contract[field]+ for field in fields)@@ -323,7 +388,11 @@ def _auxiliary_model_call_dimensions(event: Any) -> dict[str, str] | None:or data.get("outcome") not in _LEGACY_MODEL_OUTCOMES):return None- dimensions = model_call_fields(data)+ outcome = data["outcome"]+ dimensions = model_route_fields(+ data, call_role="auxiliary", outcome=outcome,+ error_class="none" if outcome == "success" else "unknown",+ )return dimensions if counter_dimensions_are_valid(MODEL_ROUTE_METRIC, dimensions) else None@@ -339,9 +408,37 @@ def task_counter(event: Any) -> tuple[str, dict[str, str]] | None:def tool_call_dimensions(event: Any) -> dict[str, str] | None:"""Return package dimensions for one allowlisted tool lifecycle end event."""- return _scoped_dimensions(- event, TOOL_CALL_METRIC, category="tool", name=TOOL_CALL_SCOPE, category_profile={}- )+ return _tool_end_projection(event, TOOL_CALL_METRIC)+++def tool_usage_dimensions(event: Any) -> dict[str, str] | None:+ """Return the per-tool usage dimensions carried by the same tool lifecycle end event."""+ return _tool_end_projection(event, TOOL_USAGE_METRIC)+++_TOOL_END_FIELDS = _METRIC_FIELDS[TOOL_CALL_METRIC] | _METRIC_FIELDS[TOOL_USAGE_METRIC]+++def _tool_end_projection(event: Any, metric_name: str) -> dict[str, str] | None:+ """Project the tool end event onto one counter; both projections must validate first."""+ if not _valid_shape(+ event, kind="scope", scope_category="end", category="tool", name=TOOL_CALL_SCOPE,+ category_profile={},+ ):+ return None+ data = getattr(event, "data", None)+ if not isinstance(data, dict) or set(data) != _TOOL_END_FIELDS:+ return None+ projections = {+ name: _bounded_dimensions(name, {f: data[f] for f in _METRIC_FIELDS[name]})+ for name in (TOOL_CALL_METRIC, TOOL_USAGE_METRIC)+ }+ return projections[metric_name] if all(projections.values()) else None+++def install_snapshot_counter(event: Any) -> tuple[str, dict[str, str]] | None:+ """Return the daily install-configuration snapshot from a safe mark."""+ return _mark_counter(event, {INSTALL_SNAPSHOT_MARK: INSTALL_SNAPSHOT_METRIC})def tool_approval_counter(event: Any) -> tuple[str, dict[str, str]] | None:@@ -416,7 +513,18 @@ def execution_surface(kwargs: dict[str, Any]) -> str:def task_start_fields(kwargs: dict[str, Any]) -> dict[str, str]:"""Build the bounded fields recorded on a task scope start event."""surface = execution_surface(kwargs)- return {"entrypoint": task_entrypoint(kwargs, surface), "execution_surface": surface}+ return {+ "entrypoint": task_entrypoint(kwargs, surface), "execution_surface": surface,+ "platform": gateway_platform(kwargs, surface),+ }+++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."""+ if (surface or execution_surface(kwargs)) != "gateway":+ return "none"+ value = _norm(kwargs.get("platform"))+ return value if value in GATEWAY_PLATFORMS else "plugin"_SURFACE_ENTRYPOINTS = {@@ -448,6 +556,7 @@ def task_terminal_fields(**task_start_fields(kwargs),"duration_bucket": duration_bucket(duration_ms),"end_reason": end_reason,+ "failure_class": task_failure_class(kwargs, outcome),"model_call_count_bucket": count_bucket(model_call_count),"outcome": outcome,"retry_count_bucket": count_bucket(retry_count),@@ -456,6 +565,37 @@ def task_terminal_fields(}+_LOCAL_FAILURE_CLASSES = {"interpreter_shutdown": "shutdown", "session_busy": "session_busy"}+# turn_exit_reason prefix -> class, for failures that never reached the provider classifier.+_EXIT_REASON_FAILURE_CLASSES = (+ ("empty_response", "empty_response"), ("all_retries_exhausted", "empty_response"),+ ("context_compression", "context_compression"), ("compaction_", "context_compression"),+ ("ollama_runtime_context", "context_compression"),+ ("local_processing_error", "local_error"), ("repeated_outer_errors", "repeated_errors"),+ ("error_near_max_iterations", "repeated_errors"), ("session_persistence", "persistence"),+ ("redirect_restart_limit", "restart_limit"), ("rebuilt_restart_limit", "restart_limit"),+)+++def task_failure_class(kwargs: dict[str, Any], outcome: str | None = None) -> str:+ """Why a failed task failed, as a closed class; ``none`` for any non-failed outcome."""+ if (outcome or task_terminal_state(kwargs)[0]) != "failed":+ return "none"+ declared = _norm(kwargs.get("failure_class"))+ if declared in TASK_FAILURE_CLASSES - {"none"}:+ return declared+ failure_reason = _norm(kwargs.get("failure_reason"))+ if failure_reason in MODEL_ERROR_CLASSES - {"none"}:+ return failure_reason+ if failure_reason in _LOCAL_FAILURE_CLASSES:+ return _LOCAL_FAILURE_CLASSES[failure_reason]+ reason = _norm(kwargs.get("turn_exit_reason"))+ return next(+ (label for prefix, label in _EXIT_REASON_FAILURE_CLASSES if reason.startswith(prefix)),+ "other",+ )++def task_terminal_state(kwargs: dict[str, Any]) -> tuple[str, str, str]:"""Map Hermes terminal state to bounded (outcome, end_reason, termination)."""reason = _norm(kwargs.get("turn_exit_reason"))@@ -559,20 +699,57 @@ def tool_approval_outcome(kwargs: dict[str, Any]) -> str:def tool_terminal_fields(kwargs: dict[str, Any], *, category: str | None = None, approval_outcome: str = "not_required",- fallback_duration_ms: int | None = None,+ fallback_duration_ms: int | None = None, tool_name: str | None = None,) -> dict[str, str]:- """Build one bounded tool-call terminal payload."""+ """Build one bounded tool-call terminal payload (feeds the category and per-tool counters)."""+ outcome = tool_outcome(kwargs)return {"approval_outcome": _allowlisted(approval_outcome, TOOL_APPROVAL_OUTCOMES),+ "error_class": tool_error_class(kwargs, outcome),"latency_bucket": tool_latency_bucket(kwargs.get("duration_ms"), fallback_duration_ms=fallback_duration_ms),- "outcome": tool_outcome(kwargs),+ "outcome": outcome,"retry_count_bucket": tool_retry_bucket(kwargs.get("retry_count")),"tool_category": category if category in TOOL_CATEGORIES else tool_category(kwargs),+ "tool_name": tool_name if tool_name is not None and tool_name in TOOL_NAMES+ else tool_metric_name(kwargs),}+def tool_metric_name(kwargs: dict[str, Any]) -> str:+ """A built-in tool's own name; MCP and plugin tools collapse to their source kind."""+ name = _norm(kwargs.get("tool_name"))+ if name in BUILTIN_TOOL_NAMES:+ return name+ if not name:+ return "unknown"+ return "mcp" if name.startswith("mcp_") or tool_category(kwargs) == "mcp" else "plugin"+++_TOOL_STATUS_ERROR_CLASSES = {+ "blocked": "blocked", "cancelled": "interrupted", "success": "none", "timed_out": "timeout",+}+_TOOL_ERROR_TYPES = {+ **dict.fromkeys(("keyboard_interrupt", "tool_interrupted", "user_interrupt"), "interrupted"),+ "invalid_tool_arguments": "invalid_arguments", "thread_missing_result": "exception",+ "tool_error": "tool_error", "tool_result_contract": "contract_violation",+ "tool_timeout": "timeout",+}+++def tool_error_class(kwargs: dict[str, Any], outcome: str | None = None) -> str:+ """Closed failure class from Hermes's own error_type; exception class names become+ ``exception`` so plugin-defined identifiers never leave the machine."""+ outcome = outcome or tool_outcome(kwargs)+ if outcome in _TOOL_STATUS_ERROR_CLASSES:+ return _TOOL_STATUS_ERROR_CLASSES[outcome]+ if outcome != "failed":+ return "unknown"+ error_type = _norm(kwargs.get("error_type"))+ return _TOOL_ERROR_TYPES.get(error_type, "exception" if error_type else "unknown")++def tool_latency_bucket(value: Any, *, fallback_duration_ms: int | None = None) -> str:"""Bucket a tool duration reported in milliseconds."""duration_ms = _non_negative_number(value)@@ -609,6 +786,54 @@ def model_call_fields(kwargs: dict[str, Any]) -> dict[str, str]:return {"model": model, "provider": provider}+def model_route_fields(+ kwargs: dict[str, Any], *, call_role: str, outcome: str, error_class: str+) -> dict[str, str]:+ """The terminal route plus how the logical call ended. ``error_class`` is the last+ classified attempt error, so ``success`` + ``rate_limit`` reads as "recovered from a 429"."""+ return {+ **model_call_fields(kwargs),+ "call_role": _allowlisted(call_role, MODEL_CALL_ROLES),+ "error_class": error_class if error_class in MODEL_ERROR_CLASSES else "unknown",+ "outcome": outcome if outcome in MODEL_OUTCOMES else "failed",+ }+++def model_error_class(kwargs: dict[str, Any]) -> str:+ """The classifier's FailoverReason for one failed provider attempt."""+ reason = _norm(kwargs.get("reason"))+ return reason if reason in MODEL_ERROR_CLASSES - {"none"} else "unknown"+++# (exclusive upper bound, label) for install-scale counts (skills routinely exceed 100).+_SIZE_THRESHOLDS = (+ (1, "0"), (2, "1"), (3, "2"), (6, "3_to_5"), (11, "6_to_10"), (26, "11_to_25"),+ (101, "26_to_100"), (251, "101_to_250"),+)+++def size_bucket(count: int) -> str:+ """Bucket a non-negative install-scale count."""+ return _bucket(max(0, int(count)), _SIZE_THRESHOLDS, "gte_251")+++def install_snapshot_fields(+ *, memory_provider: Any, mcp_servers: int, plugins: int, skills: int, cron_jobs: int,+ profiles: int,+) -> dict[str, str]:+ """Bounded daily configuration snapshot: counts only, plus a bundled memory provider name."""+ provider = _norm(memory_provider)+ return {+ "cron_job_count_bucket": size_bucket(cron_jobs),+ "mcp_server_count_bucket": size_bucket(mcp_servers),+ "memory_provider": "builtin" if not provider+ else provider if provider in MEMORY_PROVIDERS else "plugin",+ "plugin_count_bucket": size_bucket(plugins),+ "profile_count_bucket": size_bucket(profiles),+ "skill_count_bucket": size_bucket(skills),+ }++def _metric_identifier(value: Any, *, max_length: int) -> str:"""Normalize one structurally safe identifier without a product catalog."""if not isinstance(value, str):diff --git a/hermes_cli/observability/shared_metrics_snapshot.py b/hermes_cli/observability/shared_metrics_snapshot.pynew file mode 100644index 00000000000..758c9a1645d--- /dev/null+++ b/hermes_cli/observability/shared_metrics_snapshot.py@@ -0,0 +1,71 @@+"""Collect the once-a-day install configuration snapshot for shared metrics.++Only counts and a bundled memory-provider name are read out; server names, plugin names, skill+names, job prompts and profile names stay local (the contract buckets every count).+"""++from __future__ import annotations++import json+from itertools import islice+from typing import Any++from hermes_constants import get_hermes_home++from . import shared_metrics_contract as contract++# The largest bucket starts at 251: counting past it only costs I/O.+_COUNT_CAP = 251+++def _sub(config: Any, key: str) -> Any:+ return config.get(key) if isinstance(config, dict) else None+++def _mcp_server_count(config: dict[str, Any]) -> int:+ servers = _sub(config, "mcp_servers")+ if not isinstance(servers, dict):+ return 0+ return sum(1 for spec in servers.values() if not (isinstance(spec, dict) and spec.get("enabled") is False))+++def _plugin_count(config: dict[str, Any]) -> int:+ enabled = _sub(_sub(config, "plugins"), "enabled")+ return len(enabled) if isinstance(enabled, list) else 0+++def _cron_job_count() -> int:+ try:+ # utf-8-sig: same dialect as cron/jobs.load_jobs (Windows editors may leave a BOM).+ with open(get_hermes_home() / "cron" / "jobs.json", encoding="utf-8-sig") as handle:+ jobs = json.load(handle).get("jobs", [])+ except (OSError, ValueError, AttributeError):+ return 0+ return sum(1 for job in jobs if isinstance(job, dict) and job.get("enabled", True))+++def _skill_count() -> int:+ from agent.skill_utils import iter_skill_index_files++ skills_dir = get_hermes_home() / "skills"+ if not skills_dir.is_dir():+ return 0+ return sum(1 for _ in islice(iter_skill_index_files(skills_dir, "SKILL.md"), _COUNT_CAP))+++def _profile_count() -> int:+ from hermes_cli.profiles import list_profile_names++ return len(list_profile_names())+++def collect_install_snapshot(config: dict[str, Any]) -> dict[str, str]:+ """Bounded snapshot fields for the active profile's ``config``."""+ return contract.install_snapshot_fields(+ memory_provider=_sub(_sub(config, "memory"), "provider"),+ mcp_servers=_mcp_server_count(config),+ plugins=_plugin_count(config),+ skills=_skill_count(),+ cron_jobs=_cron_job_count(),+ profiles=_profile_count(),+ )diff --git a/hermes_cli/observability/shared_metrics_subscriber.py b/hermes_cli/observability/shared_metrics_subscriber.pyindex 48e96733b98..626027bfdd1 100644--- a/hermes_cli/observability/shared_metrics_subscriber.py+++ b/hermes_cli/observability/shared_metrics_subscriber.py@@ -13,24 +13,31 @@ from hermes_cli.config import detect_install_methodfrom .shared_metrics import SharedMetricsStorefrom .shared_metrics_contract import (CLIENT_ACTIVE_METRIC,+ INSTALL_SNAPSHOT_METRIC,MODEL_ROUTE_METRIC,TOOL_CALL_METRIC,+ TOOL_USAGE_METRIC,client_active_counter,client_resource,+ install_snapshot_counter,model_call_dimensions,skill_counter,task_counter,tool_approval_counter,tool_call_dimensions,+ tool_usage_dimensions,)logger = logging.getLogger(__name__)-# Contract projections in match order; each yields (metric_name, dimensions) or None.+# Contract projections; each yields (metric_name, dimensions) or None. One tool end event feeds+# both the category counter and the per-tool counter, so every match is recorded._COUNTERS = (client_active_counter,+ install_snapshot_counter,lambda event: _named(MODEL_ROUTE_METRIC, model_call_dimensions(event)),lambda event: _named(TOOL_CALL_METRIC, tool_call_dimensions(event)),+ lambda event: _named(TOOL_USAGE_METRIC, tool_usage_dimensions(event)),task_counter,tool_approval_counter,skill_counter,@@ -68,9 +75,9 @@ class SharedMetricsSubscriber:self._active = False@staticmethod- def _classify(event: Any) -> tuple[str, dict] | None:- """Return ``(metric_name, dimensions)`` for the first matching contract, else None."""- return next((m for m in (project(event) for project in _COUNTERS) if m is not None), None)+ def _classify(event: Any) -> list[tuple[str, dict]]:+ """Return every ``(metric_name, dimensions)`` the event satisfies."""+ return [m for m in (project(event) for project in _COUNTERS) if m is not None]def __call__(self, event: Any) -> None:if self._runtime_id is not None:@@ -80,19 +87,18 @@ class SharedMetricsSubscriber:or metadata.get(RUNTIME_INSTANCE_KEY) != self._runtime_id):return- metric = self._classify(event)- if metric is None:- return- metric_name, dimensions = metric- with self._lock:- if not self._active:- return- try:- if metric_name == CLIENT_ACTIVE_METRIC:- self.store.record_client_active(self._client_resource)- else:- self.store.record_counter(metric_name, dimensions, self._client_resource)- except Exception:- logger.warning(- "Unable to persist the Hermes shared metric: %s", metric_name, exc_info=True- )+ for metric_name, dimensions in self._classify(event):+ with self._lock:+ if not self._active:+ return+ try:+ if metric_name == CLIENT_ACTIVE_METRIC:+ self.store.record_client_active(self._client_resource)+ elif metric_name == INSTALL_SNAPSHOT_METRIC:+ self.store.record_install_snapshot(dimensions, self._client_resource)+ else:+ self.store.record_counter(metric_name, dimensions, self._client_resource)+ except Exception:+ logger.warning(+ "Unable to persist the Hermes shared metric: %s", metric_name, exc_info=True+ )diff --git a/hermes_cli/setup.py b/hermes_cli/setup.pyindex b61c17a6c22..331a4f8aa10 100644--- a/hermes_cli/setup.py+++ b/hermes_cli/setup.py@@ -523,7 +523,8 @@ _SEND_CONSENT_EXPLAINER = (def setup_telemetry(config: dict):"""Configure the local shared-metrics subscriber and optional sending."""print_header("Shared Metrics")- _info("Shared metrics contain only bounded counters and histograms.",+ _info("Shared metrics contain only bounded counters: activity, outcomes, error",+ "classes, model routes and built-in tool names. Never prompts, files or error text.","Collection is local. Sending them to Nous is a separate opt-in.")shared_metrics = _sub_dict(_sub_dict(config, "telemetry"), "shared_metrics")current = shared_metrics.get("enabled") is Truediff --git a/scripts/smoke_nemo_relay_shared_metrics.py b/scripts/smoke_nemo_relay_shared_metrics.pyindex 3ba4c55197a..cc0feed31ca 100644--- a/scripts/smoke_nemo_relay_shared_metrics.py+++ b/scripts/smoke_nemo_relay_shared_metrics.py@@ -266,6 +266,9 @@ def _write_config(home: Path, port: int) -> None:api_key: no-key-requiredsecurity:tirith_enabled: false+auxiliary:+ title_generation:+ enabled: falsetelemetry:shared_metrics:enabled: true@@ -299,11 +302,13 @@ def _validate_store(database_path: Path) -> list[dict[str, Any]]:by_name.setdefault(counter["name"], []).append(counter)if set(by_name) != {"hermes.client.active",+ "hermes.install.snapshot","hermes.model_route.count","hermes.skill.lifecycle.count","hermes.skill.load.count","hermes.task_run.finished","hermes.task_run.started",+ "hermes.tool.usage.count","hermes.tool_call.count",}:raise AssertionError(@@ -324,7 +329,10 @@ def _validate_store(database_path: Path) -> list[dict[str, Any]]:expected_model = {"name": "hermes.model_route.count","dimensions": {+ "call_role": "primary",+ "error_class": "none","model": MODEL_CANARY,+ "outcome": "success","provider": "custom",},"value": 2,@@ -339,6 +347,7 @@ def _validate_store(database_path: Path) -> list[dict[str, Any]]:"dimensions": {"entrypoint": "interactive","execution_surface": "cli",+ "platform": "none",},"value": 1,"packaged_value": 1,@@ -353,8 +362,10 @@ def _validate_store(database_path: Path) -> list[dict[str, Any]]:"end_reason": "completed","entrypoint": "interactive","execution_surface": "cli",+ "failure_class": "none","model_call_count_bucket": "2","outcome": "success",+ "platform": "none","retry_count_bucket": "0","termination": "none","tool_call_count_bucket": "1",@@ -365,6 +376,13 @@ def _validate_store(database_path: Path) -> list[dict[str, Any]]:or terminal["packaged_value"] != 1):raise AssertionError(f"Unexpected task terminal counter: {terminal}")+ if [c["dimensions"] for c in by_name["hermes.tool.usage.count"]] != [+ {"error_class": "none", "outcome": "success", "tool_name": "read_file"}+ ]:+ raise AssertionError(f"Unexpected tool usage: {by_name['hermes.tool.usage.count']}")+ [snapshot] = by_name["hermes.install.snapshot"]+ if snapshot["value"] != 1 or snapshot["dimensions"]["memory_provider"] != "builtin":+ raise AssertionError(f"Unexpected install snapshot: {snapshot}")[tool] = by_name["hermes.tool_call.count"]expected_tool_dimensions = {"approval_outcome": "not_required",@@ -468,11 +486,13 @@ def _validate_packages(metrics.setdefault(metric["name"], []).append(metric)if set(metrics) != {"hermes.client.active",+ "hermes.install.snapshot","hermes.model_route.count","hermes.skill.lifecycle.count","hermes.skill.load.count","hermes.task_run.finished","hermes.task_run.started",+ "hermes.tool.usage.count","hermes.tool_call.count",}:raise AssertionError(@@ -491,7 +511,10 @@ def _validate_packages()[model] = metrics["hermes.model_route.count"]if model["dimensions"] != {+ "call_role": "primary",+ "error_class": "none","model": MODEL_CANARY,+ "outcome": "success","provider": "custom",} or model["value"] != 2:raise AssertionError(@@ -503,8 +526,10 @@ def _validate_packages("end_reason": "completed","entrypoint": "interactive","execution_surface": "cli",+ "failure_class": "none","model_call_count_bucket": "2","outcome": "success",+ "platform": "none","retry_count_bucket": "0","termination": "none","tool_call_count_bucket": "1",@@ -723,7 +748,7 @@ def main() -> int:/ "hermes_cli"/ "observability"/ "schemas"- / "hermes.shared_metrics.v2.schema.json",+ / "hermes.shared_metrics.v3.schema.json",)print("Hermes -> NeMo Relay shared-metrics smoke test passed")diff --git a/tests/hermes_cli/test_relay_shared_metrics.py b/tests/hermes_cli/test_relay_shared_metrics.pyindex 16189a1e587..a87a721b8be 100644--- a/tests/hermes_cli/test_relay_shared_metrics.py+++ b/tests/hermes_cli/test_relay_shared_metrics.py@@ -62,6 +62,7 @@ from hermes_cli.observability.shared_metrics_contract import (tool_approval_counter,tool_approval_outcome,tool_call_dimensions,+ tool_usage_dimensions,tool_category,tool_latency_bucket,tool_outcome,@@ -74,7 +75,7 @@ SCHEMA_PATH = (/ "hermes_cli"/ "observability"/ "schemas"- / "hermes.shared_metrics.v2.schema.json"+ / "hermes.shared_metrics.v3.schema.json")LEGACY_SCHEMA_PATH = SCHEMA_PATH.with_name("hermes.shared_metrics.v1.schema.json")@@ -172,7 +173,7 @@ def test_model_call_counter_survives_restart_and_exports_only_new_deltas(tmp_pat_schema_validator().validate(first_package)uuid.UUID(first_package["package_id"])uuid.UUID(first_package["install_id"])- assert first_package["schema_version"] == "hermes.shared_metrics.v2"+ assert first_package["schema_version"] == "hermes.shared_metrics.v3"assert first_package["resource"] == _resource()assert first_package["metrics"] == [{@@ -250,7 +251,7 @@ def test_v2_package_preserves_pending_v1_model_counters(tmp_path):package = json.loads(package_path.read_text(encoding="utf-8"))_schema_validator().validate(package)- assert package["schema_version"] == "hermes.shared_metrics.v2"+ assert package["schema_version"] == "hermes.shared_metrics.v3"assert package["metrics"] == [{"name": LEGACY_MODEL_CALL_METRIC,@@ -496,8 +497,10 @@ def test_package_schema_matches_the_model_call_contract():schema = json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))properties = _package_dimension_schema()["properties"]- assert schema["properties"]["schema_version"]["const"] == "hermes.shared_metrics.v2"- assert set(properties) == {"model", "provider"}+ assert schema["properties"]["schema_version"]["const"] == "hermes.shared_metrics.v3"+ assert set(properties) == {"call_role", "error_class", "model", "outcome", "provider"}+ # Rows counted before the v3 upgrade carry only model/provider and must still drain.+ assert set(_package_dimension_schema()["required"]) == {"model", "provider"}assert properties["model"]["maxLength"] == MODEL_IDENTIFIER_MAX_LENGTHassert properties["provider"]["maxLength"] == PROVIDER_IDENTIFIER_MAX_LENGTHassert "enum" not in properties["model"]@@ -558,7 +561,7 @@ def test_client_active_mark_accepts_only_an_empty_allowlisted_payload():name="hermes.client.active",scope_category=None,metadata={- "hermes.metrics.schema_version": "hermes.metrics.event.v2",+ "hermes.metrics.schema_version": "hermes.metrics.event.v3",},data={},)@@ -759,7 +762,10 @@ def test_auxiliary_logical_scope_projects_one_normalized_terminal_route():)assert model_call_dimensions(event) == {+ "call_role": "auxiliary",+ "error_class": "none","model": "accepted/model",+ "outcome": "success","provider": "openrouter",}@@ -768,7 +774,10 @@ def test_auxiliary_logical_scope_projects_one_normalized_terminal_route():"response_model": "malformed response model",})assert model_call_dimensions(event) == {+ "call_role": "auxiliary",+ "error_class": "none","model": "configured/model",+ "outcome": "success","provider": "openrouter",}@@ -823,16 +832,31 @@ def test_tool_subscriber_contract_accepts_only_bounded_events():category_profile={},name="hermes.tool_call",scope_category="end",- metadata={"hermes.metrics.schema_version": "hermes.metrics.event.v2"},+ metadata={"hermes.metrics.schema_version": "hermes.metrics.event.v3"},data={"approval_outcome": "approved",+ "error_class": "none","latency_bucket": "250ms_to_500ms","outcome": "success","retry_count_bucket": "0","tool_category": "terminal",+ "tool_name": "terminal",},)- assert tool_call_dimensions(terminal) == terminal.data+ assert tool_call_dimensions(terminal) == {+ "approval_outcome": "approved",+ "latency_bucket": "250ms_to_500ms",+ "outcome": "success",+ "retry_count_bucket": "0",+ "tool_category": "terminal",+ }+ assert tool_usage_dimensions(terminal) == {+ "error_class": "none", "outcome": "success", "tool_name": "terminal",+ }+ terminal.data["tool_name"] = "private-plugin-tool"+ assert tool_usage_dimensions(terminal) is None+ assert tool_call_dimensions(terminal) is None+ terminal.data["tool_name"] = "terminal"terminal.data["result"] = "must-not-pass"assert tool_call_dimensions(terminal) is None@@ -849,7 +873,7 @@ def test_tool_subscriber_contract_accepts_only_bounded_events():category_profile=None,name="hermes.tool_approval",scope_category=None,- metadata={"hermes.metrics.schema_version": "hermes.metrics.event.v2"},+ metadata={"hermes.metrics.schema_version": "hermes.metrics.event.v3"},data={"attribution": "unattributed", "outcome": "denied"},)assert tool_approval_counter(approval) == (@@ -861,7 +885,7 @@ def test_tool_subscriber_contract_accepts_only_bounded_events():def test_skill_subscriber_contract_accepts_only_bounded_marks():- metadata = {"hermes.metrics.schema_version": "hermes.metrics.event.v2"}+ metadata = {"hermes.metrics.schema_version": "hermes.metrics.event.v3"}lifecycle = SimpleNamespace(kind="mark",category=None,diff --git a/tests/hermes_cli/test_relay_shared_metrics_runtime.py b/tests/hermes_cli/test_relay_shared_metrics_runtime.pyindex 1a79d8074c7..bf1e550acf0 100644--- a/tests/hermes_cli/test_relay_shared_metrics_runtime.py+++ b/tests/hermes_cli/test_relay_shared_metrics_runtime.py@@ -357,6 +357,7 @@ def test_direct_runtime_records_without_enabling_a_plugin(direct_runtime, tmp_paassert scope_starts[1][3]["input"] == {"entrypoint": "interactive","execution_surface": "cli",+ "platform": "none",}assert len(starts) == 1assert len(ends) == 1@@ -366,10 +367,12 @@ def test_direct_runtime_records_without_enabling_a_plugin(direct_runtime, tmp_paassert tool_starts[0][2] == {}assert tool_ends[0][2] == {"approval_outcome": "approved",+ "error_class": "none","latency_bucket": "250ms_to_500ms","outcome": "success","retry_count_bucket": "0","tool_category": "terminal",+ "tool_name": "terminal",}assert starts[0][2] == {}assert starts[0][3]["model_name"] == "unknown"@@ -381,7 +384,11 @@ def test_direct_runtime_records_without_enabling_a_plugin(direct_runtime, tmp_paassert len(active_marks) == 2assert all(mark[2]["data"] == {} for mark in active_marks)assert ends[0][2] == {+ "call_role": "primary",+ # The call recovered from an unclassified provider error before succeeding.+ "error_class": "unknown","model": "claude-sonnet",+ "outcome": "success","provider": "anthropic",}serialized_events = json.dumps(direct_runtime.events)@@ -402,12 +409,18 @@ def test_direct_runtime_records_without_enabling_a_plugin(direct_runtime, tmp_pametrics = {metric["name"]: metric for metric in package["metrics"]}assert set(metrics) == {"hermes.client.active",+ "hermes.install.snapshot","hermes.model_route.count","hermes.task_run.finished","hermes.task_run.started",+ "hermes.tool.usage.count","hermes.tool_approval.count","hermes.tool_call.count",}+ assert metrics["hermes.tool.usage.count"]["dimensions"] == {+ "error_class": "none", "outcome": "success", "tool_name": "terminal",+ }+ assert metrics["hermes.install.snapshot"]["value"] == 1assert metrics["hermes.client.active"] == {"name": "hermes.client.active","type": "counter",@@ -415,7 +428,11 @@ def test_direct_runtime_records_without_enabling_a_plugin(direct_runtime, tmp_pa"value": 1,}assert metrics["hermes.model_route.count"]["dimensions"] == {+ "call_role": "primary",+ # The call recovered from an unclassified provider error before succeeding.+ "error_class": "unknown","model": "claude-sonnet",+ "outcome": "success","provider": "anthropic",}assert metrics["hermes.model_route.count"]["value"] == 1@@ -446,6 +463,7 @@ def test_direct_runtime_records_without_enabling_a_plugin(direct_runtime, tmp_pa"dimensions": {"entrypoint": "interactive","execution_surface": "cli",+ "platform": "none",},"value": 1,}@@ -464,8 +482,10 @@ def test_direct_runtime_records_without_enabling_a_plugin(direct_runtime, tmp_pa"end_reason": "completed","entrypoint": "interactive","execution_surface": "cli",+ "failure_class": "none","model_call_count_bucket": "1","outcome": "success",+ "platform": "none","retry_count_bucket": "1","termination": "none","tool_call_count_bucket": "1",@@ -637,13 +657,32 @@ def test_real_binding_drives_lifecycle_aggregation_export_and_snapshot(assert by_metric["hermes.client.active"][0]["value"] == 1assert len(by_metric["hermes.task_run.started"]) == 1assert by_metric["hermes.task_run.started"][0]["value"] == 3- assert len(by_metric["hermes.model_route.count"]) == 1- model_counter = by_metric["hermes.model_route.count"][0]- assert model_counter["dimensions"] == {- "model": model_canary,- "provider": "custom",+ # v3: one route row per terminal outcome; an unclassified failed call reports `unknown`.+ route_by_outcome = {+ counter["dimensions"]["outcome"]: counter+ for counter in by_metric["hermes.model_route.count"]+ }+ assert set(route_by_outcome) == {"success", "failed", "cancelled"}+ for outcome, error_class in (+ # The success call recovered from an unclassified error; the failed one never did.+ ("success", "unknown"), ("failed", "unknown"), ("cancelled", "none")+ ):+ assert route_by_outcome[outcome]["dimensions"] == {+ "call_role": "primary",+ "error_class": error_class,+ "model": model_canary,+ "outcome": outcome,+ "provider": "custom",+ }+ assert route_by_outcome[outcome]["value"] == 1+ assert {+ (c["dimensions"]["tool_name"], c["dimensions"]["outcome"], c["dimensions"]["error_class"])+ for c in by_metric["hermes.tool.usage.count"]+ } == {+ ("terminal", "success", "none"),+ ("read_file", "failed", "unknown"),+ ("browser_navigate", "cancelled", "interrupted"),}- assert model_counter["value"] == 3assert {counter["dimensions"]["outcome"]for counter in by_metric["hermes.tool_call.count"]@@ -691,6 +730,8 @@ def test_real_binding_drives_lifecycle_aggregation_export_and_snapshot(assert terminal_by_outcome["failed"]["dimensions"]["end_reason"] == ("system_aborted")+ assert terminal_by_outcome["failed"]["dimensions"]["failure_class"] == "other"+ assert terminal_by_outcome["success"]["dimensions"]["failure_class"] == "none"assert terminal_by_outcome["cancelled"]["dimensions"]["termination"] == ("user_cancelled")@@ -710,7 +751,7 @@ def test_real_binding_drives_lifecycle_aggregation_export_and_snapshot(json.loads(package.read_text(encoding="utf-8")) for package in packages]for package in package_payloads:- assert package["schema_version"] == "hermes.shared_metrics.v2"+ assert package["schema_version"] == "hermes.shared_metrics.v3"for metric in package["metrics"]:key = (metric["name"], tuple(sorted(metric["dimensions"].items())))package_values[key] = package_values.get(key, 0) + metric["value"]@@ -1249,6 +1290,7 @@ def test_disabling_shared_metrics_stops_collection_and_shutdown_export(store = SharedMetricsStore(root / "metrics.sqlite3", root / "outbox")assert [row["metric_name"] for row in store.counter_snapshot()] == ["hermes.client.active",+ "hermes.install.snapshot","hermes.task_run.started"]assert list((root / "outbox").glob("*.json")) == []@@ -1647,6 +1689,7 @@ def test_terminal_model_error_retains_the_failed_route(direct_runtime):"api_request_error",**base,retryable=False,+ reason="auth",error={"message": "sensitive-error"},)assert not [event for event in direct_runtime.events if event[0] == "llm.call_end"]@@ -1662,7 +1705,10 @@ def test_terminal_model_error_retains_the_failed_route(direct_runtime):[end] = [event for event in direct_runtime.events if event[0] == "llm.call_end"]assert end[2] == {+ "call_role": "primary",+ "error_class": "auth","model": "claude-sonnet",+ "outcome": "failed","provider": "anthropic",}@@ -1684,6 +1730,7 @@ def test_nonretryable_provider_error_can_recover_within_one_logical_call(**base,retry_count=0,retryable=False,+ reason="model_not_found",)fallback = {**base,@@ -1701,8 +1748,12 @@ def test_nonretryable_provider_error_can_recover_within_one_logical_call([end] = [event for event in direct_runtime.events if event[0] == "llm.call_end"][start] = [event for event in direct_runtime.events if event[0] == "llm.call"]assert start[3]["model_name"] == "unknown"+ # The recovered call keeps the error it recovered from.assert end[2] == {+ "call_role": "primary",+ "error_class": "model_not_found","model": "gpt-5",+ "outcome": "success","provider": "openai-api",}@@ -2098,10 +2149,12 @@ def test_pending_tool_is_closed_and_counted_when_task_is_interrupted(direct_runt]assert tool_end[2] == {"approval_outcome": "not_required",+ "error_class": "interrupted","latency_bucket": tool_end[2]["latency_bucket"],"outcome": "cancelled","retry_count_bucket": "unknown","tool_category": "terminal",+ "tool_name": "terminal",}[task_end] = [event@@ -2350,8 +2403,9 @@ def test_task_retry_count_survives_provider_fallback_ordinal_reset(direct_runtim[model_end] = [event for event in direct_runtime.events if event[0] == "llm.call_end"]- assert model_end[2] == {+ assert {k: model_end[2][k] for k in ("model", "outcome", "provider")} == {"model": "gpt-5",+ "outcome": "success","provider": "openai",}[task_end] = [@@ -2621,3 +2675,80 @@ def test_real_binding_concurrent_task_close_skips_pop_under_sibling_scope()lifecycle.invoke_hook("on_session_end", **event)assert "task close failed" not in caplog.text+++def _stored_counters(tmp_path) -> dict[str, list[dict[str, Any]]]:+ from hermes_cli.observability.shared_metrics import SharedMetricsStore++ root = tmp_path / "hermes-home" / "telemetry" / "shared_metrics"+ by_metric: dict[str, list[dict[str, Any]]] = {}+ for counter in SharedMetricsStore(root / "metrics.sqlite3", root / "outbox").counter_snapshot():+ by_metric.setdefault(counter["metric_name"], []).append(counter["dimensions"])+ return by_metric+++def test_v3_failure_dimensions_never_export_third_party_identifiers(direct_runtime, tmp_path):+ """Plugin tool names, exception class names, plugin platforms and raw exit reasons collapse+ to closed classes, while Hermes's own vocabularies pass through."""+ base = {+ "session_id": "s1", "task_id": "t1", "api_request_id": "r1", "platform": "telegram",+ "provider": "anthropic", "model": "claude-sonnet",+ }+ lifecycle.invoke_hook("pre_llm_call", **base)+ lifecycle.invoke_hook("pre_api_request", **base)+ lifecycle.invoke_hook("api_request_error", **base, retryable=True, reason="rate_limit")+ for call_id, tool, error_type in (+ ("c1", "acme_private_tool", "AcmePrivateError"), ("c2", "terminal", "tool_timeout"),+ ):+ lifecycle.invoke_hook("pre_tool_call", **base, tool_call_id=call_id, tool_name=tool)+ lifecycle.invoke_hook(+ "post_tool_call", **base, tool_call_id=call_id, tool_name=tool, status="error",+ error_type=error_type, duration_ms=10,+ )+ relay_shared_metrics.finish_task_run(+ session_id="s1", task_id="t1", platform="telegram",+ result={"failed": True, "failure_reason": "rate_limit",+ "turn_exit_reason": "acme private exit reason"},+ )+ lifecycle.finalize_session(session_id="s1")++ counters = _stored_counters(tmp_path)+ assert "acme" not in json.dumps(counters).lower()+ assert {(d["tool_name"], d["error_class"]) for d in counters["hermes.tool.usage.count"]} == {+ ("plugin", "exception"), ("terminal", "timeout"),+ }+ [route] = counters["hermes.model_route.count"]+ assert (route["outcome"], route["error_class"]) == ("failed", "rate_limit")+ [finished] = counters["hermes.task_run.finished"]+ assert (finished["platform"], finished["failure_class"]) == ("telegram", "rate_limit")+++def test_install_snapshot_is_daily_and_carries_only_bucketed_counts(+ direct_runtime, tmp_path, monkeypatch,+):+ monkeypatch.setattr(+ "hermes_cli.config.read_raw_config_readonly",+ lambda: {+ "telemetry": {"shared_metrics": {"enabled": True}},+ "memory": {"provider": "acme-private-memory"},+ "mcp_servers": {"acme-private-server": {"command": "x"}, "off": {"enabled": False}},+ "plugins": {"enabled": ["acme-private-plugin", "b", "c"]},+ },+ )+ for task_id in ("t1", "t2"):+ event = {"session_id": task_id, "task_id": task_id, "platform": "cli"}+ lifecycle.invoke_hook("pre_llm_call", **event)+ relay_shared_metrics.finish_task_run(**event, result={"completed": True})+ lifecycle.finalize_session(session_id=task_id)+ # A new runtime has no in-process throttle; only the store's 24h latch can hold it back.+ relay_shared_metrics._reset_for_tests()+ event = {"session_id": "t3", "task_id": "t3", "platform": "cli"}+ lifecycle.invoke_hook("pre_llm_call", **event)+ lifecycle.finalize_session(session_id="t3")++ [snapshot] = _stored_counters(tmp_path)["hermes.install.snapshot"]+ assert snapshot == {+ "cron_job_count_bucket": "0", "mcp_server_count_bucket": "1",+ "memory_provider": "plugin", "plugin_count_bucket": "3_to_5",+ "profile_count_bucket": snapshot["profile_count_bucket"], "skill_count_bucket": "0",+ }diff --git a/toolsets.py b/toolsets.pyindex 5d3ef5b7494..a1cf5d52a37 100644--- a/toolsets.py+++ b/toolsets.py@@ -255,6 +255,10 @@ TOOLSETS = {),}+# Captured before create_custom_toolset() can add user-named tools: shared metrics may export only+# these names, so a plugin, MCP server or custom toolset name never leaves the machine.+BUILTIN_TOOL_NAMES = frozenset(tool for spec in TOOLSETS.values() for tool in spec["tools"])+def _registry():"""Live tool registry, or None when tools.registry can't be imported."""diff --git a/website/docs/developer-guide/relay-shared-metrics.md b/website/docs/developer-guide/relay-shared-metrics.mdindex c2577cc0e82..75e9baeb345 100644--- a/website/docs/developer-guide/relay-shared-metrics.md+++ b/website/docs/developer-guide/relay-shared-metrics.md@@ -172,9 +172,14 @@ provider route that Hermes used for the logical call, such as`nvidia/nemotron-3-ultra` through `openrouter`. These identifiers arelowercased and structurally bounded, but they are not normalized through achecked-in model catalog. Pricing and model-family classification belong to-the metrics backend. Prompts, responses, endpoints, errors, session IDs, task-IDs, and request IDs are not included in the metrics event or package.-New calls use `hermes.model_route.count`. The previous+the metrics backend. Prompts, responses, endpoints, error text, session IDs,+task IDs, and request IDs are not included in the metrics event or package.+New calls use `hermes.model_route.count`. Since package schema v3 each route row+also carries `call_role` (`primary` or `auxiliary`), `outcome` (`success`,+`failed`, `cancelled`) and `error_class`: the error classifier's own+`FailoverReason` value (`rate_limit`, `auth`, `context_overflow`, ...) for the+last failed attempt of that logical call, or `none`. A `success` row with a+non-`none` class is a call that recovered after that error. The previous`hermes.model_call.count` contract remains readable only so pending localcounters created by older builds can be exported without losing data.@@ -189,9 +194,15 @@ 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 execution-surface and entrypoint values. The terminal counter contains bounded outcome,-end reason, termination status, duration, logical model-call count, terminal-tool-call count, and provider-retry count buckets. Retries are additional+surface 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+outcome, 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+died on a classified API error, otherwise a local class (`empty_response`,+`context_compression`, `repeated_errors`, `exception`, `other`, ...). Raw exit+reasons never leave the machine. Retries are additionalprovider attempts for the same Hermes API request ID; they do not inflate thelogical model-call count. Tool calls are deduplicated by their Hermes tool-callID after a terminal tool result is observed. The outer `AIAgent` execution@@ -204,13 +215,21 @@ Each tool invocation is represented by a Relay tool lifecycle namedoutcome, approval outcome, latency, and explicit retry-count buckets. Hermesderives the category from the toolset already declared in its runtime registry;custom and unrecognized toolsets collapse to `other` rather than exporting-tool or plugin names. Hermes does not infer retries from repeated tool names or+tool or plugin names. The same terminal event also feeds+`hermes.tool.usage.count` with `tool_name`, `outcome` and `error_class`.+`tool_name` is exported only for tools declared in the repository's static+`toolsets.TOOLSETS` (`toolsets.BUILTIN_TOOL_NAMES`, captured before any runtime+custom toolset is created); MCP tools report `mcp` and every plugin or custom+tool reports `plugin`. `error_class` maps Hermes's own `error_type` values+(`tool_error`, `timeout`, `interrupted`, `invalid_arguments`, `blocked`,+`contract_violation`); any other value, such as an exception class name,+collapses to `exception`. Hermes does not infer retries from repeated tool names oradjacent calls; when thehook does not provide an explicit retry relationship, the retry bucket is`unknown`. Approval decisions are emitted as `hermes.tool_approval` marks and-recorded as attributed to a tool call or explicitly `unattributed`. Tool names,-call IDs, arguments, results, commands, descriptions, and error text are not-included in shared-metrics events or packages. A started tool that is still+recorded as attributed to a tool call or explicitly `unattributed`. Non-built-in+tool names, call IDs, arguments, results, commands, descriptions, and error+text are not included in shared-metrics events or packages. A started tool that is stillopen when its task terminates is closed as failed, timed out, or cancelled andremains in the task's tool-count bucket.@@ -225,6 +244,15 @@ SQLite dimensions, or packages. A use after a new patch is counted once asTask-outcome attribution after a patch remains deferred until its window andmulti-skill semantics are defined.+Once per rolling 24 hours, the first activation also emits a+`hermes.install.snapshot` mark describing how the profile is configured: the+memory provider (a bundled provider name, `builtin`, or `plugin`) and bucketed+counts of MCP servers, enabled plugins, installed skills, enabled cron jobs and+profiles. Server, plugin, skill, job and profile names are never read into the+event. The same compare-and-set latch as `hermes.client.active` keeps it to one+row per install per day, and the producer checks the latch before walking the+skills tree.+Local state is written under:```text@@ -241,9 +269,12 @@ platform strings, hostnames, and paths are never included. Fully packagedaggregate rows and successfully exported package rows and files are retainedlocally for 30 days. Pending package rows and counters with unexported deltasare never pruned.-Package schema v1 remains unchanged for existing outbox files. New packages-use v2, which accepts both the retired model-call contract and the current-model-route contract so upgrades can drain pending counters safely.+Package schemas v1 and v2 remain unchanged for existing outbox files. New+packages use v3, which also accepts the v2 field sets of `hermes.model_route.count`+and the task counters so counters recorded before an upgrade drain safely.+Vocabularies derived from in-repo registries (tool names, platforms, memory+providers, error classes) are bounded by pattern in the JSON schema; the+authoritative allowlist is `shared_metrics_contract.py`.Each package contains an `install_id` generated as a random UUID. Despite theschema field name, its current scope is one `HERMES_HOME`, so it is more