Skip to content

The agent that grows with you

fix(telemetry): user-named providers and models never leave the machine; milestones use the owning profile

teknium1ccd1a274e85b
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.py
index 3beb3c8128b..e0fa61a97ac 100644
--- a/agent/conversation_compression.py
+++ b/agent/conversation_compression.py
@@ -1497,27 +1497,9 @@ def _emit_compression_attempt_telemetry(
logger.info(
"context compression attempt telemetry: %s", json.dumps(payload, sort_keys=True, separators=(",", ":"))
)
- _record_compression_metric(agent, commit_status=commit_status, failure_class=failure_class)
+ from hermes_cli.observability.shared_metrics_events import finish_compression_attempt
-
-# Per-thread, not on the compressor or the agent: abort paths restore the compressor snapshot (seed
-# included) before they emit, and a stalled attempt's worker can unwind after its stall-fallback retry
-# began on another thread. An attempt begins and emits on one thread (the pool worker or the caller).
-_attempt_metric = threading.local()
-
-
-def _record_compression_metric(agent: Any, *, commit_status: str, failure_class: str | None) -> None:
- """Count this thread's pending attempt once in shared metrics."""
- pending, _attempt_metric.pending = getattr(_attempt_metric, "pending", None), None
- if not pending:
- return
- from hermes_cli.observability.shared_metrics_events import record_compression
-
- outcome = "success" if commit_status == "committed" else "skipped" if failure_class == "lock_contended" else "failed"
- record_compression(
- trigger=pending["trigger"], outcome=outcome, tokens_before=pending["tokens_before"],
- context_length=getattr(agent.context_compressor, "context_length", None),
- )
+ finish_compression_attempt(commit_status, failure_class, getattr(agent.context_compressor, "context_length", None))
def _existing_system_prompt(agent: Any, system_message: str) -> str:
@@ -4019,10 +4001,9 @@ def _begin_compression_attempt(
trigger = trigger or ("manual" if force else "auto")
with contextlib.suppress(Exception):
agent._compression_attempt_id = attempt_id
- _attempt_metric.pending = {
- "trigger": trigger,
- "tokens_before": approx_tokens or getattr(agent.context_compressor, "last_prompt_tokens", None),
- }
+ from hermes_cli.observability.shared_metrics_events import begin_compression_attempt
+
+ begin_compression_attempt(trigger, approx_tokens or getattr(agent.context_compressor, "last_prompt_tokens", None))
agent.context_compressor._compression_telemetry_seed = {
"attempt_id": attempt_id, "session_id": agent.session_id or "", "trigger_source": trigger,
}
diff --git a/gateway/run_inbound.py b/gateway/run_inbound.py
index 01fdfd59989..638960da4b3 100644
--- a/gateway/run_inbound.py
+++ b/gateway/run_inbound.py
@@ -1314,17 +1314,6 @@ class GatewayInboundMixin:
logger.debug("FIFO orphan rescue pre-claim failed for %s", _quick_key, exc_info=True)
return event, source, is_internal
- @staticmethod
- def _hm_count_slash_command(event: "MessageEvent") -> None:
- """Count a user-typed slash command once: a queued busy-path event re-enters
- ``_handle_message`` when drained, so the event carries the mark."""
- command = event.get_command()
- if not command or getattr(event, "_slash_command_counted", False):
- return
- event._slash_command_counted = True
- from hermes_cli.observability.shared_metrics_events import record_slash_command
- record_slash_command(command=command, surface="gateway")
-
async def _handle_message(self, event: MessageEvent) -> Optional[str]:
"""Handle an incoming message from any platform: auth → command check → running-agent
interrupt → get/create session → build context → run agent → return response."""
@@ -1334,7 +1323,8 @@ class GatewayInboundMixin:
return None
event, source, is_internal = _admitted
if not is_internal:
- self._hm_count_slash_command(event)
+ from hermes_cli.observability.shared_metrics_events import record_gateway_slash_command
+ record_gateway_slash_command(event)
# TERMINAL-DECLINE LATCH TEARDOWN. Deliberately placed AFTER admission,
# not on the adapter's raw inbound: profile routing, the ignored-channel
# guard, plugin hooks and user authorization all reject events above,
diff --git a/gateway/session_recovery.py b/gateway/session_recovery.py
index a466af5a25d..a57b47a36ae 100644
--- a/gateway/session_recovery.py
+++ b/gateway/session_recovery.py
@@ -392,6 +392,10 @@ class SessionRecoveryMixin:
explicit reset boundary (with the specific reason so state.db is auditable, e.g.
``suspended`` vs plain ``session_reset``), then INSERT the new row + routing
peer. Both best-effort: failures are warned and self-healed by the next peer refresh."""
+ if end_session_id:
+ from hermes_cli.observability.relay_shared_metrics import close_session_run
+
+ close_session_run(end_session_id)
if self._db_for_key(session_key) and end_session_id:
self._promote_session_reset(
session_key, end_session_id, end_reason,
diff --git a/hermes_cli/observability/relay_shared_metrics.py b/hermes_cli/observability/relay_shared_metrics.py
index 9a75251e230..4c31c0edfe5 100644
--- a/hermes_cli/observability/relay_shared_metrics.py
+++ b/hermes_cli/observability/relay_shared_metrics.py
@@ -1064,6 +1064,16 @@ def start_task_run(
)
+def close_session_run(session_id: str) -> None:
+ """Emit the summary of a session a surface retired without a finalize hook (gateway
+ auto-reset, idle expiry). Never creates a runtime; unknown ids are a no-op."""
+ if not session_id or not enabled():
+ return
+ runtime = _RUNTIMES.get(relay_runtime.current_profile_key())
+ if isinstance(runtime, _Runtime):
+ runtime._safe(runtime.close_session, {"session_id": session_id})
+
+
def finish_task_run(
*, session_id: str, task_id: str, platform: str,
result: dict[str, Any] | None = None, error: BaseException | None = None,
diff --git a/hermes_cli/observability/shared_metrics_catalog.py b/hermes_cli/observability/shared_metrics_catalog.py
index a8228355c2a..cdbf0578c09 100644
--- a/hermes_cli/observability/shared_metrics_catalog.py
+++ b/hermes_cli/observability/shared_metrics_catalog.py
@@ -77,6 +77,30 @@ def display_languages() -> frozenset[str]:
return _yaml_stems(_REPO_ROOT / "locales")
+def provider_names() -> frozenset[str]:
+ """Provider ids Hermes itself ships (auth registry, overlays, model catalog, aliases)."""
+ from hermes_cli.auth import PROVIDER_REGISTRY
+ from hermes_cli.models import _KNOWN_PROVIDER_NAMES
+ from hermes_cli.providers import ALIASES, HERMES_OVERLAYS
+
+ return frozenset(PROVIDER_REGISTRY) | frozenset(HERMES_OVERLAYS) | frozenset(_KNOWN_PROVIDER_NAMES) | frozenset(ALIASES)
+
+
+def user_named_model_providers() -> frozenset[str]:
+ """Providers whose model ids the user names: custom endpoints and loopback servers."""
+ from urllib.parse import urlparse
+
+ from hermes_cli.auth import PROVIDER_REGISTRY
+
+ loopback = {"localhost", "127.0.0.1", "::1", "0.0.0.0"}
+ return frozenset(
+ name for name, config in PROVIDER_REGISTRY.items()
+ if urlparse(str(getattr(config, "inference_base_url", "") or "")).hostname in loopback
+ ) | {CUSTOM}
+
+
def _norm(value: object) -> str:
return value.strip().lower() if isinstance(value, str) else ""
@@ -142,6 +166,42 @@ def aux_task_metric_name(raw: object) -> str:
return name if name in _safe(aux_task_names) else "other"
+def provider_metric_name(raw: object) -> str:
+ """A shipped provider id; user-named providers (``custom:<name>``, unknown ids) read ``custom``."""
+ from .shared_metrics_contract import PROVIDER_IDENTIFIER_MAX_LENGTH, _metric_identifier
+
+ name = _metric_identifier(raw, max_length=PROVIDER_IDENTIFIER_MAX_LENGTH)
+ if name == "unknown":
+ return name
+ if name.startswith(CUSTOM):
+ return CUSTOM
+ return name if name in _safe(provider_names) or _models_dev_provider(name) else CUSTOM
+
+
[email protected]_cache(maxsize=256)
+def _models_dev_provider(name: str) -> bool:
+ """A public models.dev provider id, from the local cache only (never a network call)."""
+ try:
+ from agent.models_dev import get_provider_info
+
+ return get_provider_info(name, allow_network=False) is not None
+ except Exception:
+ return False
+
+
+def model_metric_name(raw: object, provider: str, *, max_length: int) -> str:
+ """The model id for a shipped remote provider; ``custom`` when the user names it (custom
+ endpoint, loopback server) or it looks like a filesystem path or URL."""
+ from .shared_metrics_contract import _metric_identifier
+
+ if provider in _safe(user_named_model_providers):
+ return CUSTOM
+ model = _metric_identifier(raw, max_length=max_length)
+ if "://" in model or ":/" in model or model.endswith((".gguf", ".bin", ".safetensors")):
+ return CUSTOM
+ return model
+
+
def display_language_metric_name(raw: object) -> str:
name = _norm(raw) or "en"
return name if name in _safe(display_languages) else "other"
diff --git a/hermes_cli/observability/shared_metrics_contract.py b/hermes_cli/observability/shared_metrics_contract.py
index 5c334267cd0..d9a5340aaca 100644
--- a/hermes_cli/observability/shared_metrics_contract.py
+++ b/hermes_cli/observability/shared_metrics_contract.py
@@ -921,10 +921,12 @@ def _non_negative_number(value: Any) -> float | None:
def model_call_fields(kwargs: dict[str, Any]) -> dict[str, str]:
"""Return the terminal model identity and provider route known to Hermes."""
- model = _metric_identifier(kwargs.get("response_model"), max_length=MODEL_IDENTIFIER_MAX_LENGTH)
+ from .shared_metrics_catalog import model_metric_name, provider_metric_name
+
+ provider = provider_metric_name(kwargs.get("provider"))
+ model = model_metric_name(kwargs.get("response_model"), provider, max_length=MODEL_IDENTIFIER_MAX_LENGTH)
if model == "unknown":
- model = _metric_identifier(kwargs.get("model"), max_length=MODEL_IDENTIFIER_MAX_LENGTH)
- provider = _metric_identifier(kwargs.get("provider"), max_length=PROVIDER_IDENTIFIER_MAX_LENGTH)
+ model = model_metric_name(kwargs.get("model"), provider, max_length=MODEL_IDENTIFIER_MAX_LENGTH)
return {"model": model, "provider": provider}
@@ -967,7 +969,7 @@ def install_snapshot_fields(
terminal_backend: Any, display_language: Any,
) -> dict[str, str]:
"""Bounded daily configuration snapshot: counts, closed enums and public names only."""
- from .shared_metrics_catalog import display_language_metric_name
+ from .shared_metrics_catalog import display_language_metric_name, provider_metric_name
provider = _norm(memory_provider)
backend = _norm(terminal_backend) or "local"
@@ -975,8 +977,7 @@ def install_snapshot_fields(
"cron_job_count_bucket": size_bucket(cron_jobs),
"display_language": display_language_metric_name(display_language),
"install_age_bucket": install_age_bucket if install_age_bucket in INSTALL_AGE_BUCKETS else "unknown",
- "main_provider": _metric_identifier(main_provider, max_length=PROVIDER_IDENTIFIER_MAX_LENGTH)
- if main_provider else "none",
+ "main_provider": provider_metric_name(main_provider) if main_provider else "none",
"mcp_server_count_bucket": size_bucket(mcp_servers),
"memory_provider": "builtin" if not provider
else provider if provider in MEMORY_PROVIDERS else "plugin",
diff --git a/hermes_cli/observability/shared_metrics_events.py b/hermes_cli/observability/shared_metrics_events.py
index 0220d46d0a1..6ebb67acc21 100644
--- a/hermes_cli/observability/shared_metrics_events.py
+++ b/hermes_cli/observability/shared_metrics_events.py
@@ -9,6 +9,7 @@ shared metrics are enabled, and never raises into the caller.
from __future__ import annotations
import logging
+import threading
from typing import Any, Callable
from . import shared_metrics_contract as contract
@@ -47,6 +48,35 @@ def record_compression(
)
+# Per-thread, not on the compressor or the agent: abort paths restore the compressor snapshot (seed
+# included) before they emit, and a stalled attempt's worker can unwind after its stall-fallback retry
+# began on another thread. An attempt begins and emits on one thread (the pool worker or the caller).
+_compression_attempt = threading.local()
+
+
+def begin_compression_attempt(trigger: str, tokens_before: Any) -> None:
+ _compression_attempt.pending = (trigger, tokens_before)
+
+
+def finish_compression_attempt(commit_status: str, failure_class: str | None, context_length: Any) -> None:
+ """Count this thread's pending compression attempt once."""
+ pending, _compression_attempt.pending = getattr(_compression_attempt, "pending", None), None
+ if not pending:
+ return
+ outcome = "success" if commit_status == "committed" else "skipped" if failure_class == "lock_contended" else "failed"
+ record_compression(trigger=pending[0], outcome=outcome, tokens_before=pending[1], context_length=context_length)
+
+
+def record_gateway_slash_command(event: Any) -> None:
+ """Count a user-typed gateway slash command once: a queued busy-path event re-enters
+ ``_handle_message`` when drained, so the event carries the mark."""
+ command = event.get_command()
+ if not command or getattr(event, "_slash_command_counted", False):
+ return
+ event._slash_command_counted = True
+ record_slash_command(command=command, surface="gateway")
+
+
def record_model_switch(*, from_provider: str | None, to_provider: str | None, surface: str) -> None:
_emit(
contract.MODEL_SWITCH_MARK, fields_.model_switch_fields,
diff --git a/hermes_cli/observability/shared_metrics_fields.py b/hermes_cli/observability/shared_metrics_fields.py
index 0035c16db14..f52cd3480e2 100644
--- a/hermes_cli/observability/shared_metrics_fields.py
+++ b/hermes_cli/observability/shared_metrics_fields.py
@@ -38,7 +38,7 @@ def _number(value: Any) -> float | None:
def provider_identifier(value: Any) -> str:
- return _metric_identifier(value, max_length=PROVIDER_IDENTIFIER_MAX_LENGTH)
+ return catalog.provider_metric_name(value)
def session_fields(
@@ -99,7 +99,9 @@ def model_token_fields(
return {
"aux_task": catalog.aux_task_metric_name(aux_task) if call_role == "auxiliary" else "none",
"call_role": call_role,
- "model": _metric_identifier(model, max_length=MODEL_IDENTIFIER_MAX_LENGTH),
+ "model": catalog.model_metric_name(
+ model, provider_identifier(provider), max_length=MODEL_IDENTIFIER_MAX_LENGTH,
+ ),
"provider": provider_identifier(provider),
**amounts,
}
diff --git a/hermes_cli/observability/shared_metrics_snapshot.py b/hermes_cli/observability/shared_metrics_snapshot.py
index 1a439ac6547..48b61b46e86 100644
--- a/hermes_cli/observability/shared_metrics_snapshot.py
+++ b/hermes_cli/observability/shared_metrics_snapshot.py
@@ -12,6 +12,7 @@ import json
import sqlite3
import time
from itertools import islice
+from pathlib import Path
from typing import Any
from hermes_constants import get_hermes_home
@@ -86,12 +87,12 @@ def _safe_count(reader) -> int:
_first_session_at: dict[str, float] = {}
-def _first_session_started_at() -> float | None:
+def _first_session_started_at(home: Path | None = None) -> float | None:
"""Epoch of the profile's first session; ``now`` when it has none yet (a brand-new install).
Raises ``sqlite3.Error`` when state.db exists but cannot be read.
"""
- home = get_hermes_home()
+ home = home or get_hermes_home()
if str(home) in _first_session_at:
return _first_session_at[str(home)]
database = home / "state.db"
@@ -107,12 +108,13 @@ def _first_session_started_at() -> float | None:
return _first_session_at[str(home)]
-def install_age_bucket() -> str:
- """How long ago this profile's first-ever session started, bucketed; ``unknown`` if unreadable."""
+def install_age_bucket(home: Path | None = None) -> str:
+ """How long ago the profile's first-ever session started, bucketed; ``unknown`` if unreadable.
+ ``home`` defaults to the bound profile; callers off the turn thread must pass theirs."""
from .shared_metrics_fields import install_age_bucket as bucket
try:
- first = _first_session_started_at()
+ first = _first_session_started_at(home)
except sqlite3.Error:
return "unknown"
return bucket(time.time() - first)
diff --git a/hermes_cli/observability/shared_metrics_subscriber.py b/hermes_cli/observability/shared_metrics_subscriber.py
index f401c977119..52c754c2485 100644
--- a/hermes_cli/observability/shared_metrics_subscriber.py
+++ b/hermes_cli/observability/shared_metrics_subscriber.py
@@ -9,6 +9,7 @@ from typing import Any
from agent.relay_runtime import RUNTIME_INSTANCE_KEY
from hermes_cli.config import detect_install_method
+from hermes_constants import get_hermes_home
from .shared_metrics import SharedMetricsStore
from .shared_metrics_fields import milestones_for
@@ -73,6 +74,8 @@ class SharedMetricsSubscriber:
self._active = True
self._lock = threading.RLock()
self._milestones_done: set[str] = set(store.recorded_milestones())
+ # Events arrive on the Relay thread, which carries no profile binding.
+ self._hermes_home = get_hermes_home()
def deactivate(self) -> None:
"""Stop accepting events before telemetry is disabled or torn down."""
@@ -92,7 +95,7 @@ class SharedMetricsSubscriber:
return
from .shared_metrics_snapshot import install_age_bucket
- age = install_age_bucket()
+ age = install_age_bucket(self._hermes_home)
for milestone in reached:
self.store.record_milestone(milestone, age, self._client_resource)
self._milestones_done.add(milestone)
diff --git a/hermes_cli/web_routers/mcp.py b/hermes_cli/web_routers/mcp.py
index 70c69e23558..32714e873dc 100644
--- a/hermes_cli/web_routers/mcp.py
+++ b/hermes_cli/web_routers/mcp.py
@@ -117,7 +117,7 @@ async def add_mcp_server(body: MCPServerCreate, profile: Optional[str] = None):
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
- def _run():
+ def _save() -> bool:
# _save_mcp_server does its own load→mutate→save; the duplicate-name
# check sits under the same lock span so a concurrent add can't slip
# between check and save.
@@ -134,13 +134,18 @@ async def add_mcp_server(body: MCPServerCreate, profile: Optional[str] = None):
raise HTTPException(status_code=409, detail=f"Server '{name}' already exists")
if bearer_token is not None:
server_config["headers"] = _save_bearer_auth_token(name, bearer_token)
- saved = _save_mcp_server(name, server_config)
+ return _save_mcp_server(name, server_config)
+
+ def _run():
+ saved = _save()
+ # Outside the config mutation lock: a cold first metric call costs imports + catalog loads.
+ with _profile_scope(body.profile or profile):
record_mcp_install("url" if server_config.get("url") else "local", None,
"success" if saved else "failed")
- if not saved:
- raise HTTPException(
- status_code=400, detail=f"Server '{name}' rejected: suspicious command/args configuration",
- )
+ if not saved:
+ raise HTTPException(
+ status_code=400, detail=f"Server '{name}' rejected: suspicious command/args configuration",
+ )
try:
await asyncio.to_thread(_run)
diff --git a/scripts/smoke_nemo_relay_shared_metrics.py b/scripts/smoke_nemo_relay_shared_metrics.py
index a0c26ec3219..06d2ef74cd4 100644
--- a/scripts/smoke_nemo_relay_shared_metrics.py
+++ b/scripts/smoke_nemo_relay_shared_metrics.py
@@ -334,7 +334,7 @@ def _validate_store(database_path: Path) -> list[dict[str, Any]]:
"dimensions": {
"call_role": "primary",
"error_class": "none",
- "model": MODEL_CANARY,
+ "model": "custom",
"outcome": "success",
"provider": "custom",
"ttft_bucket": "lt_500ms",
@@ -484,6 +484,7 @@ def _validate_packages(
serialized = json.dumps(packages)
for prohibited in (
+ MODEL_CANARY,
PROMPT_CANARY,
RESPONSE_CANARY,
TOOL_CALL_CANARY,
@@ -531,7 +532,7 @@ def _validate_packages(
if model["dimensions"] != {
"call_role": "primary",
"error_class": "none",
- "model": MODEL_CANARY,
+ "model": "custom",
"outcome": "success",
"provider": "custom",
"ttft_bucket": "lt_500ms",
diff --git a/tests/hermes_cli/test_relay_shared_metrics.py b/tests/hermes_cli/test_relay_shared_metrics.py
index e0064fd671c..118b31918bd 100644
--- a/tests/hermes_cli/test_relay_shared_metrics.py
+++ b/tests/hermes_cli/test_relay_shared_metrics.py
@@ -723,7 +723,7 @@ def test_tool_retry_bucket_requires_an_explicit_non_negative_count(
assert tool_retry_bucket(retry_count) == expected
-def test_model_call_fields_report_terminal_model_and_provider_without_a_catalog():
+def test_model_call_fields_report_terminal_model_and_shipped_provider():
assert model_call_fields({
"model": "fallback/model",
"response_model": "NVIDIA/Nemotron-3-Ultra",
@@ -733,12 +733,14 @@ def test_model_call_fields_report_terminal_model_and_provider_without_a_catalog(
"model": "nvidia/nemotron-3-ultra",
"provider": "openrouter",
}
+ # A provider Hermes does not ship is user-named (a custom endpoint key): neither it nor
+ # the model id it serves leaves the machine.
assert model_call_fields({
"model": "ZAI/GLM-5.2",
"provider": "Brev",
}) == {
- "model": "zai/glm-5.2",
- "provider": "brev",
+ "model": "custom",
+ "provider": "custom",
}
diff --git a/tests/hermes_cli/test_relay_shared_metrics_runtime.py b/tests/hermes_cli/test_relay_shared_metrics_runtime.py
index 360b309402d..a41c407ace3 100644
--- a/tests/hermes_cli/test_relay_shared_metrics_runtime.py
+++ b/tests/hermes_cli/test_relay_shared_metrics_runtime.py
@@ -673,7 +673,8 @@ def test_real_binding_drives_lifecycle_aggregation_export_and_snapshot(
assert route_by_outcome[outcome]["dimensions"] == {
"call_role": "primary",
"error_class": error_class,
- "model": model_canary,
+ # A custom endpoint's model id is user-named: it never leaves the machine.
+ "model": "custom",
"outcome": outcome,
"provider": "custom",
"ttft_bucket": route_by_outcome[outcome]["dimensions"]["ttft_bucket"],
@@ -765,8 +766,8 @@ def test_real_binding_drives_lifecycle_aggregation_export_and_snapshot(
"snapshot": snapshot,
"packages": package_payloads,
})
- assert model_canary in serialized_analytics
for canary in (
+ model_canary,
prompt_canary,
response_canary,
tool_canary,
@@ -2795,6 +2796,59 @@ def test_sessions_summarize_on_close_and_milestones_latch_once_per_install(direc
assert milestones["first_task_success"] == 1
+def test_user_named_providers_and_models_never_reach_counters(direct_runtime, tmp_path):
+ """A custom endpoint's name (``custom:<key>``), its model id and loopback-server models read
+ ``custom``; shipped providers and their public model ids stay readable."""
+ from hermes_cli.observability import shared_metrics_events as events
+ from hermes_cli.observability.shared_metrics import SharedMetricsStore
+
+ events.record_setup_completed(surface="cli", provider="custom:acme-secret-llm")
+ events.record_model_switch(from_provider="custom:acme-secret-llm", to_provider="lmstudio", surface="cli")
+ events.record_fallback(from_provider="acme-unknown", to_provider="openrouter", reason="rate_limit")
+ runtime = relay_shared_metrics._get_runtime(retry_failed=True)
+ for provider, model in (("custom:acme-secret-llm", "acme-internal"), ("lmstudio", "bob-finetune"),
+ ("openrouter", "c:/users/bob/model.gguf"), ("openrouter", "anthropic/claude-sonnet")):
+ runtime.record_auxiliary_tokens({
+ "usage": {"input_tokens": 5}, "aux_task": "compression", "provider": provider, "model": model,
+ })
+ runtime.relay.subscribers.flush()
+
+ root = tmp_path / "hermes-home" / "telemetry" / "shared_metrics"
+ stored = json.dumps(SharedMetricsStore(root / "metrics.sqlite3", root / "outbox").counter_snapshot())
+ assert not any(leak in stored for leak in ("acme", "bob", "users"))
+ tokens = {(d["provider"], d["model"]) for d, _ in _stored_values(tmp_path, "hermes.model_tokens.sum")}
+ assert tokens == {("custom", "custom"), ("lmstudio", "custom"), ("openrouter", "custom"),
+ ("openrouter", "anthropic/claude-sonnet")}
+
+
+def test_milestone_install_age_is_the_subscriber_profile_not_the_relay_thread(tmp_path, monkeypatch):
+ """Under multiplex the Relay thread carries no profile binding: a milestone reached in
+ profile B must carry B's install age, not the launch profile's."""
+ import sqlite3 as _sqlite3
+ import time
+
+ from hermes_cli.observability.shared_metrics import SharedMetricsStore
+ from hermes_cli.observability.shared_metrics_subscriber import SharedMetricsSubscriber
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+
+ launch, other = tmp_path / "A", tmp_path / "B"
+ for home in (launch, other):
+ home.mkdir()
+ with _sqlite3.connect(other / "state.db") as con:
+ con.execute("CREATE TABLE sessions (id TEXT, started_at REAL)")
+ con.execute("INSERT INTO sessions VALUES ('s1', ?)", (time.time() - 120 * 86400,))
+ monkeypatch.setenv("HERMES_HOME", str(launch))
+ token = set_hermes_home_override(str(other))
+ try:
+ subscriber = SharedMetricsSubscriber(SharedMetricsStore(), "1.0")
+ finally:
+ reset_hermes_home_override(token)
+ subscriber._record_milestones("hermes.setup.completed", {"provider": "nous", "surface": "cli"})
+ ages = [c["dimensions"]["install_age_bucket"] for c in subscriber.store.counter_snapshot()
+ if c["metric_name"] == "hermes.install.milestone"]
+ assert ages == ["gte_90d"]
+
+
def test_token_usage_is_summed_per_model_and_auxiliary_task(direct_runtime, tmp_path):
base = {"session_id": "s1", "task_id": "t1", "provider": "anthropic", "model": "claude-sonnet"}
for request_id in ("r1", "r2"):