The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(telemetry): add opt-in send config and send-state columns
Ben Barclaye5180ab3df71
diff --git a/cli-config.yaml.example b/cli-config.yaml.exampleindex 1a8021ff984..2fe2c5e610c 100644--- a/cli-config.yaml.example+++ b/cli-config.yaml.example@@ -1782,15 +1782,28 @@ display:# =============================================================================# Shared metrics are disabled by default. When enabled, Hermes writes only# allowlisted aggregate counters and immutable JSON-# packages under $HERMES_HOME/telemetry/shared_metrics; it does not upload them.+# packages under $HERMES_HOME/telemetry/shared_metrics.# Packages include a random profile-scoped ID that stays stable until this# directory is deleted. It is not derived from hardware, account, or host data.# Successfully exported local history is retained for 30 days; pending deltas# are retained until they can be exported.# This profile-owned choice is not overridden by managed-scope configuration.+#+# Nothing is uploaded unless you also set `send: true`. That is a separate+# opt-in and requires `enabled`; it never turns collection on by itself.+# When sending is on:+# * only packages whose period starts on or after the day you opted in are+# ever transmitted, so data collected beforehand stays on this machine;+# * the profile-scoped ID is NOT sent. Each package carries an HMAC of it,+# keyed by a local-only salt that rotates every 30 days, so installs stay+# countable without shipping a durable identifier.+# See docs/observability/relay-shared-metrics.md (Appendix A) for the full+# consent, identity, rotation, retention, and deletion decisions.telemetry:shared_metrics:enabled: false+ send: false+ # endpoint: https://telemetry.nousresearch.com/v1/telemetry# =============================================================================diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex 0fb14883168..cf321b4e3da 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -3323,11 +3323,27 @@ DEFAULT_CONFIG = {"profile_build": "ask",},- # Privacy-safe aggregate metrics written only to this profile's local- # telemetry directory. Collection is opt-in and no remote sink exists.+ # Privacy-safe aggregate metrics written to this profile's local telemetry+ # directory. Collection is opt-in (``enabled``). Transmission to the Nous+ # telemetry service is a SEPARATE opt-in (``send``) and is off by default;+ # see docs/observability/relay-shared-metrics.md, Appendix A, for the+ # consent, identity, rotation, retention, and deletion decisions."telemetry": {"shared_metrics": {"enabled": False,+ # Transmit exported packages to the Nous telemetry service.+ # Requires ``enabled``: it never switches collection on by itself,+ # and ``send`` without ``enabled`` is logged as an error rather+ # than silently doing nothing. Only packages whose period starts+ # on or after the opt-in day are ever sent, so data collected+ # before consent stays local.+ "send": False,+ # Ingest endpoint. Production by default; override for staging or+ # a local test server. The HERMES_TELEMETRY_ENDPOINT environment+ # variable takes precedence (used by the live E2E so a test never+ # has to mutate a user's config). Non-HTTPS is refused unless the+ # host is localhost.+ "endpoint": "https://telemetry.nousresearch.com/v1/telemetry",},},diff --git a/hermes_cli/observability/shared_metrics.py b/hermes_cli/observability/shared_metrics.pyindex fd42b062306..bf5c1fb0bf4 100644--- a/hermes_cli/observability/shared_metrics.py+++ b/hermes_cli/observability/shared_metrics.py@@ -337,6 +337,7 @@ class SharedMetricsStore:)""")+ SharedMetricsStore._add_send_columns(connection)connection.execute("""INSERT INTO telemetry_state(key, value)@@ -346,6 +347,42 @@ class SharedMetricsStore:(_STORE_SCHEMA_VERSION,),)+ @staticmethod+ def _add_send_columns(connection: sqlite3.Connection) -> None:+ """Add transmission bookkeeping to ``package_outbox``, idempotently.++ These columns are ADDITIVE and nullable, and the store schema version+ is deliberately NOT bumped. ``_ensure_schema_in_transaction`` raises on+ any version it does not recognise and has no forward-compatibility+ branch, so bumping would make an older Hermes — a second profile on an+ older build, or a rollback — hard-fail against the same database file.+ Old readers select named columns and never ``SELECT *``, so extra+ columns are invisible to them.+ """+ existing = {+ str(row["name"])+ for row in connection.execute("PRAGMA table_info(package_outbox)")+ }+ for column, declaration in (+ # When the 202 was received. NULL = never acknowledged.+ ("sent_at", "TEXT"),+ # NULL/'pending' = eligible, 'sent' = done, 'rejected' = permanent 400.+ ("send_state", "TEXT"),+ ("send_attempts", "INTEGER NOT NULL DEFAULT 0"),+ # Earliest next attempt; enforces backoff across process restarts.+ ("next_attempt_at", "TEXT"),+ ("last_error", "TEXT"),+ # The derived identifier actually transmitted, frozen on the first+ # attempt so retries stay byte-identical across a salt rotation.+ # Only the ~36-byte id is stored: the body is recomputed from+ # payload_json, whose serialisation is deterministic.+ ("sent_install_id", "TEXT"),+ ):+ if column not in existing:+ connection.execute(+ f"ALTER TABLE package_outbox ADD COLUMN {column} {declaration}"+ )+@staticmethoddef _create_counter_aggregates_table(connection: sqlite3.Connection) -> None:connection.execute(diff --git a/hermes_cli/observability/shared_metrics_send_config.py b/hermes_cli/observability/shared_metrics_send_config.pynew file mode 100644index 00000000000..8011c595ab1--- /dev/null+++ b/hermes_cli/observability/shared_metrics_send_config.py@@ -0,0 +1,114 @@+"""Configuration for shared-metrics transmission.++Collection (``telemetry.shared_metrics.enabled``) and transmission+(``telemetry.shared_metrics.send``) are separate opt-ins. See+``docs/observability/relay-shared-metrics.md`` Appendix A for the consent,+identity, rotation, retention, and deletion decisions behind this module.+"""++from __future__ import annotations++import logging+import os+from dataclasses import dataclass+from urllib.parse import urlparse++logger = logging.getLogger(__name__)++#: Production ingest endpoint. Overridable by config or environment so the+#: live E2E can target staging without mutating a user's config.+DEFAULT_ENDPOINT = "https://telemetry.nousresearch.com/v1/telemetry"++#: Environment override, highest precedence. Intended for tests and staging+#: validation, not as the documented user-facing setting (which is config).+ENDPOINT_ENV_VAR = "HERMES_TELEMETRY_ENDPOINT"++_LOCAL_HOSTS = frozenset({"localhost", "127.0.0.1", "::1", "[::1]"})++# Module-level latch: the enabled/send mismatch is a static misconfiguration,+# so it is reported once per process instead of on every hook fire.+_warned_send_without_collection = False+++@dataclass(frozen=True)+class SendConfig:+ """Resolved transmission settings."""++ #: Collection is on. Nothing is packaged or sent without it.+ enabled: bool+ #: Transmission is on AND permitted (that is, collection is also on).+ send: bool+ #: Where packages are POSTed.+ endpoint: str+++def _endpoint_is_safe(endpoint: str) -> bool:+ """Reject plaintext destinations unless they are loopback.++ Telemetry must not leave a machine in clear text because of a typo in a+ config file. Loopback stays allowed so tests can use a local HTTP server.+ """+ try:+ parsed = urlparse(endpoint)+ except ValueError:+ return False+ if parsed.scheme == "https":+ return True+ if parsed.scheme == "http":+ return (parsed.hostname or "") in _LOCAL_HOSTS+ return False+++def resolve_send_config(config: dict | None) -> SendConfig:+ """Resolve transmission settings from config plus the environment.++ Endpoint precedence: ``HERMES_TELEMETRY_ENDPOINT`` > config > production+ default.++ ``send`` is returned as False whenever transmission cannot legitimately+ happen, so callers never have to re-check the combination.+ """+ global _warned_send_without_collection++ raw = config if isinstance(config, dict) else {}+ telemetry = raw.get("telemetry")+ telemetry = telemetry if isinstance(telemetry, dict) else {}+ shared = telemetry.get("shared_metrics")+ shared = shared if isinstance(shared, dict) else {}++ enabled = shared.get("enabled") is True+ send_requested = shared.get("send") is True++ if send_requested and not enabled:+ # Loud, not silent: the user believes telemetry is being sent, and it+ # never will be. Error level, once per process.+ if not _warned_send_without_collection:+ _warned_send_without_collection = True+ logger.error(+ "telemetry.shared_metrics.send is true but "+ "telemetry.shared_metrics.enabled is false — nothing is "+ "collected, so nothing can be sent. Enable collection or "+ "turn sending off."+ )+ return SendConfig(enabled=False, send=False, endpoint=DEFAULT_ENDPOINT)++ endpoint = os.environ.get(ENDPOINT_ENV_VAR) or shared.get("endpoint")+ if not isinstance(endpoint, str) or not endpoint.strip():+ endpoint = DEFAULT_ENDPOINT+ endpoint = endpoint.strip()++ if send_requested and not _endpoint_is_safe(endpoint):+ logger.error(+ "Refusing to send shared metrics to %r: telemetry must use https "+ "(or a localhost http endpoint for testing).",+ endpoint,+ )+ return SendConfig(enabled=enabled, send=False, endpoint=endpoint)++ return SendConfig(enabled=enabled, send=send_requested, endpoint=endpoint)+++def reset_warning_latch_for_tests() -> None:+ """Clear the once-per-process error latch (test support only)."""+ global _warned_send_without_collection+ _warned_send_without_collection = Falsediff --git a/hermes_cli/setup.py b/hermes_cli/setup.pyindex 4f0d1902034..d6497fbc051 100644--- a/hermes_cli/setup.py+++ b/hermes_cli/setup.py@@ -2428,10 +2428,10 @@ def setup_tools(config: dict, first_install: bool = False):def setup_telemetry(config: dict):- """Configure the local, privacy-safe shared-metrics subscriber."""+ """Configure the local shared-metrics subscriber and optional sending."""print_header("Shared Metrics")print_info("Shared metrics contain only bounded counters and histograms.")- print_info("Packages stay under this Hermes profile and are not uploaded.")+ print_info("Collection is local. Sending them to Nous is a separate opt-in.")telemetry = config.get("telemetry")if not isinstance(telemetry, dict):@@ -2447,10 +2447,30 @@ def setup_telemetry(config: dict):"Enable local shared metrics?",default=current,)- if shared_metrics["enabled"]:- print_success("Local shared metrics enabled.")- else:+ if not shared_metrics["enabled"]:print_info("Local shared metrics disabled.")+ # Sending cannot outlive collection: leaving send=true here would be a+ # configuration that logs an error on every run and never transmits.+ if shared_metrics.get("send") is True:+ shared_metrics["send"] = False+ print_info("Sending shared metrics disabled as well.")+ return++ print_success("Local shared metrics enabled.")+ print_info("")+ print_info("Sending uploads each daily package to the Nous telemetry")+ print_info("service. Your profile-scoped install ID is NOT sent: packages")+ print_info("carry a rotating HMAC of it instead. Only packages from the")+ print_info("day you opt in onwards are ever sent, and sending can be")+ print_info("turned off again at any time.")+ shared_metrics["send"] = prompt_yes_no(+ "Send shared metrics to Nous?",+ default=shared_metrics.get("send") is True,+ )+ if shared_metrics["send"]:+ print_success("Sending shared metrics enabled.")+ else:+ print_info("Sending shared metrics disabled (collection stays local).")# =============================================================================diff --git a/tests/hermes_cli/test_shared_metrics_send_config.py b/tests/hermes_cli/test_shared_metrics_send_config.pynew file mode 100644index 00000000000..235777d49ab--- /dev/null+++ b/tests/hermes_cli/test_shared_metrics_send_config.py@@ -0,0 +1,137 @@+"""Tests for shared-metrics send configuration resolution."""++from __future__ import annotations++import logging++import pytest++from hermes_cli.config import DEFAULT_CONFIG+from hermes_cli.observability.shared_metrics_send_config import (+ DEFAULT_ENDPOINT,+ ENDPOINT_ENV_VAR,+ resolve_send_config,+ reset_warning_latch_for_tests,+)++[email protected](autouse=True)+def _reset_latch():+ reset_warning_latch_for_tests()+ yield+ reset_warning_latch_for_tests()+++def _config(**shared):+ return {"telemetry": {"shared_metrics": shared}}+++class TestDefaults:+ def test_send_is_registered_disabled_by_default(self):+ shared = DEFAULT_CONFIG["telemetry"]["shared_metrics"]+ assert shared["enabled"] is False+ assert shared["send"] is False++ def test_default_endpoint_is_production(self):+ shared = DEFAULT_CONFIG["telemetry"]["shared_metrics"]+ assert shared["endpoint"] == DEFAULT_ENDPOINT+ assert DEFAULT_ENDPOINT.startswith("https://")++ def test_empty_config_sends_nothing(self):+ resolved = resolve_send_config({})+ assert resolved.enabled is False+ assert resolved.send is False++ def test_none_config_is_tolerated(self):+ assert resolve_send_config(None).send is False+++class TestSendRequiresCollection:+ def test_collection_alone_does_not_send(self):+ resolved = resolve_send_config(_config(enabled=True))+ assert resolved.enabled is True+ assert resolved.send is False++ def test_send_with_collection_sends(self):+ resolved = resolve_send_config(_config(enabled=True, send=True))+ assert resolved.send is True++ def test_send_without_collection_is_refused(self):+ resolved = resolve_send_config(_config(enabled=False, send=True))+ assert resolved.send is False+ # send must never imply enabled+ assert resolved.enabled is False++ def test_send_without_collection_logs_an_error(self, caplog):+ with caplog.at_level(logging.ERROR):+ resolve_send_config(_config(enabled=False, send=True))+ errors = [r for r in caplog.records if r.levelno >= logging.ERROR]+ assert len(errors) == 1+ assert "enabled is false" in errors[0].getMessage()++ def test_the_error_is_logged_once_per_process(self, caplog):+ with caplog.at_level(logging.ERROR):+ for _ in range(5):+ resolve_send_config(_config(enabled=False, send=True))+ errors = [r for r in caplog.records if r.levelno >= logging.ERROR]+ assert len(errors) == 1, "misconfiguration must not spam every hook fire"+++class TestEndpointPrecedence:+ def test_config_endpoint_overrides_default(self):+ resolved = resolve_send_config(+ _config(enabled=True, send=True, endpoint="https://example.test/v1")+ )+ assert resolved.endpoint == "https://example.test/v1"++ def test_env_var_overrides_config(self, monkeypatch):+ monkeypatch.setenv(ENDPOINT_ENV_VAR, "https://staging.test/v1")+ resolved = resolve_send_config(+ _config(enabled=True, send=True, endpoint="https://example.test/v1")+ )+ assert resolved.endpoint == "https://staging.test/v1"++ def test_blank_endpoint_falls_back_to_production(self):+ resolved = resolve_send_config(_config(enabled=True, send=True, endpoint=" "))+ assert resolved.endpoint == DEFAULT_ENDPOINT++ def test_endpoint_is_stripped(self, monkeypatch):+ monkeypatch.setenv(ENDPOINT_ENV_VAR, " https://staging.test/v1 ")+ assert resolve_send_config(_config(enabled=True, send=True)).endpoint == (+ "https://staging.test/v1"+ )+++class TestTransportSafety:+ def test_plaintext_endpoint_is_refused(self, caplog):+ with caplog.at_level(logging.ERROR):+ resolved = resolve_send_config(+ _config(enabled=True, send=True, endpoint="http://example.test/v1")+ )+ assert resolved.send is False, "telemetry must not go out in clear text"+ assert any("https" in r.getMessage() for r in caplog.records)++ @pytest.mark.parametrize(+ "endpoint",+ [+ "http://localhost:8099/v1/telemetry",+ "http://127.0.0.1:8099/v1/telemetry",+ ],+ )+ def test_loopback_http_is_allowed_for_testing(self, endpoint):+ resolved = resolve_send_config(+ _config(enabled=True, send=True, endpoint=endpoint)+ )+ assert resolved.send is True++ def test_nonsense_scheme_is_refused(self):+ resolved = resolve_send_config(+ _config(enabled=True, send=True, endpoint="ftp://example.test/v1")+ )+ assert resolved.send is False++ def test_unsafe_endpoint_does_not_block_collection(self):+ resolved = resolve_send_config(+ _config(enabled=True, send=True, endpoint="http://example.test/v1")+ )+ assert resolved.enabled is Truediff --git a/tests/hermes_cli/test_shared_metrics_send_migration.py b/tests/hermes_cli/test_shared_metrics_send_migration.pynew file mode 100644index 00000000000..54518c644ad--- /dev/null+++ b/tests/hermes_cli/test_shared_metrics_send_migration.py@@ -0,0 +1,224 @@+"""Tests for the additive send-state migration on ``package_outbox``.++The store schema version must NOT move when these columns are added: the+existing loader raises on any version it does not recognise, so bumping it+would hard-fail an older Hermes (a second profile on an older build, or a+rollback) against the same database file.+"""++from __future__ import annotations++import json+import sqlite3++import pytest++from hermes_cli.observability.shared_metrics import SharedMetricsStore++SEND_COLUMNS = {+ "sent_at",+ "send_state",+ "send_attempts",+ "next_attempt_at",+ "last_error",+ "sent_install_id",+}+++def _columns(db_path):+ connection = sqlite3.connect(db_path)+ try:+ return {row[1] for row in connection.execute("PRAGMA table_info(package_outbox)")}+ finally:+ connection.close()+++def _schema_version(db_path):+ connection = sqlite3.connect(db_path)+ try:+ row = connection.execute(+ "SELECT value FROM telemetry_state WHERE key = 'schema_version'"+ ).fetchone()+ return row[0] if row else None+ finally:+ connection.close()+++def store(tmp_path):+ return SharedMetricsStore(+ database_path=tmp_path / "metrics.sqlite3",+ outbox_directory=tmp_path / "outbox",+ )+++class TestFreshDatabase:+ def test_send_columns_exist(self, store):+ assert SEND_COLUMNS <= _columns(store.database_path)++ def test_original_columns_survive(self, store):+ assert {+ "package_id",+ "period_start",+ "period_end",+ "payload_json",+ "created_at",+ "exported_at",+ } <= _columns(store.database_path)++ def test_send_attempts_defaults_to_zero(self, store):+ connection = sqlite3.connect(store.database_path)+ try:+ connection.execute(+ """+ INSERT INTO package_outbox(+ package_id, period_start, period_end, payload_json, created_at+ ) VALUES ('p', '2026-01-01', '2026-01-02', '{}', '2026-01-01T00:00:00Z')+ """+ )+ connection.commit()+ row = connection.execute(+ "SELECT send_attempts, send_state, sent_install_id FROM package_outbox"+ ).fetchone()+ finally:+ connection.close()+ assert row[0] == 0+ assert row[1] is None+ assert row[2] is None+++class TestUpgradeFromPreSendDatabase:+ """The real-world case: a database written before this feature existed."""++ @pytest.fixture+ def legacy_db(self, tmp_path):+ path = tmp_path / "metrics.sqlite3"+ connection = sqlite3.connect(path)+ try:+ connection.execute(+ """+ CREATE TABLE telemetry_state (+ key TEXT PRIMARY KEY,+ value TEXT NOT NULL+ )+ """+ )+ connection.execute(+ "INSERT INTO telemetry_state(key, value) VALUES ('schema_version', '2')"+ )+ connection.execute(+ """+ CREATE TABLE package_outbox (+ package_id TEXT PRIMARY KEY,+ period_start TEXT NOT NULL,+ period_end TEXT NOT NULL,+ payload_json TEXT NOT NULL,+ created_at TEXT NOT NULL,+ exported_at TEXT+ )+ """+ )+ connection.execute(+ """+ CREATE TABLE counter_aggregates (+ period_start TEXT NOT NULL,+ metric_name TEXT NOT NULL,+ hermes_version TEXT NOT NULL,+ os_family TEXT NOT NULL,+ architecture TEXT NOT NULL,+ install_method TEXT NOT NULL,+ dimensions_json TEXT NOT NULL,+ value INTEGER NOT NULL,+ packaged_value INTEGER NOT NULL,+ PRIMARY KEY (+ period_start, metric_name, hermes_version, os_family,+ architecture, install_method, dimensions_json+ )+ )+ """+ )+ for i in range(3):+ connection.execute(+ """+ INSERT INTO package_outbox(+ package_id, period_start, period_end, payload_json,+ created_at, exported_at+ ) VALUES (?, ?, ?, ?, ?, ?)+ """,+ (+ f"pkg-{i}",+ "2026-08-2%d" % i,+ "2026-08-2%d" % (i + 1),+ json.dumps({"package_id": f"pkg-{i}"}),+ "2026-08-2%dT00:00:00Z" % i,+ "2026-08-2%dT01:00:00Z" % i,+ ),+ )+ connection.commit()+ finally:+ connection.close()+ return path++ def test_upgrade_preserves_every_row(self, legacy_db, tmp_path):+ SharedMetricsStore(+ database_path=legacy_db, outbox_directory=tmp_path / "outbox"+ )+ connection = sqlite3.connect(legacy_db)+ try:+ count = connection.execute("SELECT COUNT(*) FROM package_outbox").fetchone()[0]+ payloads = connection.execute(+ "SELECT package_id, payload_json FROM package_outbox ORDER BY package_id"+ ).fetchall()+ finally:+ connection.close()+ assert count == 3+ assert payloads == [+ ("pkg-0", '{"package_id": "pkg-0"}'),+ ("pkg-1", '{"package_id": "pkg-1"}'),+ ("pkg-2", '{"package_id": "pkg-2"}'),+ ]++ def test_upgrade_adds_the_send_columns(self, legacy_db, tmp_path):+ SharedMetricsStore(+ database_path=legacy_db, outbox_directory=tmp_path / "outbox"+ )+ assert SEND_COLUMNS <= _columns(legacy_db)++ def test_upgrade_does_not_move_the_schema_version(self, legacy_db, tmp_path):+ """Bumping would make older builds refuse the same file."""+ SharedMetricsStore(+ database_path=legacy_db, outbox_directory=tmp_path / "outbox"+ )+ assert _schema_version(legacy_db) == "2"++ def test_migration_is_idempotent(self, legacy_db, tmp_path):+ for _ in range(3):+ SharedMetricsStore(+ database_path=legacy_db, outbox_directory=tmp_path / "outbox"+ )+ columns = [+ row[1]+ for row in sqlite3.connect(legacy_db).execute(+ "PRAGMA table_info(package_outbox)"+ )+ ]+ assert len(columns) == len(set(columns)), "columns were added more than once"++ def test_queries_written_before_this_change_still_work(self, legacy_db, tmp_path):+ """The shipped export query selects named columns; it must be unaffected."""+ SharedMetricsStore(+ database_path=legacy_db, outbox_directory=tmp_path / "outbox"+ )+ connection = sqlite3.connect(legacy_db)+ try:+ rows = connection.execute(+ """+ SELECT package_id, payload_json+ FROM package_outbox+ WHERE exported_at IS NULL+ ORDER BY created_at, package_id+ """+ ).fetchall()+ finally:+ connection.close()+ assert rows == []