Skip to content

The agent that grows with you

Merge updated client resource metrics into active-install metrics

Alex Fournier07ac9ca6872c
diff --cc docs/observability/relay-shared-metrics.md
index 33c1de6498a,182608dc225..ad5711c06e2
--- a/docs/observability/relay-shared-metrics.md
+++ b/docs/observability/relay-shared-metrics.md
@@@ -76,16 -75,10 +76,19 @@@ lowercased and structurally bounded, bu
checked-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
+ `hermes.model_call.count` contract remains readable only so pending local
+ counters created by older builds can be exported without losing data.
+The first consented session start emits an empty `hermes.client.active` Relay
+mark. The profile-scoped subscriber creates a random UUID install identity and
+uses a transactional compare-and-set to record at most one active-install
+counter in any rolling 24-hour window. The metric has no dimensions; Hermes
+version, OS family, architecture, and install method remain bounded package
+resources. Concurrent Hermes processes share the SQLite latch, so simultaneous
+starts cannot double-count one install. A later session or task can attempt the
+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 to
the owning Hermes session. The start counter contains only bounded execution
surface and entrypoint values. The terminal counter contains bounded outcome,
diff --cc hermes_cli/observability/schemas/hermes.shared_metrics.v2.schema.json
index 00000000000,1416581a2ae..5d0bea610a7
mode 000000,100644..100644
--- a/hermes_cli/observability/schemas/hermes.shared_metrics.v2.schema.json
+++ b/hermes_cli/observability/schemas/hermes.shared_metrics.v2.schema.json
@@@ -1,0 -1,673 +1,702 @@@
+ {
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "urn:hermes-agent:schema:shared-metrics:v2",
+ "title": "Hermes Shared Metrics Package v2",
+ "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.v2"
+ },
+ "package_id": {
+ "$ref": "#/$defs/uuid"
+ },
+ "install_id": {
+ "description": "Random persistent identifier scoped to one HERMES_HOME; local-only in schema v2.",
+ "$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": ["docker", "git", "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"
+ }
+ ]
+ }
+ }
+ },
+ "$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._:/@+\\-]*$"
+ }
+ }
+ },
+ "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"
+ }
+ }
+ },
+ "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"
+ }
+ }
+ },
+ "value": {
+ "type": "integer",
+ "minimum": 1
+ }
+ }
+ },
+ "execution_surface": {
+ "enum": [
+ "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",
+ "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",
+ "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"
+ ]
+ }
+ }
+ }
diff --cc hermes_cli/observability/shared_metrics.py
index 85212f7cfc5,f488c0d8224..fd42b062306
--- a/hermes_cli/observability/shared_metrics.py
+++ b/hermes_cli/observability/shared_metrics.py
@@@ -17,9 -17,8 +17,9 @@@ from hermes_constants import get_hermes
from utils import atomic_json_write
from .shared_metrics_contract import (
+ CLIENT_ACTIVE_METRIC,
COUNTER_METRICS,
- MODEL_CALL_METRIC,
+ MODEL_ROUTE_METRIC,
client_resource_is_valid,
counter_dimensions_are_valid,
)
@@@ -66,57 -63,8 +66,57 @@@ class SharedMetricsStore
resource: dict[str, str],
) -> None:
"""Increment the terminal model-call counter for the current UTC day."""
- self.record_counter(MODEL_CALL_METRIC, dimensions, resource)
+ self.record_counter(MODEL_ROUTE_METRIC, dimensions, resource)
+ 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)
+ now = _utc_now()
+ with self._connection() as connection:
+ with write_txn(connection):
+ row = connection.execute(
+ "SELECT value FROM telemetry_state WHERE key = ?",
+ (_ACTIVE_INSTALL_STATE_KEY,),
+ ).fetchone()
+ if row is not None:
+ last_recorded = self._parse_state_timestamp(row["value"])
+ if last_recorded is not None and last_recorded > now:
+ # A wall-clock correction must not suppress activity until
+ # the stale future timestamp plus another full interval.
+ connection.execute(
+ """
+ UPDATE telemetry_state
+ SET value = ?
+ WHERE key = ?
+ """,
+ (_isoformat(now), _ACTIVE_INSTALL_STATE_KEY),
+ )
+ return False
+ if (
+ last_recorded is not None
+ and now < last_recorded + _ACTIVE_INSTALL_INTERVAL
+ ):
+ return False
+
+ self._install_id(connection)
+ self._record_counter_in_transaction(
+ connection,
+ CLIENT_ACTIVE_METRIC,
+ dimensions,
+ resource,
+ period_start=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)),
+ )
+ return True
+
def record_counter(
self,
metric_name: str,
diff --cc hermes_cli/observability/shared_metrics_contract.py
index 9969f01f6fc,2bbea8e1de0..b7637c9317c
--- a/hermes_cli/observability/shared_metrics_contract.py
+++ b/hermes_cli/observability/shared_metrics_contract.py
@@@ -18,8 -22,8 +23,9 @@@ TOOL_APPROVAL_MARK = "hermes.tool_appro
SKILL_LIFECYCLE_MARK = "hermes.skill.lifecycle"
SKILL_LOAD_MARK = "hermes.skill.load"
SUBSCRIBER_NAME = "hermes.nemo_relay.shared_metrics"
- MODEL_CALL_METRIC = "hermes.model_call.count"
+CLIENT_ACTIVE_METRIC = "hermes.client.active"
+ LEGACY_MODEL_CALL_METRIC = "hermes.model_call.count"
+ MODEL_ROUTE_METRIC = "hermes.model_route.count"
TASK_STARTED_METRIC = "hermes.task_run.started"
TASK_FINISHED_METRIC = "hermes.task_run.finished"
TOOL_CALL_METRIC = "hermes.tool_call.count"
@@@ -266,8 -272,48 +274,49 @@@ def client_resource_is_valid(resource:
)
+ _LEGACY_PROVIDER_FAMILIES = frozenset({
+ "aggregator",
+ "custom",
+ "direct",
+ "local",
+ "unknown",
+ })
+ _LEGACY_MODEL_LOCALITIES = frozenset({"local", "remote", "unknown"})
+ _LEGACY_MODEL_OUTCOMES = frozenset({"cancelled", "failed", "success"})
+ _LEGACY_MODEL_FAMILIES = frozenset({
+ "claude",
+ "deepseek",
+ "gemini",
+ "gemma",
+ "glm",
+ "gpt",
+ "grok",
+ "kimi",
+ "llama",
+ "minimax",
+ "mimo",
+ "mistral",
+ "nemotron",
+ "nova",
+ "o1",
+ "o3",
+ "o4",
+ "qwen",
+ "step",
+ "trinity",
+ "unknown",
+ })
+
_COUNTER_DIMENSION_VALUES: dict[str, dict[str, frozenset[str]]] = {
+ CLIENT_ACTIVE_METRIC: {},
+ # Retained only so pre-v2 pending rows remain packageable.
+ LEGACY_MODEL_CALL_METRIC: {
+ "call_role": frozenset({"primary"}),
+ "locality": _LEGACY_MODEL_LOCALITIES,
+ "model_family": _LEGACY_MODEL_FAMILIES,
+ "outcome": _LEGACY_MODEL_OUTCOMES,
+ "provider_family": _LEGACY_PROVIDER_FAMILIES,
+ },
TASK_STARTED_METRIC: {
"entrypoint": TASK_ENTRYPOINTS,
"execution_surface": EXECUTION_SURFACES,
@@@ -305,9 -351,15 +354,16 @@@
"use_count_bucket": COUNT_BUCKETS,
},
}
- COUNTER_METRICS: frozenset[str] = frozenset(
- {*_COUNTER_DIMENSION_VALUES, MODEL_CALL_METRIC}
- )
+ COUNTER_METRICS: frozenset[str] = frozenset({
++ CLIENT_ACTIVE_METRIC,
+ MODEL_ROUTE_METRIC,
+ SKILL_LIFECYCLE_METRIC,
+ SKILL_LOAD_METRIC,
+ TASK_FINISHED_METRIC,
+ TASK_STARTED_METRIC,
+ TOOL_APPROVAL_METRIC,
+ TOOL_CALL_METRIC,
+ })
def counter_dimensions_are_valid(
@@@ -348,24 -400,11 +404,27 @@@ def _event_metadata_is_valid(event: Any
) in {"OK", "ERROR"}
+def client_active_counter(event: Any) -> tuple[str, dict[str, str]] | None:
+ """Return the active-install counter for one empty allowlisted mark."""
+ if not _event_metadata_is_valid(event):
+ return None
+ if (
+ str(getattr(event, "kind", "") or "") != "mark"
+ or str(getattr(event, "name", "") or "") != CLIENT_ACTIVE_MARK
+ or getattr(event, "category", None) is not None
+ or getattr(event, "scope_category", None) is not None
+ or getattr(event, "category_profile", None) is not None
+ or getattr(event, "data", None) != {}
+ ):
+ return None
+ return CLIENT_ACTIVE_METRIC, {}
+
+
def model_call_dimensions(event: Any) -> dict[str, str] | None:
- """Return package dimensions for one valid primary model-call end event."""
+ """Return package dimensions for one valid logical model-call end event."""
+ auxiliary = _auxiliary_model_call_dimensions(event)
+ if auxiliary is not None:
+ return auxiliary
if not _event_metadata_is_valid(event):
return None
if (
diff --cc hermes_cli/observability/shared_metrics_subscriber.py
index 36ca4ce80ff,742edd9ca98..54c05e5780d
--- a/hermes_cli/observability/shared_metrics_subscriber.py
+++ b/hermes_cli/observability/shared_metrics_subscriber.py
@@@ -12,10 -12,8 +12,10 @@@ from hermes_cli.config import detect_in
from .shared_metrics import SharedMetricsStore
from .shared_metrics_contract import (
+ CLIENT_ACTIVE_METRIC,
- MODEL_CALL_METRIC,
+ MODEL_ROUTE_METRIC,
TOOL_CALL_METRIC,
+ client_active_counter,
client_resource,
model_call_dimensions,
skill_counter,
@@@ -61,14 -59,8 +61,14 @@@ class SharedMetricsSubscriber
or metadata.get(RUNTIME_INSTANCE_KEY) != self._runtime_id
):
return
- dimensions = model_call_dimensions(event)
- metric_name = MODEL_ROUTE_METRIC
+ metric = client_active_counter(event)
+ dimensions = None
+ metric_name = CLIENT_ACTIVE_METRIC
+ if metric is not None:
+ metric_name, dimensions = metric
+ if dimensions is None:
+ dimensions = model_call_dimensions(event)
- metric_name = MODEL_CALL_METRIC
++ metric_name = MODEL_ROUTE_METRIC
if dimensions is None:
dimensions = tool_call_dimensions(event)
metric_name = TOOL_CALL_METRIC
diff --cc scripts/smoke_nemo_relay_shared_metrics.py
index 49d5bb77512,b07bf5ae389..c7685bdb48a
--- a/scripts/smoke_nemo_relay_shared_metrics.py
+++ b/scripts/smoke_nemo_relay_shared_metrics.py
@@@ -298,8 -298,7 +298,8 @@@ def _validate_store(database_path: Path
for counter in counters:
by_name.setdefault(counter["name"], []).append(counter)
if set(by_name) != {
+ "hermes.client.active",
- "hermes.model_call.count",
+ "hermes.model_route.count",
"hermes.skill.lifecycle.count",
"hermes.skill.load.count",
"hermes.task_run.finished",
@@@ -309,20 -308,9 +309,20 @@@
raise AssertionError(
f"Unexpected SQLite counters:\n{json.dumps(counters, indent=2)}"
)
+ if by_name["hermes.client.active"] != [
+ {
+ "name": "hermes.client.active",
+ "dimensions": {},
+ "value": 1,
+ "packaged_value": 1,
+ }
+ ]:
+ raise AssertionError(
+ f"Unexpected client-active counter: {by_name['hermes.client.active']}"
+ )
- [model] = by_name["hermes.model_call.count"]
+ [model] = by_name["hermes.model_route.count"]
expected_model = {
- "name": "hermes.model_call.count",
+ "name": "hermes.model_route.count",
"dimensions": {
"model": MODEL_CANARY,
"provider": "custom",
@@@ -467,8 -455,7 +467,8 @@@ def _validate_packages
for metric in package.get("metrics", []):
metrics.setdefault(metric["name"], []).append(metric)
if set(metrics) != {
+ "hermes.client.active",
- "hermes.model_call.count",
+ "hermes.model_route.count",
"hermes.skill.lifecycle.count",
"hermes.skill.load.count",
"hermes.task_run.finished",
@@@ -478,30 -465,14 +478,25 @@@
raise AssertionError(
f"Unexpected package metrics:\n{json.dumps(metrics, indent=2)}"
)
+ if metrics["hermes.client.active"] != [
+ {
+ "name": "hermes.client.active",
+ "type": "counter",
+ "dimensions": {},
+ "value": 1,
+ }
+ ]:
+ raise AssertionError(
+ f"Unexpected client-active metric: {metrics['hermes.client.active']}"
+ )
- models = metrics["hermes.model_call.count"]
- if (
- sum(metric["value"] for metric in models) != 2
- or any(
- metric["dimensions"]
- != {
- "model": MODEL_CANARY,
- "provider": "custom",
- }
- for metric in models
+ [model] = metrics["hermes.model_route.count"]
+ if model["dimensions"] != {
+ "model": MODEL_CANARY,
+ "provider": "custom",
+ } or model["value"] != 2:
+ raise AssertionError(
+ f"Unexpected model metric: {metrics['hermes.model_route.count']}"
)
- ):
- raise AssertionError(f"Unexpected model metrics: {models}")
[terminal] = metrics["hermes.task_run.finished"]
if terminal["dimensions"] != {
"duration_bucket": terminal["dimensions"].get("duration_bucket"),
diff --cc tests/hermes_cli/test_relay_shared_metrics.py
index a05999d8e53,b84fe06b7b9..e26d3fd2caf
--- a/tests/hermes_cli/test_relay_shared_metrics.py
+++ b/tests/hermes_cli/test_relay_shared_metrics.py
@@@ -233,135 -363,11 +376,137 @@@ def test_due_export_runs_once_per_utc_d
assert len(list((tmp_path / "outbox").glob("*.json"))) == 3
+def test_client_active_uses_a_transactional_rolling_24_hour_latch(
+ tmp_path,
+ monkeypatch,
+):
+ database_path = tmp_path / "metrics.sqlite3"
+ outbox_directory = tmp_path / "outbox"
+ store = SharedMetricsStore(database_path, outbox_directory)
+ now = datetime(2026, 7, 22, 10, 0, tzinfo=timezone.utc)
+ monkeypatch.setattr(shared_metrics_module, "_utc_now", lambda: now)
+
+ assert store.record_client_active(_resource())
+ assert not store.record_client_active(_resource())
+
+ now += timedelta(hours=23, minutes=59, seconds=59)
+ assert not store.record_client_active(_resource())
+
+ now += timedelta(seconds=1)
+ assert store.record_client_active(_resource())
+
+ active = [
+ counter
+ for counter in store.counter_snapshot()
+ if counter["metric_name"] == CLIENT_ACTIVE_METRIC
+ ]
+ assert [counter["dimensions"] for counter in active] == [{}, {}]
+ assert [counter["period_start"] for counter in active] == [
+ "2026-07-22",
+ "2026-07-23",
+ ]
+ assert [counter["value"] for counter in active] == [1, 1]
+
+
+def test_client_active_recovers_from_an_invalid_latch_and_creates_identity(
+ tmp_path,
+ monkeypatch,
+):
+ database_path = tmp_path / "metrics.sqlite3"
+ store = SharedMetricsStore(database_path, tmp_path / "outbox")
+ with sqlite3.connect(database_path) as connection:
+ connection.execute(
+ "INSERT INTO telemetry_state(key, value) VALUES (?, ?)",
+ ("client_active_recorded_at", "invalid-timestamp"),
+ )
+ now = datetime(2026, 7, 22, 10, 0, tzinfo=timezone.utc)
+ monkeypatch.setattr(shared_metrics_module, "_utc_now", lambda: now)
+
+ assert store.record_client_active(_resource())
+
+ with sqlite3.connect(database_path) as connection:
+ state = dict(
+ connection.execute(
+ "SELECT key, value FROM telemetry_state WHERE key != 'schema_version'"
+ ).fetchall()
+ )
+ uuid.UUID(state["install_id"])
+ assert state["client_active_recorded_at"] == "2026-07-22T10:00:00Z"
+
+
+def test_client_active_rebases_a_future_latch_without_double_counting(
+ tmp_path,
+ monkeypatch,
+):
+ database_path = tmp_path / "metrics.sqlite3"
+ store = SharedMetricsStore(database_path, tmp_path / "outbox")
+ now = datetime(2026, 7, 22, 10, 0, tzinfo=timezone.utc)
+ monkeypatch.setattr(shared_metrics_module, "_utc_now", lambda: now)
+
+ assert store.record_client_active(_resource())
+ with sqlite3.connect(database_path) as connection:
+ connection.execute(
+ "UPDATE telemetry_state SET value = ? WHERE key = ?",
+ ("2026-07-24T10:00:00Z", "client_active_recorded_at"),
+ )
+
+ assert not store.record_client_active(_resource())
+ with sqlite3.connect(database_path) as connection:
+ latch = connection.execute(
+ "SELECT value FROM telemetry_state WHERE key = ?",
+ ("client_active_recorded_at",),
+ ).fetchone()[0]
+
+ assert latch == "2026-07-22T10:00:00Z"
+ [counter] = store.counter_snapshot()
+ assert counter["metric_name"] == CLIENT_ACTIVE_METRIC
+ assert counter["value"] == 1
+
+
+def test_client_active_package_uses_empty_dimensions_and_stable_install_id(tmp_path):
+ store = SharedMetricsStore(tmp_path / "metrics.sqlite3", tmp_path / "outbox")
+
+ assert store.record_client_active(_resource())
+ [package_path] = store.create_and_export_package()
+ package = json.loads(package_path.read_text(encoding="utf-8"))
+
+ _schema_validator().validate(package)
+ uuid.UUID(package["install_id"])
+ assert package["metrics"] == [
+ {
+ "name": CLIENT_ACTIVE_METRIC,
+ "type": "counter",
+ "dimensions": {},
+ "value": 1,
+ }
+ ]
+
+
+def test_deleting_local_metrics_state_resets_install_identity(tmp_path):
+ root = tmp_path / "shared-metrics"
+ database_path = root / "metrics.sqlite3"
+ outbox_directory = root / "outbox"
+ first = SharedMetricsStore(database_path, outbox_directory)
+ assert first.record_client_active(_resource())
+ [first_package_path] = first.create_and_export_package()
+ first_package = json.loads(first_package_path.read_text(encoding="utf-8"))
+
+ shutil.rmtree(root)
+
+ reset = SharedMetricsStore(database_path, outbox_directory)
+ assert reset.record_client_active(_resource())
+ [reset_package_path] = reset.create_and_export_package()
+ reset_package = json.loads(reset_package_path.read_text(encoding="utf-8"))
+
+ assert reset_package["install_id"] != first_package["install_id"]
+ assert reset_package["metrics"][0]["name"] == CLIENT_ACTIVE_METRIC
+
+
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 properties["model"]["maxLength"] == MODEL_IDENTIFIER_MAX_LENGTH
assert properties["provider"]["maxLength"] == PROVIDER_IDENTIFIER_MAX_LENGTH
@@@ -394,10 -400,7 +539,13 @@@ def test_package_schema_matches_the_cli
schema = json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))
resource = schema["properties"]["resource"]
- # Existing v1 outbox entries predate the bounded client dimensions. New
- # packages always populate every property, while the schema remains able
- # to validate those immutable queued payloads.
- assert set(resource["required"]) == {"hermes_version"}
- # Every v2 package records the complete bounded client resource.\n assert set(resource["required"]) == {\n "architecture",\n "hermes_version",\n "install_method",\n "os_family",\n }
++ # Every v2 package records the complete bounded client resource.
++ assert set(resource["required"]) == {
++ "architecture",
++ "hermes_version",
++ "install_method",
++ "os_family",
++ }
assert set(resource["properties"]) == {
"architecture",
"hermes_version",
@@@ -410,31 -413,6 +558,31 @@@
CLIENT_INSTALL_METHODS
)
+
+def test_client_active_mark_accepts_only_an_empty_allowlisted_payload():
+ event = SimpleNamespace(
+ kind="mark",
+ category=None,
+ category_profile=None,
+ name="hermes.client.active",
+ scope_category=None,
+ metadata={
- "hermes.metrics.schema_version": "hermes.metrics.event.v1",
++ "hermes.metrics.schema_version": "hermes.metrics.event.v2",
+ },
+ data={},
+ )
+
+ assert client_active_counter(event) == (CLIENT_ACTIVE_METRIC, {})
+
+ with_payload = deepcopy(event)
+ with_payload.data = {"session_id": "privacy-canary"}
+ assert client_active_counter(with_payload) is None
+
+ wrong_schema = deepcopy(event)
+ wrong_schema.metadata["hermes.metrics.schema_version"] = "unknown"
+ assert client_active_counter(wrong_schema) is None
+
+
def test_package_schema_matches_the_task_contract():
schema = json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))
start = _task_dimension_schema("task_started_counter")["properties"]
diff --cc tests/hermes_cli/test_relay_shared_metrics_runtime.py
index f2567b5e326,67a72ccc358..dfff0f299df
--- a/tests/hermes_cli/test_relay_shared_metrics_runtime.py
+++ b/tests/hermes_cli/test_relay_shared_metrics_runtime.py
@@@ -372,20 -365,13 +372,20 @@@ def test_direct_runtime_records_without
package = json.loads(packages[0].read_text(encoding="utf-8"))
metrics = {metric["name"]: metric for metric in package["metrics"]}
assert set(metrics) == {
+ "hermes.client.active",
- "hermes.model_call.count",
+ "hermes.model_route.count",
"hermes.task_run.finished",
"hermes.task_run.started",
"hermes.tool_approval.count",
"hermes.tool_call.count",
}
+ assert metrics["hermes.client.active"] == {
+ "name": "hermes.client.active",
+ "type": "counter",
+ "dimensions": {},
+ "value": 1,
+ }
- assert metrics["hermes.model_call.count"]["dimensions"] == {
+ assert metrics["hermes.model_route.count"]["dimensions"] == {
"model": "claude-sonnet",
"provider": "anthropic",
}
@@@ -604,12 -590,10 +604,12 @@@ def test_real_binding_drives_lifecycle_
for counter in snapshot:
by_metric.setdefault(counter["metric_name"], []).append(counter)
+ assert by_metric["hermes.client.active"][0]["dimensions"] == {}
+ assert by_metric["hermes.client.active"][0]["value"] == 1
assert len(by_metric["hermes.task_run.started"]) == 1
assert by_metric["hermes.task_run.started"][0]["value"] == 3
- assert len(by_metric["hermes.model_call.count"]) == 1
- model_counter = by_metric["hermes.model_call.count"][0]
+ 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",