Skip to content

The agent that grows with you

feat(telemetry): v5 engagement rollup, turns-before-switch, per-conversation sessions, relay source platform

teknium1928daa63af57
diff --git a/acp_adapter/server.py b/acp_adapter/server.py
index e9d1d902dc0..2ba7d0e8ff4 100644
--- a/acp_adapter/server.py
+++ b/acp_adapter/server.py
@@ -359,7 +359,8 @@ class HermesACPAgent(SlashCommandsMixin, acp.Agent):
from hermes_cli.observability.shared_metrics_events import record_model_switch
record_model_switch(
- from_provider=current_provider, to_provider=target_provider, surface="acp", from_model=current_model)
+ from_provider=current_provider, to_provider=target_provider, surface="acp", from_model=current_model,
+ session_id=state.session_id)
return current_provider, target_provider, new_model
@staticmethod
diff --git a/gateway/slash_commands_model.py b/gateway/slash_commands_model.py
index 0b9c02492e4..ceaf38246c4 100644
--- a/gateway/slash_commands_model.py
+++ b/gateway/slash_commands_model.py
@@ -388,11 +388,14 @@ class GatewayModelCommandsMixin:
if getattr(getattr(self, "config", None), "multiplex_profiles", False):
with contextlib.suppress(Exception):
home = self._resolve_profile_home_for_source(source)
+ session_id = None
+ with contextlib.suppress(Exception):
+ session_id = getattr(self._cached_agent_for(ctx.session_key), "session_id", None)
token = set_hermes_home_override(str(home)) if home else None
try:
record_model_switch(
from_provider=ctx.route_provider, to_provider=result.target_provider, surface="gateway",
- from_model=ctx.current_model)
+ from_model=ctx.current_model, session_id=session_id)
finally:
if token is not None:
reset_hermes_home_override(token)
diff --git a/hermes_cli/cli_model_switch_mixin.py b/hermes_cli/cli_model_switch_mixin.py
index fdf370d1efe..28b6b1e6ed2 100644
--- a/hermes_cli/cli_model_switch_mixin.py
+++ b/hermes_cli/cli_model_switch_mixin.py
@@ -247,7 +247,8 @@ def _commit_model_switch(
if not getattr(cli, "is_slash_worker", False):
from hermes_cli.observability.shared_metrics_events import record_model_switch
record_model_switch(
- from_provider=old_provider, to_provider=result.target_provider, surface="cli", from_model=old_model)
+ from_provider=old_provider, to_provider=result.target_provider, surface="cli", from_model=old_model,
+ session_id=getattr(getattr(cli, "agent", None), "session_id", None) or getattr(cli, "session_id", None))
if not picker:
cli._pending_one_turn_model_restore = snapshot
_print_switch_summary(cli, result, old_model, one_turn=one_turn, strict_context=not picker)
diff --git a/hermes_cli/observability/relay_shared_metrics.py b/hermes_cli/observability/relay_shared_metrics.py
index f9aacbcadc1..64d5806b12b 100644
--- a/hermes_cli/observability/relay_shared_metrics.py
+++ b/hermes_cli/observability/relay_shared_metrics.py
@@ -20,6 +20,7 @@ from hermes_cli.version_info import get_version_info
from .shared_metrics import SharedMetricsStore
from . import shared_metrics_contract as contract
from . import shared_metrics_efficiency as eff
+from . import shared_metrics_engagement as engagement_
from . import shared_metrics_fields as fields_
from . import shared_metrics_model as model_
from .shared_metrics_contract import MODEL_CALL_SCOPE, SUBSCRIBER_NAME, TASK_SCOPE
@@ -162,15 +163,22 @@ class _MetricsSession:
model_state: model_.ModelSessionState = field(default_factory=model_.ModelSessionState)
lineage_root: str = ""
efficiency: eff.SessionEfficiency = field(default_factory=eff.SessionEfficiency)
+ route_run: engagement_.RouteRun = field(default_factory=engagement_.RouteRun)
+ api_calls: int = 0
+ tool_call_total: int = 0
+ replies: int = 0
@dataclass
class _PeakLineage:
- """Open segments of one conversation (compression rotates the session id) and their merged peak."""
+ """Open segments of one conversation (compression rotates the session id), their merged peak and
+ session tally, and the conversation's current-model turn run."""
open: set[str] = field(default_factory=set)
peak: model_.ModelSessionState = field(default_factory=model_.ModelSessionState)
tools: eff.ToolUsage = field(default_factory=eff.ToolUsage)
+ tally: engagement_.SessionTally = field(default_factory=engagement_.SessionTally)
+ run: engagement_.RouteRun = field(default_factory=engagement_.RouteRun)
def _absorb_peak(into: model_.ModelSessionState, segment: model_.ModelSessionState) -> None:
@@ -396,6 +404,7 @@ class _Runtime:
model_call.fields = contract.model_call_fields(event)
self._join_lineage(session, session.tasks.get(model_call.task_id))
if finish:
+ session.replies += 1
session.model_state.observe_call(model_call.fields, event.get("usage"), event.get("context_length"))
self._observe_turn_call(session, session.tasks.get(model_call.task_id), model_call, event)
model_call.ttft_bucket = fields_.ttft_bucket(event)
@@ -841,6 +850,8 @@ class _Runtime:
tool_call_count=len(task.tool_call_ids) + task.unidentified_tool_calls,
retry_count=task.retry_count,
)
+ if not session.closing:
+ self._join_lineage(session, task)
self._count_session_turn(session, task, fields["outcome"])
if not session.closing:
self._observe_model_turn(session, task, fields)
@@ -868,6 +879,8 @@ class _Runtime:
session.first_turn_ns = task.started_ns
session.turns += 1
session.failed_turns += outcome == "failed"
+ session.api_calls += len(task.model_call_ids)
+ session.tool_call_total += len(task.tool_call_ids) + task.unidentified_tool_calls
session.last_outcome = outcome
session.last_turn_ns = monotonic_ns()
@@ -875,6 +888,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_route
session.model_state.observe_turn(fields["outcome"], route, session.last_turn_ns)
+ if task.model_route is not None:
+ self._with_route_run(session, 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 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,
@@ -962,36 +982,65 @@ class _Runtime:
with self._lineage_lock:
self._lineages.setdefault(root, _PeakLineage()).open.add(session.session_id)
- def _close_lineage_segment(
- self, session: _MetricsSession, counted: bool
- ) -> tuple[dict[str, str] | None, eff.ToolUsage | None]:
- """This session's context peak and tool usage, or, for a lineage segment, the conversation's
- merged ones once its last open segment closes (None before that)."""
+ def _with_route_run(self, session: _MetricsSession, update: Callable[[engagement_.RouteRun], Any]) -> Any:
+ """Apply ``update`` to the conversation's model-turn run (the lineage's, shared by its segments)."""
+ with self._lineage_lock:
+ lineage = self._lineages.get(session.lineage_root) if session.lineage_root else None
+ return update(lineage.run if lineage is not None else session.route_run)
+
+ def _close_segment(
+ self, session: _MetricsSession, counted: bool,
+ ) -> tuple[model_.ModelSessionState | None, engagement_.SessionTally | None, eff.ToolUsage | None]:
+ """This session's context peak, tally and tool usage, or, for a lineage segment, the
+ conversation's merged ones once its last open segment closes (None before that)."""
state = session.model_state if counted else None
+ tally = engagement_.SessionTally(
+ session.start_fields, session.turns, session.failed_turns, session.last_outcome,
+ session.first_turn_ns, session.last_turn_ns, session.api_calls, session.tool_call_total, session.replies,
+ ) if counted else None
tools = session.efficiency.tools if counted and model_.attended(session.start_fields) else eff.ToolUsage()
tools.surface = (session.start_fields or {}).get("execution_surface", "unknown")
with self._lineage_lock:
lineage = self._lineages.get(session.lineage_root) if session.lineage_root else None
if lineage is None:
- return (state.context_peak_fields() if state is not None else None), tools
+ return state, tally, tools
lineage.open.discard(session.session_id)
- if state is not None:
+ if state is not None and tally is not None:
_absorb_peak(lineage.peak, state)
+ lineage.tally.absorb(tally)
lineage.tools.absorb(tools)
if lineage.open:
- return None, None
+ return None, None, None
del self._lineages[session.lineage_root]
- return lineage.peak.context_peak_fields(), lineage.tools
+ return lineage.peak, lineage.tally, lineage.tools
- def _emit_model_session_marks(self, session: _MetricsSession, counted: bool) -> None:
- peak, tools = self._close_lineage_segment(session, counted)
- marks = [(contract.CONTEXT_PEAK_MARK, peak), *(tools.rows() if tools is not None else ())]
+ def _emit_session_summary(self, session: _MetricsSession) -> None:
+ """One hermes.session.count and context-peak row per closed top-level conversation (delegated
+ children excluded; compression-rotated segments merged), its tool usage, plus a quick-abandon friction."""
+ start = session.start_fields
+ counted = bool(session.turns) and start is not None and start.get("entrypoint") != "delegated"
+ peak, tally, tools = self._close_segment(session, counted)
+ marks = [
+ (contract.CONTEXT_PEAK_MARK, peak.context_peak_fields() if peak is not None else None),
+ (contract.SESSION_MARK, tally.fields() if tally is not None else None),
+ *(tools.rows() if tools is not None else ()),
+ ]
abandoned = session.model_state.quick_abandon_route(monotonic_ns()) if counted else None
- if abandoned is not None and model_.attended(session.start_fields):
+ if abandoned is not None and model_.attended(start):
marks.append((contract.MODEL_FRICTION_MARK, model_.friction_fields("quick_abandon", abandoned)))
for mark, data in marks:
if data is not None:
- self._guarded("Hermes shared-metrics model session mark failed", self._mark, session, None, mark, data)
+ self._guarded("Hermes shared-metrics session summary failed", self._mark, session, None, mark, data)
+
+ def record_switch_after(self, session_id: str) -> None:
+ """A counted /model switch: how many turns the model being left served in this conversation."""
+ session = self._session({"session_id": session_id})
+ if session is None:
+ return
+ with session.lock:
+ taken = self._with_route_run(session, lambda run: run.take())
+ if taken is not None:
+ self.record_process_mark(contract.MODEL_SWITCH_AFTER_MARK, engagement_.switch_after_fields(*taken))
def record_friction(self, signal: str, session_id: str, fallback_route: dict[str, str], turns: int = 1) -> None:
"""A user friction action, attributed to the session's last primary model when known; an
@@ -1010,23 +1059,6 @@ class _Runtime:
self.record_process_mark(contract.MODEL_FRICTION_MARK, data)
self._emit_rows(None, wasted)
- def _emit_session_summary(self, session: _MetricsSession) -> None:
- """One hermes.session.count row per closed top-level session (delegated children excluded)."""
- start = session.start_fields
- counted = bool(session.turns) and start is not None and start.get("entrypoint") != "delegated"
- self._emit_model_session_marks(session, counted)
- if not counted:
- return
- summary = fields_.session_fields(
- start, turns=session.turns, failed_turns=session.failed_turns,
- last_outcome=session.last_outcome,
- active_ms=max(0, session.last_turn_ns - session.first_turn_ns) // 1_000_000,
- )
- self._guarded(
- "Hermes shared-metrics session summary failed", self._mark,
- session, None, contract.SESSION_MARK, summary,
- )
-
def record_process_mark(self, mark: str, data: dict[str, Any]) -> None:
"""A process-level fact with no owning task (setup, installs, commands, switches)."""
# No flush here: the next task close or the atexit shutdown drains the subscriber.
@@ -1333,6 +1365,16 @@ def record_known_cache_break(cause: str, route: dict[str, str], session_id: str)
runtime._safe(runtime.record_known_cache_break, cause, route, session_id)
+def record_model_switch_after(session_id: str) -> None:
+ """Count turns-before-switch for a session this process served; never creates a runtime (a
+ runtime that does not exist saw no turns). Callers are already in the owning profile's scope."""
+ if not session_id or not enabled() or not relay_runtime.relay_instrumentation_enabled():
+ return
+ runtime = _RUNTIMES.get(relay_runtime.current_profile_key())
+ if isinstance(runtime, _Runtime):
+ runtime._safe(runtime.record_switch_after, session_id)
+
+
def _run_task_hook(method: str, *, retry_failed: bool = False, **event: Any) -> None:
if not enabled():
return
diff --git a/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.json b/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.json
index 2911dd478cf..4a09969beba 100644
--- a/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.json
+++ b/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.json
@@ -228,6 +228,15 @@
},
{
"$ref": "#/$defs/cache_break_counter"
+ },
+ {
+ "$ref": "#/$defs/engagement_day_counter"
+ },
+ {
+ "$ref": "#/$defs/engagement_surface_day_counter"
+ },
+ {
+ "$ref": "#/$defs/model_switch_after_counter"
}
]
}
@@ -1192,8 +1201,18 @@
},
"turn_count_bucket": {
"$ref": "#/$defs/size_bucket"
+ },
+ "message_count_bucket": {
+ "$ref": "#/$defs/long_size_bucket"
+ },
+ "model_call_count_bucket": {
+ "$ref": "#/$defs/long_size_bucket"
+ },
+ "tool_call_count_bucket": {
+ "$ref": "#/$defs/long_size_bucket"
}
- }
+ },
+ "description": "v5 engagement: message/model-call/tool-call buckets are optional so session rows recorded before them still validate; one row per conversation (compression-rotated segments merged)."
},
"value": {
"type": "integer",
@@ -3245,6 +3264,194 @@
"minimum": 1
}
}
+ },
+ "engagement_day_counter": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "name",
+ "type",
+ "dimensions",
+ "value"
+ ],
+ "properties": {
+ "name": {
+ "const": "hermes.engagement.day.count"
+ },
+ "type": {
+ "const": "counter"
+ },
+ "dimensions": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "active_minutes_bucket",
+ "active_profile_count_bucket",
+ "primary_model",
+ "primary_provider",
+ "surfaces_used_count"
+ ],
+ "properties": {
+ "active_minutes_bucket": {
+ "enum": [
+ "0",
+ "lt_5m",
+ "5m_to_30m",
+ "30m_to_2h",
+ "2h_to_6h",
+ "gte_6h"
+ ]
+ },
+ "active_profile_count_bucket": {
+ "$ref": "#/$defs/size_bucket"
+ },
+ "primary_model": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 256,
+ "pattern": "^[a-z0-9][a-z0-9._:/@+\\-]*$"
+ },
+ "primary_provider": {
+ "$ref": "#/$defs/provider_identifier"
+ },
+ "surfaces_used_count": {
+ "enum": [
+ "0",
+ "1",
+ "2",
+ "3",
+ "gte_4"
+ ]
+ }
+ },
+ "description": "v5 engagement: one per closed UTC day with activity: total active time (inter-interaction gaps capped at 5 minutes), surfaces used, and the model that served most attended turns (none when no attended turn). active_profile_count_bucket: distinct profiles of the host with a user turn that day, reported only on the root (default) profile's row; other profiles' rows carry 0."
+ },
+ "value": {
+ "type": "integer",
+ "minimum": 1
+ }
+ }
+ },
+ "engagement_surface_day_counter": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "name",
+ "type",
+ "dimensions",
+ "value"
+ ],
+ "properties": {
+ "name": {
+ "const": "hermes.engagement.surface_day.count"
+ },
+ "type": {
+ "const": "counter"
+ },
+ "dimensions": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "active_minutes_bucket",
+ "surface"
+ ],
+ "properties": {
+ "active_minutes_bucket": {
+ "enum": [
+ "0",
+ "lt_5m",
+ "5m_to_30m",
+ "30m_to_2h",
+ "2h_to_6h",
+ "gte_6h"
+ ]
+ },
+ "surface": {
+ "enum": [
+ "acp",
+ "cli",
+ "cron",
+ "desktop",
+ "gateway",
+ "tui"
+ ]
+ }
+ },
+ "description": "v5 engagement: one per surface used on a closed UTC day, with that surface's active time."
+ },
+ "value": {
+ "type": "integer",
+ "minimum": 1
+ }
+ }
+ },
+ "model_switch_after_counter": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "name",
+ "type",
+ "dimensions",
+ "value"
+ ],
+ "properties": {
+ "name": {
+ "const": "hermes.model_switch_after.count"
+ },
+ "type": {
+ "const": "counter"
+ },
+ "dimensions": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "model",
+ "provider",
+ "turns_before_switch_bucket"
+ ],
+ "properties": {
+ "model": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 256,
+ "pattern": "^[a-z0-9][a-z0-9._:/@+\\-]*$"
+ },
+ "provider": {
+ "$ref": "#/$defs/provider_identifier"
+ },
+ "turns_before_switch_bucket": {
+ "enum": [
+ "1",
+ "2_to_3",
+ "4_to_10",
+ "11_to_30",
+ "gte_31"
+ ]
+ }
+ },
+ "description": "v5 engagement: one per /model switch away from a model that served turns in the conversation, with how many."
+ },
+ "value": {
+ "type": "integer",
+ "minimum": 1
+ }
+ }
+ },
+ "long_size_bucket": {
+ "description": "v5 engagement: size_bucket with a longer tail for conversation volume.",
+ "enum": [
+ "0",
+ "1",
+ "2",
+ "3_to_5",
+ "6_to_10",
+ "11_to_25",
+ "26_to_100",
+ "101_to_250",
+ "gte_251",
+ "251_to_1000",
+ "gte_1001"
+ ]
}
}
}
diff --git a/hermes_cli/observability/shared_metrics.py b/hermes_cli/observability/shared_metrics.py
index 58bb807a921..c1372deca57 100644
--- a/hermes_cli/observability/shared_metrics.py
+++ b/hermes_cli/observability/shared_metrics.py
@@ -6,7 +6,7 @@ import json
import logging
import sqlite3
import uuid
-from collections.abc import Iterator
+from collections.abc import Callable, Iterator
from contextlib import contextmanager
from datetime import datetime, timedelta, timezone
from pathlib import Path
@@ -263,6 +263,37 @@ class SharedMetricsStore:
connection, metric_name, dimensions, resource, _utc_now().date().isoformat(), amount
)
+ def update_rollup_state(
+ self, state_key: str,
+ update: Callable[[dict[str, Any] | None], tuple[dict[str, Any], list[tuple[str, dict, dict, str]]]],
+ ) -> None:
+ """Read-modify-write one JSON rollup state and record the ``(metric, dimensions, resource,
+ period_start)`` rows ``update`` closes, in one write transaction: every process of the profile
+ serializes here, so a closed period is emitted exactly once. Rows the contract rejects are
+ dropped (never retried) so one bad row cannot wedge the rollup."""
+ with self._write() as connection:
+ row = connection.execute(
+ "SELECT value FROM telemetry_state WHERE key = ?", (state_key,)
+ ).fetchone()
+ try:
+ state = json.loads(row["value"]) if row is not None else None
+ except (TypeError, ValueError):
+ state = None
+ new_state, rows = update(state if isinstance(state, dict) else None)
+ valid = [
+ r for r in rows
+ if counter_dimensions_are_valid(r[0], r[1]) and client_resource_is_valid(r[2])
+ ]
+ if valid:
+ self._install_id(connection)
+ for metric_name, dimensions, resource, period_start in valid:
+ self._record_counter_in_transaction(connection, metric_name, dimensions, resource, period_start)
+ connection.execute(
+ "INSERT INTO telemetry_state(key, value) VALUES (?, ?)"
+ " ON CONFLICT(key) DO UPDATE SET value = excluded.value",
+ (state_key, _compact_json(new_state)),
+ )
+
def recorded_milestones(self) -> frozenset[str]:
with self._connection() as connection:
rows = connection.execute(
diff --git a/hermes_cli/observability/shared_metrics_contract.py b/hermes_cli/observability/shared_metrics_contract.py
index 101a1cfb812..5ef9870f468 100644
--- a/hermes_cli/observability/shared_metrics_contract.py
+++ b/hermes_cli/observability/shared_metrics_contract.py
@@ -80,6 +80,14 @@ CONTEXT_PEAK_METRIC = "hermes.context_peak.count"
# ---- end v4 model ----
# ---- v4 install ----
STARTUP_LATENCY_METRIC = "hermes.startup.latency"
+# ---- v5 engagement ----
+# Not a counter: one attended turn's serving model, folded into the local daily engagement rollup.
+ENGAGEMENT_TURN_MARK = "hermes.engagement.turn"
+ENGAGEMENT_DAY_METRIC = "hermes.engagement.day.count"
+ENGAGEMENT_SURFACE_METRIC = "hermes.engagement.surface_day.count"
+MODEL_SWITCH_AFTER_MARK = "hermes.model_switch_after"
+MODEL_SWITCH_AFTER_METRIC = "hermes.model_switch_after.count"
+# ---- end v5 engagement ----
MODEL_IDENTIFIER_MAX_LENGTH = 256
PROVIDER_IDENTIFIER_MAX_LENGTH = 64
_METRIC_IDENTIFIER_CHARACTERS = frozenset("abcdefghijklmnopqrstuvwxyz0123456789._:/@+-")
@@ -296,6 +304,23 @@ _INSTALL_V4_SNAPSHOT_DIMENSIONS = {
"ram_bucket": RAM_BUCKETS, "release_channel": RELEASE_CHANNELS, "version_age_bucket": VERSION_AGE_BUCKETS,
}
+# ---- v5 engagement ----
+ENGAGEMENT_SURFACES = frozenset({"acp", "cli", "cron", "desktop", "gateway", "tui"})
+ACTIVE_MINUTES_BUCKETS = frozenset({"0", "lt_5m", "5m_to_30m", "30m_to_2h", "2h_to_6h", "gte_6h"})
+SURFACES_USED_BUCKETS = frozenset({"0", "1", "2", "3", "gte_4"})
+TURNS_BEFORE_SWITCH_BUCKETS = frozenset({"1", "2_to_3", "4_to_10", "11_to_30", "gte_31"})
+# SIZE_BUCKETS plus a longer tail: agentic conversations run to thousands of messages.
+LONG_SIZE_BUCKETS = SIZE_BUCKETS | frozenset({"251_to_1000", "gte_1001"})
+_LONG_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"), (1001, "251_to_1000"),
+)
+
+
+def long_size_bucket(count: int) -> str:
+ return _bucket(max(0, int(count)), _LONG_SIZE_THRESHOLDS, "gte_1001")
+# ---- end v5 engagement ----
+
# ---- v4 reliability ----
UPDATE_RUN_MARK = UPDATE_RUN_METRIC = "hermes.update.run"
UPDATE_STAGE_MARK = UPDATE_STAGE_METRIC = "hermes.update.stage"
@@ -628,6 +653,14 @@ _COUNTER_DIMENSION_VALUES: dict[str, dict[str, frozenset[str]]] = {
TOOL_ENABLED_UNUSED_METRIC: {"toolset": TOOLSET_NAMES, "used": YES_NO},
CACHE_BREAK_METRIC: {"cause": CACHE_BREAK_CAUSES},
# ---- end v5 efficiency ----
+ # ---- v5 engagement ----
+ ENGAGEMENT_DAY_METRIC: {
+ "active_minutes_bucket": ACTIVE_MINUTES_BUCKETS, "active_profile_count_bucket": SIZE_BUCKETS,
+ "surfaces_used_count": SURFACES_USED_BUCKETS,
+ },
+ ENGAGEMENT_SURFACE_METRIC: {"active_minutes_bucket": ACTIVE_MINUTES_BUCKETS, "surface": ENGAGEMENT_SURFACES},
+ MODEL_SWITCH_AFTER_METRIC: {"turns_before_switch_bucket": TURNS_BEFORE_SWITCH_BUCKETS},
+ # ---- end v5 engagement ----
}
_MODEL_ROUTE_MAX_LENGTHS = {
"model": MODEL_IDENTIFIER_MAX_LENGTH, "provider": PROVIDER_IDENTIFIER_MAX_LENGTH,
@@ -655,7 +688,20 @@ _IDENTIFIER_FIELDS: dict[str, dict[str, int]] = {
WASTED_TOKENS_METRIC: _MODEL_ROUTE_MAX_LENGTHS,
CACHE_BREAK_METRIC: _MODEL_ROUTE_MAX_LENGTHS,
# ---- end v5 efficiency ----
+ # ---- v5 engagement ----
+ ENGAGEMENT_DAY_METRIC: {
+ "primary_model": MODEL_IDENTIFIER_MAX_LENGTH, "primary_provider": PROVIDER_IDENTIFIER_MAX_LENGTH,
+ },
+ MODEL_SWITCH_AFTER_METRIC: _MODEL_ROUTE_MAX_LENGTHS,
+ # ---- end v5 engagement ----
}
+# ---- v5 engagement ----
+# Conversation volume on the session row: new fields, so rows recorded before them still package.
+SESSION_VOLUME_DIMENSIONS = dict.fromkeys(
+ ("message_count_bucket", "model_call_count_bucket", "tool_call_count_bucket"), LONG_SIZE_BUCKETS,
+)
+_COUNTER_DIMENSION_VALUES[SESSION_METRIC] = {**_COUNTER_DIMENSION_VALUES[SESSION_METRIC], **SESSION_VOLUME_DIMENSIONS}
+# ---- end v5 engagement ----
# metric -> closed dimension field set
_METRIC_FIELDS: dict[str, frozenset[str]] = {
name: frozenset(contract) | frozenset(_IDENTIFIER_FIELDS.get(name, ()))
@@ -677,6 +723,9 @@ _LEGACY_METRIC_FIELDS: dict[str, tuple[frozenset[str], ...]] = {
_METRIC_FIELDS[INSTALL_SNAPSHOT_METRIC] - set(_INSTALL_V4_SNAPSHOT_DIMENSIONS),
),
}
+# ---- v5 engagement ----
+_LEGACY_METRIC_FIELDS[SESSION_METRIC] = (_METRIC_FIELDS[SESSION_METRIC] - set(SESSION_VOLUME_DIMENSIONS),)
+# ---- end v5 engagement ----
COUNTER_METRICS = frozenset(_METRIC_FIELDS) - {LEGACY_MODEL_CALL_METRIC}
# Counters whose value is a summed quantity rather than an event count.
SUM_METRICS = frozenset({MODEL_TOKENS_METRIC})
@@ -716,6 +765,9 @@ _DECISION_MARK_METRICS = {
TOOL_OUTPUT_TRUNCATION_MARK: TOOL_OUTPUT_TRUNCATION_METRIC, TOOL_OVERHEAD_MARK: TOOL_OVERHEAD_METRIC,
TOOL_ENABLED_UNUSED_MARK: TOOL_ENABLED_UNUSED_METRIC, CACHE_BREAK_MARK: CACHE_BREAK_METRIC,
# ---- end v5 efficiency ----
+ # ---- v5 engagement ----
+ MODEL_SWITCH_AFTER_MARK: MODEL_SWITCH_AFTER_METRIC,
+ # ---- end v5 engagement ----
}
diff --git a/hermes_cli/observability/shared_metrics_engagement.py b/hermes_cli/observability/shared_metrics_engagement.py
new file mode 100644
index 00000000000..ed749dad9c0
--- /dev/null
+++ b/hermes_cli/observability/shared_metrics_engagement.py
@@ -0,0 +1,307 @@
+"""Daily engagement rollup, per-conversation session tally and turns-before-switch.
+
+Engagement is accumulated locally per UTC day in the profile's metrics store and emitted once the
+day closes (the first interaction of a later day): one ``hermes.engagement.surface_day.count`` row
+per surface used, and one ``hermes.engagement.day.count`` row with the day's total active time, how
+many surfaces it touched and the model that served most attended turns. Active time is the sum of
+the gaps between consecutive interactions (a turn starting or ending), each capped at
+``IDLE_CAP_MS``. Days-active-per-week and next-day/next-week return by model are derived
+server-side from these daily rows and the package ``install_id``: nothing here keeps a weekly
+window or any identifier of its own.
+
+The day row also carries ``active_profile_count_bucket``: how many distinct profiles of this host
+had a user turn that UTC day. Every profile's interactions are folded into ONE host accumulator,
+the root (default) profile's day state, as opaque local hashes of the profile home (a set, so a
+profile is counted once whichever process or multiplexed runtime served it). Only the root
+profile's day row reports the count; every other profile's row carries ``0`` so no row claims the
+host total twice. When the root profile has collection off, nothing is written to its store and
+the count is not reported.
+
+Only closed enums, buckets, catalog-sanitized provider/model names and profile hashes are stored
+in the state row; the hashes never leave it.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import threading
+import time
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Callable
+
+from . import shared_metrics_contract as contract
+
+# A gap longer than this is idle time: it counts only up to the cap.
+IDLE_CAP_MS = 5 * 60_000
+STATE_KEY = "engagement_day_state"
+_MINUTE_MS = 60_000
+_ACTIVE_THRESHOLDS = (
+ (5 * _MINUTE_MS, "lt_5m"), (30 * _MINUTE_MS, "5m_to_30m"), (120 * _MINUTE_MS, "30m_to_2h"),
+ (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"}
+_INTERACTION_METRICS = frozenset({contract.TASK_STARTED_METRIC, contract.TASK_FINISHED_METRIC})
+_ALL = "*"
+
+# Test / live-probe seam: wall clock in epoch seconds.
+_now: Callable[[], float] = time.time
+
+
+def active_minutes_bucket(active_ms: int) -> str:
+ return "0" if active_ms <= 0 else contract._bucket(active_ms, _ACTIVE_THRESHOLDS, "gte_6h")
+
+
+def surfaces_used_bucket(count: int) -> str:
+ return str(count) if count < 4 else "gte_4"
+
+
+def turns_before_switch_bucket(turns: int) -> str:
+ return contract._bucket(turns, _SWITCH_THRESHOLDS, "gte_31")
+
+
+# ---- producer side (relay subscriber) ------------------------------------------------------------
+
+def interaction_surface(classified: list[tuple[str, dict, int]]) -> str | None:
+ """The engagement surface of a task start/end counter, else 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 None
+ return None
+
+
+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):
+ return None
+ if contract._event_text(event, "name") != contract.ENGAGEMENT_TURN_MARK:
+ return None
+ data = getattr(event, "data", None)
+ if not isinstance(data, dict) or set(data) != {"model", "provider"}:
+ return None
+ limits = contract._MODEL_ROUTE_MAX_LENGTHS
+ route = tuple(data[k] for k in ("provider", "model"))
+ if not all(isinstance(v, str) and v == contract._metric_identifier(v, max_length=limits[k])
+ for k, v in zip(("provider", "model"), route)):
+ return None
+ return route # type: ignore[return-value]
+
+
+def record(store: Any, resource: dict[str, str], *, surface: str | None, route: tuple[str, str] | None) -> None:
+ now_ms = int(_now() * 1000)
+ profile_home = Path(store.database_path).parent.parent.parent
+ root_home = _root_home(profile_home)
+ owner = root_home == profile_home
+ profile = _profile_hash(profile_home) if surface is not None else None
+ store.update_rollup_state(STATE_KEY, lambda state: apply(
+ state, now_ms=now_ms, resource=resource, surface=surface, route=route,
+ profile=profile if owner else None, owner=owner,
+ ))
+ if profile is not None and not owner and _collects(root_home):
+ _root_store(root_home).update_rollup_state(STATE_KEY, lambda state: apply(
+ state, now_ms=now_ms, resource=resource, profile=profile, owner=True,
+ ))
+
+
+def _root_home(profile_home: Path) -> Path:
+ from hermes_constants import get_default_hermes_root
+
+ try:
+ return get_default_hermes_root(home=profile_home).resolve()
+ except Exception:
+ return profile_home.resolve()
+
+
+def _profile_hash(profile_home: Path) -> str:
+ return hashlib.sha256(str(profile_home.resolve()).encode()).hexdigest()[:16]
+
+
+def _collects(home: Path) -> bool:
+ """The root profile's own collection consent (read-only; never touches its runtime)."""
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+
+ token = set_hermes_home_override(str(home))
+ try:
+ from hermes_cli.config import read_raw_config_readonly
+
+ config: Any = read_raw_config_readonly() or {}
+ except Exception:
+ return False
+ finally:
+ reset_hermes_home_override(token)
+ for key in ("telemetry", "shared_metrics"):
+ config = config.get(key) if isinstance(config, dict) else None
+ return isinstance(config, dict) and config.get("enabled") is True
+
+
+_root_stores: dict[Path, Any] = {}
+_root_stores_lock = threading.Lock()
+
+
+def _root_store(home: Path) -> Any:
+ from .shared_metrics import SharedMetricsStore
+
+ with _root_stores_lock:
+ if home not in _root_stores:
+ root = home / "telemetry" / "shared_metrics"
+ _root_stores[home] = SharedMetricsStore(root / "metrics.sqlite3", root / "outbox")
+ return _root_stores[home]
+
+
+# ---- the rollup (pure) ---------------------------------------------------------------------------
+
+def _utc_day(now_ms: int) -> str:
+ return datetime.fromtimestamp(now_ms / 1000, tz=timezone.utc).date().isoformat()
+
+
+def _fresh(day: str, resource: dict[str, str], owner: bool) -> dict[str, Any]:
+ return {"day": day, "resource": resource, "surfaces": {}, "models": {}, "profiles": [], "owner": owner}
+
+
+def _valid_state(state: Any) -> bool:
+ return (
+ isinstance(state, dict) and isinstance(state.get("day"), str)
+ and isinstance(state.get("surfaces"), dict) and isinstance(state.get("models"), dict)
+ )
+
+
+def apply(
+ state: dict[str, Any] | None, *, now_ms: int, resource: dict[str, str],
+ surface: str | None = None, route: tuple[str, str] | None = None, profile: str | None = None,
+ owner: bool = False,
+) -> tuple[dict[str, Any], list[tuple[str, dict, dict, str]]]:
+ """Fold one interaction (``surface``), attended turn (``route``) and/or a profile's user turn
+ (``profile``, host accumulator only) into the day's state; close the stored day first when the
+ clock has moved past it."""
+ today, rows = _utc_day(now_ms), []
+ if state is not None and not _valid_state(state):
+ state = None
+ if state is not None and state["day"] != today:
+ # A day behind the clock closes; a day ahead of it (clock correction) is dropped unemitted.
+ if state["day"] < today:
+ rows = close_day(state)
+ state = None
+ state = state or _fresh(today, resource, owner)
+ state["owner"] = owner
+ profiles = state.setdefault("profiles", [])
+ if profile is not None and isinstance(profiles, list) and profile not in profiles:
+ profiles.append(profile)
+ if surface in contract.ENGAGEMENT_SURFACES:
+ for stream in (surface, _ALL):
+ active_ms, last_ms = state["surfaces"].get(stream) or (0, None)
+ if isinstance(last_ms, int):
+ active_ms += min(max(0, now_ms - last_ms), IDLE_CAP_MS)
+ state["surfaces"][stream] = [active_ms, max(now_ms, last_ms or 0)]
+ if route is not None:
+ key = " ".join(route)
+ state["models"][key] = int(state["models"].get(key, 0)) + 1
+ return state, rows
+
+
+def _primary(models: dict[str, Any]) -> tuple[str, str]:
+ counted = [(int(n), key) for key, n in models.items() if isinstance(n, int) and key.count(" ") == 1]
+ if not counted:
+ return "none", "none"
+ provider, model = max(counted)[1].split(" ")
+ return provider, model
+
+
+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)."""
+ 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 None
+ active_profiles = len(profiles) if isinstance(profiles, list) else 0
+ if not surfaces and not state["models"] and not active_profiles:
+ return []
+ rows = [
+ (contract.ENGAGEMENT_SURFACE_METRIC,
+ {"active_minutes_bucket": active_minutes_bucket(int(v[0])), "surface": name}, resource, day)
+ for name, v in sorted(surfaces.items())
+ ]
+ provider, model = _primary(state["models"])
+ rows.append((contract.ENGAGEMENT_DAY_METRIC, {
+ "active_minutes_bucket": active_minutes_bucket(int((streams.get(_ALL) or [0])[0])),
+ "active_profile_count_bucket": contract.size_bucket(active_profiles),
+ "primary_model": model, "primary_provider": provider,
+ "surfaces_used_count": surfaces_used_bucket(len(surfaces)),
+ }, resource, day))
+ return rows
+
+
+# ---- per-conversation state kept by the relay runtime -------------------------------------------
+
+@dataclass
+class RouteRun:
+ """Consecutive turns the conversation's current model served since the last /model switch."""
+
+ route: dict[str, str] | None = None
+ turns: int = 0
+
+ def observe(self, route: dict[str, str]) -> None:
+ if route == self.route:
+ self.turns += 1
+ else:
+ self.route, self.turns = route, 1
+
+ def take(self) -> tuple[dict[str, str], int] | None:
+ """The model being left and its turn count; resets (the next model starts from zero)."""
+ taken = (self.route, self.turns) if self.route is not None and self.turns else None
+ self.route, self.turns = None, 0
+ return taken
+
+
+def switch_after_fields(route: dict[str, str], turns: int) -> dict[str, str]:
+ return {**route, "turns_before_switch_bucket": turns_before_switch_bucket(turns)}
+
+
+@dataclass
+class SessionTally:
+ """A session summary that merges the segments compression rotation splits one conversation into."""
+
+ start_fields: dict[str, str] | None = None
+ turns: int = 0
+ failed_turns: int = 0
+ last_outcome: str = "unknown"
+ first_turn_ns: int = 0
+ last_turn_ns: int = 0
+ model_calls: int = 0
+ tool_calls: int = 0
+ replies: int = 0
+
+ def absorb(self, other: SessionTally) -> None:
+ if not other.turns:
+ return
+ if not self.turns or other.first_turn_ns < self.first_turn_ns:
+ self.start_fields, self.first_turn_ns = other.start_fields, other.first_turn_ns
+ if other.last_turn_ns >= self.last_turn_ns:
+ self.last_outcome, self.last_turn_ns = other.last_outcome, other.last_turn_ns
+ self.turns += other.turns
+ self.failed_turns += other.failed_turns
+ self.model_calls += other.model_calls
+ self.tool_calls += other.tool_calls
+ self.replies += other.replies
+
+ def fields(self) -> dict[str, str] | None:
+ if not self.turns or self.start_fields is None:
+ return None
+ from .shared_metrics_fields import session_fields
+
+ return {
+ **session_fields(
+ self.start_fields, turns=self.turns, failed_turns=self.failed_turns, last_outcome=self.last_outcome,
+ active_ms=max(0, self.last_turn_ns - self.first_turn_ns) // 1_000_000,
+ ),
+ # Messages the conversation added: each user turn, each primary-model reply, each tool result.
+ "message_count_bucket": contract.long_size_bucket(self.turns + self.replies + self.tool_calls),
+ "model_call_count_bucket": contract.long_size_bucket(self.model_calls),
+ "tool_call_count_bucket": contract.long_size_bucket(self.tool_calls),
+ }
diff --git a/hermes_cli/observability/shared_metrics_events.py b/hermes_cli/observability/shared_metrics_events.py
index 0fceee2b772..514ee6b19f7 100644
--- a/hermes_cli/observability/shared_metrics_events.py
+++ b/hermes_cli/observability/shared_metrics_events.py
@@ -97,8 +97,10 @@ def record_gateway_slash_command(event: Any) -> None:
def record_model_switch(
*, from_provider: str | None, to_provider: str | None, surface: str, from_model: str | None = None,
+ session_id: str | None = None,
) -> None:
- """``from_model`` also counts the switch as friction against the model the user left."""
+ """``from_model`` also counts the switch as friction against the model the user left;
+ ``session_id`` (the switched session) also counts how many turns that model served first."""
_emit(
contract.MODEL_SWITCH_MARK, fields_.model_switch_fields,
from_provider=from_provider, to_provider=to_provider, surface=surface,
@@ -107,6 +109,13 @@ def record_model_switch(
from .shared_metrics_model import record_model_friction
record_model_friction("switch_away", provider=from_provider, model=from_model)
+ if session_id:
+ try:
+ from .relay_shared_metrics import record_model_switch_after
+
+ record_model_switch_after(str(session_id))
+ except Exception:
+ logger.debug("Shared-metrics model_switch_after not recorded", exc_info=True)
def record_fallback(*, from_provider: str | None, to_provider: str | None, reason: Any) -> None:
diff --git a/hermes_cli/observability/shared_metrics_gateway.py b/hermes_cli/observability/shared_metrics_gateway.py
index 2629035b715..c336df037cd 100644
--- a/hermes_cli/observability/shared_metrics_gateway.py
+++ b/hermes_cli/observability/shared_metrics_gateway.py
@@ -229,21 +229,25 @@ def records_delivery(send: Callable[..., Any]) -> Callable[..., Any]:
@functools.wraps(send)
async def wrapper(self, *args: Any, **kwargs: Any) -> Any:
+ chat_id = kwargs.get("chat_id", args[0] if args else None)
try:
result = await send(self, *args, **kwargs)
except Exception as exc:
- _submit(_record_delivery, self, exc=exc)
+ _submit(_record_delivery, self, exc=exc, chat_id=chat_id)
raise
if isinstance(getattr(result, "success", None), bool):
- _submit(_record_delivery, self, result)
+ _submit(_record_delivery, self, result, chat_id=chat_id)
return result
return wrapper
-def _record_delivery(adapter: Any, result: Any = None, *, exc: BaseException | None = None) -> None:
+def _record_delivery(
+ adapter: Any, result: Any = None, *, exc: BaseException | None = None, chat_id: Any = None,
+) -> None:
failure_class = "none" if exc is None and result.success else delivery_failure_class(result, exc)
- _emit("PLATFORM_DELIVERY_MARK", delivery_fields, platform=adapter, failure_class=failure_class)
+ _emit("PLATFORM_DELIVERY_MARK", delivery_fields, platform=_source_platform(adapter, chat_id),
+ failure_class=failure_class)
def stops_reply_clock(send_or_edit: Callable[..., Any]) -> Callable[..., Any]:
@@ -271,6 +275,19 @@ _reply_lock = threading.Lock()
_FRONTING_PLATFORMS = frozenset({"relay"})
+def _source_platform(adapter: Any, chat_id: Any) -> Any:
+ """The platform a fronting adapter's chat really lives on (the relay connector learned it from
+ the inbound, else its primary platform); the adapter's own platform otherwise. Read-only."""
+ platform = getattr(adapter, "platform", None)
+ if str(getattr(platform, "value", platform) or "") not in _FRONTING_PLATFORMS or chat_id in (None, ""):
+ return adapter
+ resolve = getattr(adapter, "_chat_platform", None)
+ try:
+ return (resolve(str(chat_id)) if callable(resolve) else None) or adapter
+ except Exception:
+ return adapter
+
+
def _clock_key(platform: Any, chat_id: Any) -> tuple[str, str] | None:
value = str(getattr(platform, "value", platform) or "")
return (value, str(chat_id)) if value and chat_id not in (None, "") else None
@@ -297,15 +314,22 @@ def stop_reply_clock(adapter: Any, chat_id: Any, result: Any = None) -> None:
if key is None or (result is not None and getattr(result, "success", False) is not True):
return
with _reply_lock:
- started = _reply_clocks.pop(key, None)
+ started, started_key = _reply_clocks.pop(key, None), key
if started is None and key[0] in _FRONTING_PLATFORMS:
fronted = [k for k in _reply_clocks if k[1] == key[1]]
- started = _reply_clocks.pop(fronted[0]) if len(fronted) == 1 else None
+ started_key = fronted[0] if len(fronted) == 1 else key
+ started = _reply_clocks.pop(started_key) if len(fronted) == 1 else None
# A turn that ended without a reply leaves its clock behind; an unrelated send hours later
# must not be read as that turn's reply.
if started is not None and time.monotonic() - started[0] <= _REPLY_CLOCK_MAX_AGE:
- _submit(_in_home, started[1], _emit, "REPLY_LATENCY_MARK", reply_latency_fields,
- platform=adapter, seconds=time.monotonic() - started[0])
+ # Labelled by the platform the message came in on, not the connector that carried the reply.
+ platform = started_key[0] if started_key[0] not in _FRONTING_PLATFORMS else None
+ _submit(_in_home, started[1], _emit_reply_latency, adapter, chat_id, platform, time.monotonic() - started[0])
+
+
+def _emit_reply_latency(adapter: Any, chat_id: Any, platform: Any, seconds: float) -> None:
+ _emit("REPLY_LATENCY_MARK", reply_latency_fields,
+ platform=platform or _source_platform(adapter, chat_id), seconds=seconds)
def reply_latency_fields(*, platform: Any, seconds: float) -> dict[str, str]:
diff --git a/hermes_cli/observability/shared_metrics_subscriber.py b/hermes_cli/observability/shared_metrics_subscriber.py
index c4a6a06ba8d..d7f702e93d8 100644
--- a/hermes_cli/observability/shared_metrics_subscriber.py
+++ b/hermes_cli/observability/shared_metrics_subscriber.py
@@ -11,6 +11,7 @@ from agent.relay_runtime import RUNTIME_INSTANCE_KEY
from hermes_cli.config import detect_install_method
from hermes_constants import get_hermes_home
+from . import shared_metrics_engagement as engagement
from .shared_metrics import SharedMetricsStore
from .shared_metrics_fields import milestones_for
from .shared_metrics_contract import (
@@ -102,6 +103,19 @@ class SharedMetricsSubscriber:
self.store.record_milestone(milestone, age, self._client_resource)
self._milestones_done.add(milestone)
+ def _record_engagement(self, event: Any, classified: list[tuple[str, dict, int]]) -> None:
+ """Fold a turn start/end or an attended turn's model into the local daily engagement rollup."""
+ surface, route = engagement.interaction_surface(classified), engagement.turn_route(event)
+ if surface is None and route is None:
+ return
+ with self._lock:
+ if not self._active:
+ return
+ try:
+ engagement.record(self.store, self._client_resource, surface=surface, route=route)
+ except Exception:
+ logger.warning("Unable to update the Hermes engagement rollup", exc_info=True)
+
def take_saved(self, ticket: str) -> int:
"""How many events carrying ``ticket`` settled without a store error (and forget the ticket)."""
with self._lock:
@@ -117,7 +131,9 @@ class SharedMetricsSubscriber:
return
ticket = metadata.get(COMMIT_TICKET_KEY) if isinstance(metadata, dict) else None
saved = True # a row the contract rejects is settled too: no retry can change that
- for metric_name, dimensions, amount in self._classify(event):
+ classified = self._classify(event)
+ self._record_engagement(event, classified)
+ for metric_name, dimensions, amount in classified:
with self._lock:
if not self._active:
return
diff --git a/tests/gateway/test_platform_shared_metrics.py b/tests/gateway/test_platform_shared_metrics.py
index 73f5506e44f..a83f031c552 100644
--- a/tests/gateway/test_platform_shared_metrics.py
+++ b/tests/gateway/test_platform_shared_metrics.py
@@ -120,7 +120,8 @@ def test_a_relay_delivered_turn_stops_the_clock_its_inbound_started(rows):
source=SimpleNamespace(platform=Platform.SLACK, chat_id="C2", thread_id=None))
smg.start_reply_clock(event.source)
asyncio.run(relay.send_final_ledgered(event, "k", "final answer", {}, reply_to=None))
- assert rows("hermes.gateway.reply_latency") == [{"first_response_bucket": "lt_2s", "platform": "relay"}] * 2
+ assert rows("hermes.gateway.reply_latency") == [
+ {"first_response_bucket": "lt_2s", "platform": "discord"}, {"first_response_bucket": "lt_2s", "platform": "slack"}]
assert not smg._reply_clocks
diff --git a/tests/gateway/test_relay_source_platform_metrics.py b/tests/gateway/test_relay_source_platform_metrics.py
new file mode 100644
index 00000000000..9091c8d0d5e
--- /dev/null
+++ b/tests/gateway/test_relay_source_platform_metrics.py
@@ -0,0 +1,67 @@
+"""Replies the relay connector carries are labelled with the platform the conversation lives on."""
+
+import asyncio
+from types import SimpleNamespace
+
+import pytest
+
+from gateway.config import Platform, PlatformConfig
+from gateway.platforms.event import MessageEvent, MessageType
+from gateway.relay.adapter import RelayAdapter
+from gateway.session import SessionSource
+from gateway.stream_consumer import GatewayStreamConsumer, StreamConsumerConfig
+from hermes_cli.observability import shared_metrics_gateway as smg
+from tests.gateway.relay.test_relay_adapter import _CaptureTransport, make_desc
+from tests.gateway.test_platform_shared_metrics import rows # noqa: F401 - fixture
+
+
+def _relay(platform="telegram"):
+ return RelayAdapter(PlatformConfig(), make_desc(platform=platform), transport=_CaptureTransport())
+
+
+def _inbound(adapter, platform, chat_id):
+ event = MessageEvent(text="hi", message_type=MessageType.TEXT, message_id=f"in-{chat_id}",
+ source=SessionSource(platform=platform, chat_id=chat_id, chat_type="dm", user_id="u1"))
+ adapter._capture_scope(event)
+ return event
+
+
+def test_multiplatform_relay_replies_are_labelled_by_the_inbound_platform(rows):
+ relay = _relay()
+ discord = _inbound(relay, Platform.DISCORD, "c1")
+ slack = _inbound(relay, Platform.SLACK, "c2")
+ smg.start_reply_clock(discord.source)
+ assert asyncio.run(GatewayStreamConsumer(relay, "c1", StreamConsumerConfig(cursor=""))._send_or_edit("chunk"))
+ smg.start_reply_clock(slack.source)
+ asyncio.run(relay.send_final_ledgered(slack, "k", "final answer", {}, reply_to=None))
+
+ assert rows("hermes.gateway.reply_latency") == [
+ {"first_response_bucket": "lt_2s", "platform": "discord"},
+ {"first_response_bucket": "lt_2s", "platform": "slack"},
+ ]
+ # Streamed chunks send directly; the final reply is the ledgered, counted delivery.
+ assert rows("hermes.platform.delivery") == [{"failure_class": "none", "outcome": "sent", "platform": "slack"}]
+
+
+def test_single_platform_relay_inbound_is_labelled_by_the_connector_platform(rows):
+ """An inbound that only says 'relay' resolves to the platform the connector fronts."""
+ relay = _relay("discord")
+ event = _inbound(relay, Platform.RELAY, "c9")
+ smg.start_reply_clock(event.source)
+ asyncio.run(relay.send_final_ledgered(event, "k", "final answer", {}, reply_to=None))
+ assert rows("hermes.gateway.reply_latency") == [{"first_response_bucket": "lt_2s", "platform": "discord"}]
+ assert rows("hermes.platform.delivery") == [{"failure_class": "none", "outcome": "sent", "platform": "discord"}]
+
+
[email protected]("chat_platform", [None, RuntimeError("descriptor gone")])
+def test_an_unresolvable_relay_chat_keeps_the_relay_label(rows, chat_platform):
+ class _Front:
+ platform = Platform.RELAY
+
+ def _chat_platform(self, chat_id):
+ if isinstance(chat_platform, BaseException):
+ raise chat_platform
+ return chat_platform
+
+ smg._record_delivery(_Front(), SimpleNamespace(success=True), chat_id="c1")
+ assert rows("hermes.platform.delivery") == [{"failure_class": "none", "outcome": "sent", "platform": "relay"}]
diff --git a/tests/hermes_cli/test_shared_metrics_engagement.py b/tests/hermes_cli/test_shared_metrics_engagement.py
new file mode 100644
index 00000000000..ca87050a1e6
--- /dev/null
+++ b/tests/hermes_cli/test_shared_metrics_engagement.py
@@ -0,0 +1,188 @@
+"""Engagement invariants: the daily rollup reports each closed day once per profile, a compressed
+conversation is one session row with its whole volume, and turns-before-switch names the model left."""
+
+from __future__ import annotations
+
+import json
+from datetime import datetime, timezone
+
+import pytest
+
+from agent.portal_tags import reset_conversation_context, set_conversation_context
+from hermes_cli import lifecycle
+from hermes_cli.observability import relay_shared_metrics
+from hermes_cli.observability import shared_metrics_engagement as engagement
+from hermes_cli.observability.shared_metrics import SharedMetricsStore
+from tests.hermes_cli.test_relay_shared_metrics_runtime import ( # noqa: F401 - fixture
+ _stored_values,
+ direct_runtime,
+)
+
+PUBLIC = "anthropic/claude-sonnet-4"
+OTHER = "openai/gpt-5"
+DAY1 = datetime(2026, 9, 27, 9, 0, tzinfo=timezone.utc).timestamp()
+
+
+def _flush() -> None:
+ for runtime in list(relay_shared_metrics._RUNTIMES.values()):
+ runtime.relay.subscribers.flush()
+
+
+def _turn(session_id, task_id, *, platform="cli", model=PUBLIC, tools=0, clock=None, at=None, took=0.0):
+ base = {"session_id": session_id, "task_id": task_id, "provider": "openrouter", "model": model}
+ if clock is not None:
+ clock["now"] = at
+ lifecycle.invoke_hook("pre_llm_call", **base, platform=platform)
+ lifecycle.invoke_hook("pre_api_request", **base, api_request_id=f"{task_id}-r")
+ lifecycle.invoke_hook("post_api_request", **base, api_request_id=f"{task_id}-r",
+ usage={"prompt_tokens": 1_000, "output_tokens": 5}, context_length=200_000)
+ for n in range(tools):
+ call = {**base, "tool_call_id": f"{task_id}-c{n}", "tool_name": "todo", "turn_id": ""}
+ lifecycle.invoke_hook("pre_tool_call", **call)
+ lifecycle.invoke_hook("post_tool_call", **call, status="success")
+ if clock is not None:
+ clock["now"] = at + took
+ relay_shared_metrics.finish_task_run(session_id=session_id, task_id=task_id, platform=platform,
+ result={"completed": True})
+
+
+def clock(monkeypatch):
+ state = {"now": DAY1}
+ monkeypatch.setattr(engagement, "_now", lambda: state["now"])
+ return state
+
+
+def _rows(tmp_path, metric):
+ return sorted((json.dumps(d, sort_keys=True), v) for d, v in _stored_values(tmp_path, metric))
+
+
+def test_a_closed_day_reports_active_time_surfaces_and_primary_model_once(direct_runtime, tmp_path, clock):
+ """Two surfaces on day 1 (gaps capped at 5 minutes); nothing is reported until the day closes,
+ then exactly once, dated to that day, however many processes of the profile see the next day."""
+ _turn("cli-1", "t1", clock=clock, at=DAY1, took=60) # cli: 1 min
+ _turn("cli-1", "t2", clock=clock, at=DAY1 + 180, took=3600) # +2 min gap, +5 min capped run
+ _turn("gw-1", "g1", platform="telegram", model=OTHER, clock=clock, at=DAY1 + 7200, took=30)
+ lifecycle.finalize_session(session_id="cli-1")
+ lifecycle.finalize_session(session_id="gw-1")
+ _flush()
+ assert not _stored_values(tmp_path, "hermes.engagement.day.count"), "emitted before the day closed"
+
+ root = tmp_path / "hermes-home" / "telemetry" / "shared_metrics"
+ other_process = SharedMetricsStore(root / "metrics.sqlite3", root / "outbox")
+ resource = {"architecture": "x86_64", "hermes_version": "0.0.0", "install_method": "git", "os_family": "linux"}
+ clock["now"] = DAY1 + 86_400
+ engagement.record(other_process, resource, surface="cli", route=None)
+ _turn("cli-2", "t3", clock=clock, at=DAY1 + 86_400 + 5)
+ _flush()
+
+ assert _rows(tmp_path, "hermes.engagement.surface_day.count") == sorted([
+ (json.dumps({"active_minutes_bucket": "5m_to_30m", "surface": "cli"}, sort_keys=True), 1),
+ (json.dumps({"active_minutes_bucket": "lt_5m", "surface": "gateway"}, sort_keys=True), 1),
+ ])
+ assert _stored_values(tmp_path, "hermes.engagement.day.count") == [(
+ {"active_minutes_bucket": "5m_to_30m", "active_profile_count_bucket": "1", "primary_model": PUBLIC,
+ "primary_provider": "openrouter", "surfaces_used_count": "2"}, 1)]
+ periods = {c["period_start"] for c in other_process.counter_snapshot() if c["metric_name"].startswith("hermes.engagement")}
+ assert periods == {"2026-09-27"}
+
+
+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)
+ clock["now"] = DAY1 + 86_400
+ _turn("s1", "t2", clock=clock, at=DAY1 + 86_400)
+ lifecycle.finalize_session(session_id="s1")
+ assert not (tmp_path / "hermes-home" / "telemetry").exists()
+
+
+def test_a_compressed_conversation_is_one_session_row_with_its_whole_volume(direct_runtime, tmp_path):
+ """Legacy rotating compaction continues s1 as s1c under one conversation root: one session row,
+ turns / API calls / tool calls / messages summed over both segments, whatever the close order."""
+ token = set_conversation_context("s1")
+ try:
+ _turn("s1", "t1", tools=2)
+ _turn("s1", "t2", tools=1)
+ _turn("s1c", "t3", tools=0)
+ finally:
+ reset_conversation_context(token)
+ lifecycle.finalize_session(session_id="s1c")
+ _flush()
+ assert not _stored_values(tmp_path, "hermes.session.count"), "a segment reported on its own"
+ lifecycle.finalize_session(session_id="s1")
+ _flush()
+
+ [(row, value)] = _stored_values(tmp_path, "hermes.session.count")
+ assert value == 1
+ assert {k: row[k] for k in ("turn_count_bucket", "model_call_count_bucket", "tool_call_count_bucket",
+ "message_count_bucket")} == {
+ "turn_count_bucket": "3_to_5", "model_call_count_bucket": "3_to_5",
+ "tool_call_count_bucket": "3_to_5", "message_count_bucket": "6_to_10"}
+
+
+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 (compression
+ segments included); a second switch before any turn on the new model reports nothing."""
+ from hermes_cli.observability.shared_metrics_events import record_model_switch
+
+ token = set_conversation_context("s1")
+ try:
+ _turn("s1", "t1")
+ _turn("s1c", "t2")
+ _turn("s1c", "t3")
+ finally:
+ reset_conversation_context(token)
+ record_model_switch(from_provider="openrouter", to_provider="openrouter", surface="cli",
+ from_model=PUBLIC, session_id="s1c")
+ record_model_switch(from_provider="openrouter", to_provider="openrouter", surface="cli",
+ from_model=OTHER, session_id="s1c")
+ _flush()
+ assert _stored_values(tmp_path, "hermes.model_switch_after.count") == [
+ ({"model": PUBLIC, "provider": "openrouter", "turns_before_switch_bucket": "2_to_3"}, 1)]
+
+
+def _profile_store(home):
+ root = home / "telemetry" / "shared_metrics"
+ return SharedMetricsStore(root / "metrics.sqlite3", root / "outbox")
+
+
+def _day_rows(home):
+ db = home / "telemetry" / "shared_metrics" / "metrics.sqlite3"
+ if not db.exists():
+ return []
+ return [(c["period_start"], c["dimensions"]) for c in _profile_store(home).counter_snapshot()
+ if c["metric_name"] == "hermes.engagement.day.count"]
+
+
[email protected]("root_collects", [True, False])
+def test_active_profiles_are_counted_once_per_host_day_on_the_root_profiles_row(tmp_path, clock, root_collects):
+ """Profiles A -> B -> A on one day (any process, any runtime): the root (default) profile's day
+ row reports 2 distinct active profiles, even though the root itself was idle; the profiles' own
+ rows report 0 so no row claims the host total twice. A root with collection off is untouched."""
+ root = tmp_path / "root"
+ (root / "profiles").mkdir(parents=True)
+ (root / "config.yaml").write_text(f"telemetry:\n shared_metrics:\n enabled: {str(root_collects).lower()}\n")
+ a, b = root / "profiles" / "a", root / "profiles" / "b"
+ resource = {"architecture": "x86_64", "hermes_version": "0.0.0", "install_method": "git", "os_family": "linux"}
+ for home, at in ((a, 0), (b, 60), (a, 120), (a, 86_400)):
+ clock["now"] = DAY1 + at
+ engagement.record(_profile_store(home), resource, surface="cli", route=None)
+
+ zero = {"active_minutes_bucket": "lt_5m", "active_profile_count_bucket": "0", "primary_model": "none",
+ "primary_provider": "none", "surfaces_used_count": "1"}
+ assert _day_rows(a) == [("2026-09-27", zero)]
+ assert _day_rows(b) == [] # B has not seen a later day yet; its row will carry 0 too
+ if root_collects:
+ assert _day_rows(root) == [("2026-09-27", {
+ "active_minutes_bucket": "0", "active_profile_count_bucket": "2", "primary_model": "none",
+ "primary_provider": "none", "surfaces_used_count": "0"})]
+ else:
+ assert not (root / "telemetry").exists()
+
+
[email protected](("count", "bucket"), [(250, "101_to_250"), (251, "251_to_1000"), (1001, "gte_1001")])
+def test_long_conversations_bucket_past_251(count, bucket):
+ from hermes_cli.observability import shared_metrics_contract as contract
+
+ assert contract.long_size_bucket(count) == bucket
+ assert bucket in contract.LONG_SIZE_BUCKETS
diff --git a/tui_gateway/model_switch.py b/tui_gateway/model_switch.py
index 34e4576f4aa..4adbbf447c7 100644
--- a/tui_gateway/model_switch.py
+++ b/tui_gateway/model_switch.py
@@ -365,7 +365,8 @@ def _apply_model_switch(
record_model_switch(
from_provider=_switch_away_provider(agent, explicit_provider, current_provider),
- to_provider=result.target_provider, surface=_session_source(session), from_model=current_model)
+ to_provider=result.target_provider, surface=_session_source(session), from_model=current_model,
+ session_id=getattr(agent, "session_id", None))
return {
"value": result.new_model, "warning": result.warning_message or "",
"confirm_required": False,
diff --git a/website/docs/developer-guide/relay-shared-metrics.md b/website/docs/developer-guide/relay-shared-metrics.md
index 6229188ccab..0cb64a67a73 100644
--- a/website/docs/developer-guide/relay-shared-metrics.md
+++ b/website/docs/developer-guide/relay-shared-metrics.md
@@ -294,7 +294,7 @@ itself ships.
| Metric | Dimensions | Question it answers |
|---|---|---|
-| `hermes.session.count` | entrypoint, surface, platform, turn/failed-turn buckets, active-duration bucket, last outcome | How deep is real usage per surface; do sessions end right after a failure? |
+| `hermes.session.count` | entrypoint, surface, platform, turn/failed-turn buckets, active-duration bucket, last outcome, message / model-call / tool-call count buckets (`0` … `101_to_250`, `251_to_1000`, `gte_1001`) | How deep is real usage per surface; do sessions end right after a failure? One row per conversation: the session ids a compression rotation continues it under merge into one row. Messages are user turns + primary-model replies + tool results; model calls are logical primary API requests (retries excluded). |
| `hermes.install.milestone` | milestone, install age bucket | How long from install to first success, first gateway message, first cron run, first delegation, first created skill, first long session? Recorded once per install. |
| `hermes.setup.completed` | surface (`cli`/`desktop`), provider | Which providers people choose at setup, and on which surface. |
| `hermes.model_tokens.sum` | call role, model, provider, auxiliary task, token type | Token volume per model/provider, prompt-cache share, and what auxiliary work (compression, titles, vision, ...) costs. The value is a token sum, not an event count. |
@@ -311,6 +311,10 @@ itself ships.
| `hermes.platform.health` | platform, event (`connect_ok`/`connect_failed`/`reconnect`/`disconnect`), error class (`auth`/`network`/`rate_limited`/`config`/`other`) | Which messaging platforms fail to connect or drop, and why. Classified from exception types, HTTP statuses and Hermes's own fatal codes, never error text. |
| `hermes.platform.delivery` | platform, outcome (`sent`/`failed`), failure class (`rate_limited`/`too_long`/`auth`/`network`/`forbidden`/`other`) | How often replies fail to reach the user per platform (one count per logical reply, retries included). |
| `hermes.gateway.reply_latency` | platform, first-response bucket (`lt_2s` … `gte_60s`) | Time from an accepted inbound message to the first visible reply text (stream first chunk or final message). |
+
+Replies the relay connector carries report the platform the conversation lives
+on (the inbound's platform, else the platform the connector fronts), never
+`relay`; `relay` remains only when neither is known.
| `hermes.cron.run` | outcome (`success`/`failed`/`missed`/`skipped`), delivery kind (`local`/`platform`/`webhook`/`none`/`other`), duration bucket | Do scheduled jobs run, fail, get skipped by a gate or overlap, or get missed while Hermes was down. Job names, prompts, schedules and targets are never included. |
| `hermes.startup.latency` | surface (`cli`, `tui`, `desktop_attach`, `gateway_boot`, `serve_boot`), latency bucket (`lt_500ms` … `gte_10s`) | How long each surface takes from launch to usable, so startup regressions show per surface and release. One row per process start: CLI = process start to first rendered prompt (or a `-q` query dispatched; Kanban workers excluded), TUI = Ink process start to gateway ready, Desktop = app start to backend attached, gateway = process start to adapters connected, `hermes serve` = process start to listening. Not counted: a process re-exec'd in place (e.g. `hermes sessions browse` resuming a session) and each dashboard Chat-tab terminal; a TUI/Desktop reconnect to the same backend never re-counts. |
| `hermes.update.run` | kind, outcome, failed_stage, duration_bucket, from_version_age_bucket, apply_mode | Whether updates succeed, how long they take, where they fail, and how stale the version being updated from was. `hermes update` rows are derived from the final update receipt, once per run (`kind` is `desktop` when Desktop's source-checkout hand-off ran it); a run the pre-update interpreter finishes is parked locally with only these fields, only while collection is on, and counted by the next start; Desktop packaged self-updates (`apply_mode=package`) are reported once by the app, after the restart that applies them. |
@@ -367,6 +371,39 @@ the curator, delegated subagents' own turns) is not a user turn.
| `hermes.cache_break.count` | provider, model, cause (`compression`, `model_switch`, `toolset_change`, `system_prompt_rebuild`, `provider_reported_miss`, `cache_expired`) | How often Hermes throws away a warm prompt cache, and why. `compression` is expected; `model_switch`, `toolset_change` (the tool array changed mid-conversation) and `system_prompt_rebuild` (a continuing conversation rebuilt its system prompt instead of replaying the stored bytes) are Hermes-known causes; `provider_reported_miss` is a primary call reading zero cached tokens right after a warm read on the same model with no Hermes-known cause, `cache_expired` the same after at least five idle minutes. A known cause is not counted again as a miss. |
<!-- ---- end v5 efficiency ---- -->
+<!-- ---- v5 engagement ---- -->
+#### Engagement and implicit model satisfaction
+
+| 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. |
+
+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
+minutes. The day's rows are recorded once the day closes, by the first
+interaction on a later day, in one database transaction, so a day is reported
+exactly once per profile however many processes see the rollover; they are
+dated 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
+rules. Days active per week and return by model are derived server-side from
+these daily rows and the existing `install_id`: Hermes keeps no weekly window
+and no identifier beyond `install_id` for them.
+
+`active_profile_count_bucket` counts the distinct profiles of the host with a
+user-owned turn (the interactions above) that UTC day. Every profile folds its turns into one host
+accumulator kept in the root (default) profile's database, as opaque local
+hashes of each profile's home that never leave it, so a profile counts once
+whichever process or multiplexed runtime served it. Only the root profile's
+day row carries the count (it reports a day even when the root itself was
+idle, with `0` active minutes and surfaces); every other profile's row reads
+`0`. When the root profile has collection off, nothing is written to its
+database and the count is not reported.
+<!-- ---- end v5 engagement ---- -->
+
Local state is written under:
```text