The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(telemetry): engagement and switch_after count only a person's turns (M1, M3, M7, M8, m6)
teknium14c7085d28489
diff --git a/hermes_cli/observability/relay_shared_metrics.py b/hermes_cli/observability/relay_shared_metrics.pyindex 924e0a0aa71..80265da96b2 100644--- a/hermes_cli/observability/relay_shared_metrics.py+++ b/hermes_cli/observability/relay_shared_metrics.py@@ -140,6 +140,8 @@ class _TaskRun:unidentified_tool_calls: int = 0retry_count: int = 0model_route: dict[str, str] | None = None+ # The route the turn was sent on (its first request): provider failover does not change it.+ selected_route: dict[str, str] | None = Nonecost: eff.TurnCost = field(default_factory=eff.TurnCost)@@ -382,6 +384,7 @@ class _Runtime:returnif task is not None:task.model_route = fields+ task.selected_route = task.selected_route or fieldstask.model_call_ids.add(request_id)if _retry_ordinal(event) > 0:# A real Hermes retry can advance api_request_id while carrying the@@ -905,13 +908,13 @@ class _Runtime:"""A turn the user saw end (session-close aborts excluded): trailing-failure state and interrupts."""route = task.model_route or session.model_state.last_routesession.model_state.observe_turn(fields["outcome"], route, session.last_turn_ns)- if task.model_route is not None:- self._with_route_run(session.session_id, session.route_run, lambda run: run.observe(task.model_route))- if model_.attended(task.start_fields):- self._guarded(- "Hermes shared-metrics engagement mark failed", self._mark,- session, None, contract.ENGAGEMENT_TURN_MARK, dict(task.model_route),- )+ if task.selected_route is not None and task.cost.user_turn:+ self._with_route_run(session.session_id, session.route_run, lambda run: run.observe(task.selected_route))+ if task.model_route is not None and engagement_.engaged_turn(task.start_fields, task.cost.user_turn):+ self._guarded(+ "Hermes shared-metrics engagement mark failed", self._mark,+ session, None, contract.ENGAGEMENT_TURN_MARK, dict(task.model_route),+ )if fields["end_reason"] == "user_cancelled" and route is not None and model_.attended(task.start_fields):self._guarded("Hermes shared-metrics friction mark failed", self._mark,diff --git a/hermes_cli/observability/shared_metrics_engagement.py b/hermes_cli/observability/shared_metrics_engagement.pyindex ed749dad9c0..2188930a488 100644--- a/hermes_cli/observability/shared_metrics_engagement.py+++ b/hermes_cli/observability/shared_metrics_engagement.py@@ -42,10 +42,9 @@ _ACTIVE_THRESHOLDS = ((360 * _MINUTE_MS, "2h_to_6h"),)_SWITCH_THRESHOLDS = ((2, "1"), (4, "2_to_3"), (11, "4_to_10"), (31, "11_to_30"))-# Task entrypoints that are a person (or their schedule) using Hermes; delegated children,-# background review forks, batch and API/python embedding are not engagement.-_ENGAGED_ENTRYPOINTS = frozenset({"gateway_message", "interactive", "scheduled_task"})-_SURFACE_NAMES = {"scheduled_task": "cron"}+# Task entrypoints that are a person using Hermes. Unattended cron runs (counted by hermes.cron.run),+# delegated children, background review forks, batch and API/python embedding are not engagement.+_ENGAGED_ENTRYPOINTS = frozenset({"gateway_message", "interactive"})_INTERACTION_METRICS = frozenset({contract.TASK_STARTED_METRIC, contract.TASK_FINISHED_METRIC})_ALL = "*"@@ -72,11 +71,15 @@ def interaction_surface(classified: list[tuple[str, dict, int]]) -> str | None:for metric_name, dimensions, _ in classified:if metric_name in _INTERACTION_METRICS and dimensions.get("entrypoint") in _ENGAGED_ENTRYPOINTS:surface = dimensions.get("execution_surface", "")- surface = _SURFACE_NAMES.get(surface, surface)return surface if surface in contract.ENGAGEMENT_SURFACES else Nonereturn None+def engaged_turn(start_fields: dict[str, str] | None, user_turn: bool) -> bool:+ """A turn a person sent on an engagement surface (its model counts toward the day's primary model)."""+ return user_turn and (start_fields or {}).get("entrypoint") in _ENGAGED_ENTRYPOINTS++def turn_route(event: Any) -> tuple[str, str] | None:"""(provider, model) of one validated engagement turn mark."""if not contract._valid_shape(event, **contract._MARK_SHAPE):@@ -214,13 +217,14 @@ def _primary(models: dict[str, Any]) -> tuple[str, str]:def close_day(state: dict[str, Any]) -> list[tuple[str, dict, dict, str]]:- """The rows one closed day reports (none for a day with no activity)."""+ """The rows one closed day reports: none for a day with no engaged surface, except the root+ profile's host row (0 minutes, 0 surfaces) carrying the day's active-profile count."""day, resource = state["day"], state.get("resource") or {}streams = {k: v for k, v in state["surfaces"].items() if isinstance(v, list) and len(v) == 2}surfaces = {k: v for k, v in streams.items() if k in contract.ENGAGEMENT_SURFACES}profiles = state.get("profiles") if state.get("owner") is True else Noneactive_profiles = len(profiles) if isinstance(profiles, list) else 0- if not surfaces and not state["models"] and not active_profiles:+ if not surfaces and not active_profiles:return []rows = [(contract.ENGAGEMENT_SURFACE_METRIC,diff --git a/tests/hermes_cli/test_shared_metrics_engagement.py b/tests/hermes_cli/test_shared_metrics_engagement.pyindex d85cc9c758a..b669931d4d8 100644--- a/tests/hermes_cli/test_shared_metrics_engagement.py+++ b/tests/hermes_cli/test_shared_metrics_engagement.py@@ -87,6 +87,25 @@ def test_a_closed_day_reports_active_time_surfaces_and_primary_model_once(directassert periods == {"2026-09-27"}+def test_internal_and_unattended_turns_are_not_engagement(direct_runtime, tmp_path, clock):+ """API-server and cron turns add no active time, surface, profile or primary model: a day of them+ alone reports nothing, and they never outvote the person's model."""+ _turn("api-1", "a1", platform="api_server", model=OTHER, clock=clock, at=DAY1)+ _turn("cron-1", "c1", platform="cron", model=OTHER, clock=clock, at=DAY1 + 300, took=7200)+ _turn("cli-1", "t0", clock=clock, at=DAY1 + 86_400) # day 2 closes day 1+ _flush()+ assert not _stored_values(tmp_path, "hermes.engagement.day.count")+ for n in range(5):+ _turn("api-1", f"a{n + 2}", platform="api_server", model=OTHER, clock=clock, at=DAY1 + 86_400 + 60 * n)+ _turn("cli-1", "t1", clock=clock, at=DAY1 + 86_400 + 400)+ clock["now"] = DAY1 + 2 * 86_400+ _turn("cli-1", "t2", clock=clock, at=DAY1 + 2 * 86_400)+ _flush()+ [(day, _)] = _stored_values(tmp_path, "hermes.engagement.day.count")+ assert (day["primary_model"], day["surfaces_used_count"]) == (PUBLIC, "1")+ assert [d["surface"] for d, _ in _stored_values(tmp_path, "hermes.engagement.surface_day.count")] == ["cli"]++def test_collection_off_writes_no_engagement_state(direct_runtime, tmp_path, clock, monkeypatch):monkeypatch.setattr("hermes_cli.config.read_raw_config_readonly", lambda: {})_turn("s1", "t1", clock=clock, at=DAY1)@@ -193,6 +212,30 @@ def test_a_background_review_fork_on_the_session_id_adds_no_session_volume(direcassert (row["turn_count_bucket"], row["model_call_count_bucket"], row["message_count_bucket"]) == ("1", "1", "2")+def test_turns_before_switch_ignore_failover_and_review_forks(direct_runtime, tmp_path):+ """The run counts the route each user turn was sent on: a turn that failed over to a fallback+ still served the selected model, and a background review fork on another model is not a turn."""+ from hermes_cli.observability.shared_metrics_events import record_model_switch++ _turn("s1", "t1")+ base = {"session_id": "s1", "task_id": "t2", "provider": "openrouter"}+ lifecycle.invoke_hook("pre_llm_call", **base, model=PUBLIC, platform="cli")+ lifecycle.invoke_hook("pre_api_request", **base, model=PUBLIC, api_request_id="t2-r")+ lifecycle.invoke_hook("api_request_error", **base, model=PUBLIC, api_request_id="t2-r")+ lifecycle.invoke_hook("pre_api_request", **base, model=OTHER, api_request_id="t2-fallback")+ lifecycle.invoke_hook("post_api_request", **base, model=OTHER, api_request_id="t2-fallback", usage={})+ relay_shared_metrics.finish_task_run(session_id="s1", task_id="t2", platform="cli", result={"completed": True})+ relay_shared_metrics.start_task_run(session_id="s1", task_id="review", platform="cli")+ lifecycle.invoke_hook("pre_api_request", session_id="s1", task_id="review", provider="openrouter",+ model=OTHER, api_request_id="rv-r")+ relay_shared_metrics.finish_task_run(session_id="s1", task_id="review", platform="cli", result={"completed": True})+ record_model_switch(from_provider="openrouter", to_provider="openrouter", surface="cli",+ from_model=PUBLIC, session_id="s1")+ _flush()+ assert _stored_values(tmp_path, "hermes.model_switch_after.count") == [+ ({"model": PUBLIC, "provider": "openrouter", "turns_before_switch_bucket": "2_to_3"}, 1)]++def test_turns_before_switch_count_the_model_left_across_rotation(direct_runtime, tmp_path):"""/model counts how many turns the model being left served in the conversation (compressionsegments included); a second switch before any turn on the new model reports nothing."""diff --git a/website/docs/developer-guide/relay-shared-metrics.md b/website/docs/developer-guide/relay-shared-metrics.mdindex 869e1af9f91..35fee81b6ac 100644--- a/website/docs/developer-guide/relay-shared-metrics.md+++ b/website/docs/developer-guide/relay-shared-metrics.md@@ -402,19 +402,20 @@ the curator, delegated subagents' own turns) is not a user turn.| Metric | Dimensions | Question it answers ||---|---|---|-| `hermes.engagement.surface_day.count` | surface (`cli`, `tui`, `desktop`, `gateway`, `acp`, `cron`), active-minutes bucket (`0`, `lt_5m`, `5m_to_30m`, `30m_to_2h`, `2h_to_6h`, `gte_6h`) | How long each surface is actually used per day. One row per surface used on a closed UTC day. |-| `hermes.engagement.day.count` | active-minutes bucket, surfaces-used count (`0`–`3`, `gte_4`), primary provider, primary model, active-profile count bucket | Days active per week, multi-surface use, and next-day / next-week return by model. One row per closed UTC day with activity. |-| `hermes.model_switch_after.count` | provider, model (the model switched away from), turns-before-switch bucket (`1`, `2_to_3`, `4_to_10`, `11_to_30`, `gte_31`) | How long users stay on a model before `/model` leaves it. Counts the old model's turns in the conversation (compression segments included); a switch before any turn on the current model is not counted. |+| `hermes.engagement.surface_day.count` | surface (`cli`, `tui`, `desktop`, `gateway`, `acp`), active-minutes bucket (`0`, `lt_5m`, `5m_to_30m`, `30m_to_2h`, `2h_to_6h`, `gte_6h`) | How long each surface is actually used per day. One row per surface used on a closed UTC day. |+| `hermes.engagement.day.count` | active-minutes bucket, surfaces-used count (`0`–`3`, `gte_4`), primary provider, primary model, active-profile count bucket | Days active per week, multi-surface use, and next-day / next-week return by model. One row per closed UTC day a person used Hermes on. The root (default) profile also writes a host row on days only other profiles were active: `surfaces_used_count` `0`, active minutes `0`, carrying the active-profile count; exclude `surfaces_used_count=0` rows when counting days active. |+| `hermes.model_switch_after.count` | provider, model (the model switched away from), turns-before-switch bucket (`1`, `2_to_3`, `4_to_10`, `11_to_30`, `gte_31`) | How long users stay on a model before `/model` leaves it. Counts the user turns sent on the old model in the conversation (compression segments included; a turn that failed over to a fallback still counts for the model it was sent on; background review forks are not turns); a switch before any turn on the current model is not counted. |Active time is accumulated locally per UTC day: the sum of the gaps between-consecutive interactions (a user-owned turn starting or ending: interactive-surfaces, gateway messages and cron runs; delegated children, background-review, batch and API/python embedding are excluded), each gap capped at 5+consecutive interactions (a user turn starting or ending on an interactive+surface or a gateway message; unattended cron runs, which `hermes.cron.run`+counts, delegated children, background review, curator, batch and API-server /+python embedding are excluded), each gap capped at 5minutes. The day's rows are recorded once the day closes, by the firstinteraction on a later day, in one database transaction, so a day is reportedexactly once per profile however many processes see the rollover; they aredated to the day they describe. The primary model is the one that served the-most attended turns that day (`none` when none did), named by the model-route+most of those user turns that day (`none` when none did), named by the model-routerules. Days active per week and return by model are derived server-side fromthese daily rows and the existing `install_id`: Hermes keeps no weekly windowand no identifier beyond `install_id` for them.