The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(telemetry): pre-apply exit classes, parked parity, receipt-less refusals; docs + smoke
Tekniumb5a8fba1b4d8
diff --git a/scripts/smoke_nemo_relay_shared_metrics.py b/scripts/smoke_nemo_relay_shared_metrics.pyindex 978a397ef24..6fa34bbca16 100644--- a/scripts/smoke_nemo_relay_shared_metrics.py+++ b/scripts/smoke_nemo_relay_shared_metrics.py@@ -277,7 +277,7 @@ telemetry:# ---- iuf c1 ----# The offline probes in the skill-lifecycle subprocess: one failed URL plugin install and one failed-# update run (refused before the checkout moved), identical in SQLite and in the export.+# update run (its fetch failed before the checkout moved), identical in SQLite and in the export.FAILURE_EXPECTED_DIMENSIONS = {"hermes.extension.install.count": {"failure_class": "clone_failed", "kind": "plugin", "name": "custom", "outcome": "failed",@@ -285,7 +285,7 @@ FAILURE_EXPECTED_DIMENSIONS = {},"hermes.update.run": {"apply_mode": "unknown", "duration_bucket": "lt_30s", "failed_stage": "apply",- "failure_class": "aborted_before_apply", "from_version_age_bucket": "unknown", "kind": "cli",+ "failure_class": "fetch_failed", "from_version_age_bucket": "unknown", "kind": "cli","outcome": "failed",},}@@ -816,7 +816,7 @@ def main() -> int:"set_state(skill, STATE_ACTIVE)","record_installed(installed)",# A real failing plugin install (offline: a file:// repo that does not exist) and a- # dirty-tree-shaped final update receipt: each emits one row with a failure_class.+ # final update receipt whose fetch failed: each emits one row with a failure_class."from pathlib import Path","from hermes_cli.plugins_cmd import PluginOperationError, _install_plugin_core","from hermes_cli.plugins_cmd_install import recorded_install",@@ -831,6 +831,7 @@ def main() -> int:"record_update_receipt({'schema': 1, 'update_id': '0123456789abcdef',"," 'started_at': '2026-10-06T10:00:00+00:00', 'finished_at': '2026-10-06T10:00:01+00:00',"," 'outcome': 'failed', 'exit_code': 1, 'stop_reason': 'sys.exit(1)', 'pre_update': {},",+ " 'stop_class': 'fetch_failed',"," 'stages': [{'name': 'plan', 'outcome': 'success', 'at': '2026-10-06T10:00:00+00:00'},"," {'name': 'snapshot', 'outcome': 'skipped', 'at': '2026-10-06T10:00:00+00:00'}],"," 'steps': [], 'fleet': []})",diff --git a/tests/hermes_cli/test_shared_metrics_install_failures.py b/tests/hermes_cli/test_shared_metrics_install_failures.pyindex 2cacab9f696..6dbb64d7faa 100644--- a/tests/hermes_cli/test_shared_metrics_install_failures.py+++ b/tests/hermes_cli/test_shared_metrics_install_failures.py@@ -127,6 +127,10 @@ def test_a_partial_run_with_a_failed_stage_keeps_that_stage_and_its_verify_row_p(_receipt("failed", [("plan", "success")], exit_code=1,stop_reason="KeyboardInterrupt: /home/alice/x"), "interrupted"),(_receipt("failed", [("plan", "success")], exit_code=1, stop_reason="PermissionError: [Errno 13] /x"),+ "permission_denied"),+ (_receipt("failed", [("plan", "success")], exit_code=1, stop_reason="OSError: [Errno 28] No space left: /x"),+ "disk_full"),+ (_receipt("failed", [("plan", "success")], exit_code=1, stop_reason="FileExistsError: [Errno 17] /x"),"os_error"),(_receipt("failed", [("plan", "success")], exit_code=1, stop_reason="InstallError: venv: uv"), "deps_failed"),(_receipt("failed", [("plan", "success"), ("snapshot", "success"), ("apply", "success")], exit_code=1,diff --git a/tests/hermes_cli/test_shared_metrics_update_stop_reasons.py b/tests/hermes_cli/test_shared_metrics_update_stop_reasons.pynew file mode 100644index 00000000000..e45a3313edc--- /dev/null+++ b/tests/hermes_cli/test_shared_metrics_update_stop_reasons.py@@ -0,0 +1,100 @@+"""Every `hermes update` exit before the apply step names its closed reason (hermes.update.run+``failure_class``), in-process and through the parked copy alike; exits that fire before the+receipt opens still count once; a run that committed and owes work never reads ``failed``."""++from __future__ import annotations++import json+from types import SimpleNamespace++import pytest++from hermes_cli import update_receipt+from hermes_cli.observability import relay_shared_metrics+from hermes_cli.observability import shared_metrics_contract as contract+from hermes_cli.observability import shared_metrics_update as update_metrics+++def rows(tmp_path, monkeypatch):+ captured: list[tuple[str, dict]] = []+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))+ monkeypatch.setattr("hermes_cli.config.read_raw_config_readonly",+ lambda: {"telemetry": {"shared_metrics": {"enabled": True}}})+ monkeypatch.setattr(relay_shared_metrics, "enabled", lambda: True)+ monkeypatch.setattr(relay_shared_metrics, "record_process_mark", lambda mark, data: captured.append((mark, data)))+ monkeypatch.setattr(update_receipt, "_code_identity", lambda refresh=False: {"sha": "a" * 40, "commit_date": None})+ with update_receipt.update_receipt_scope():+ yield SimpleNamespace(runs=lambda: [d for m, d in captured if m == contract.UPDATE_RUN_MARK],+ home=tmp_path / "home")+++def _run(stop: str | None, *, applied: bool = False, code: int = 1, user_action: bool = False) -> dict:+ update_receipt.begin_update_receipt()+ update_receipt.record_stage("plan", "success")+ if user_action:+ update_receipt.record_user_action("local_changes", "stash ref /home/alice/private")+ if stop:+ update_receipt.record_stop_reason(stop)+ if applied:+ update_receipt.record_stage("apply", "success", mode="git")+ path = update_receipt.finalize_pending_update_receipt(code, f"sys.exit({code})")+ return json.loads(path.read_text(encoding="utf-8"))++[email protected](("stop", "kwargs", "expected"), [+ *[(name, {}, (name, "failed")) for name in sorted(contract.UPDATE_STOP_CLASSES - {"lock_held", "managed_install"})],+ ("not_a_class: /home/alice", {}, ("aborted_before_apply", "failed")), # only closed tokens pass+ (None, {}, ("aborted_before_apply", "failed")), # the fallback stays for an exit with no reason+ ("fetch_failed", {"applied": True}, ("deps_failed", "failed")), # a reason never outlives the apply+ (None, {"applied": True, "code": 1, "user_action": True}, ("local_changes_parked", "partial")),+])+def test_a_pre_apply_exit_reads_its_own_class_in_process_and_parked(rows, stop, kwargs, expected):+ """Invariant: the class is the exit that fired (recorded at it), the parked copy a pre-pull+ interpreter writes classifies the same run identically and keeps no free text, and a committed+ run that only owes the user's parked changes is ``partial``, never ``failed``."""+ receipt = _run(stop, **kwargs)+ (run,) = rows.runs()+ assert (run["failure_class"], run["outcome"]) == expected+ assert contract.counter_dimensions_are_valid(contract.UPDATE_RUN_METRIC, run)+ parked = update_receipt._metric_receipt(receipt)+ assert "/home/alice" not in json.dumps(parked)+ assert update_metrics.update_receipt_fields(json.loads(json.dumps(parked)))[0] == run+++def test_exits_before_the_receipt_opens_count_once_and_leave_the_holders_receipt_alone(rows, monkeypatch):+ """Invariant: the update-lock refusal and the Git-operation refusal fire before this run's+ receipt opens; each still yields exactly one row with its class, and neither writes a receipt+ (``latest.json`` belongs to the update holding the lock)."""+ from hermes_cli import main, update_cmd, update_lock, update_owning_install++ update_receipt.begin_update_receipt() # the holder's open run+ holders = (rows.home / "logs/update_receipts/latest.json").read_bytes()+ update_receipt._current.set(None)++ class Held:+ holder = None++ def __init__(self, **_kw):+ pass++ def acquire(self):+ return False++ monkeypatch.setattr(update_owning_install, "retarget_to_owning_install", lambda root: None)+ monkeypatch.setattr(main, "_update_preflight_handled", lambda args: False)+ monkeypatch.setattr(main, "_install_hangup_protection", lambda **kw: None)+ monkeypatch.setattr(main, "_finalize_update_output", lambda state: None)+ monkeypatch.setattr(update_lock, "UpdateLock", Held)+ monkeypatch.setattr(update_lock, "describe_holder", lambda holder: "another update is running")+ with pytest.raises(SystemExit) as refused:+ main.cmd_update(SimpleNamespace(gateway=False))+ monkeypatch.setattr(update_cmd, "git_operation_in_progress", lambda root: "rebase")+ with pytest.raises(SystemExit) as in_progress:+ update_cmd._cmd_update_impl(SimpleNamespace(), gateway_mode=False)++ assert (refused.value.code, in_progress.value.code) == (2, 1)+ assert [(r["failure_class"], r["outcome"], r["failed_stage"]) for r in rows.runs()] == [+ ("lock_held", "refused", "none"), ("git_in_progress", "failed", "other")]+ assert all(contract.counter_dimensions_are_valid(contract.UPDATE_RUN_METRIC, r) for r in rows.runs())+ assert (rows.home / "logs/update_receipts/latest.json").read_bytes() == holdersdiff --git a/website/docs/developer-guide/relay-shared-metrics.md b/website/docs/developer-guide/relay-shared-metrics.mdindex 60620e92c44..847705a03c0 100644--- a/website/docs/developer-guide/relay-shared-metrics.md+++ b/website/docs/developer-guide/relay-shared-metrics.md@@ -353,7 +353,7 @@ itself ships.| `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). || `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. |+| `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. `outcome` is `success`, `noop`, `failed`, `refused`, or `partial` (committed, then interrupted or left the user's stashed changes parked; `hermes update` rows only). `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 the bounded fields the row needs, 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. || `hermes.update.stage` | stage, outcome, duration_bucket | Per-stage result and wall time of `hermes update` (plan, snapshot, apply, deps, build, restart, verify), from the receipt's stage timestamps. || `hermes.process.exit` | process_kind, exit_kind, crash_class | How CLI / TUI / gateway / serve / cron-tick processes end (`clean`, `crash` with an exception family only, `killed`, `watchdog`), reported by the next start in the same profile from a local marker (a start with collection off deletes these markers, and pending `provider_setup` ones, unreported). Turns aborted by a turn watchdog also count as `exit_kind=watchdog`. |@@ -506,7 +506,7 @@ they failed. Rows recorded before the change keep their old field set and still| Metric | Dimensions added | Question it answers ||---|---|---|| `hermes.extension.install.count` | failure class, registry | Why skill, plugin and MCP installs fail, and which skills-hub source fails. `failure_class` is `none` on success, else a closed name for the failure exit that stopped the install. Skills: `ambiguous`, `auth_rejected`, `fetch_failed`, `invalid_bundle`, `invalid_name`, `not_found`, `rate_limited`, `scan_blocked`, `stale_index`. Plugins: `already_installed`, `clone_failed`, `deps_declined`, `deps_failed`, `git_missing`, `incompatible`, `invalid_source`, `manifest_invalid`, `non_interactive`, `removed_from_catalog`, `scan_blocked`. MCP servers: `auth_required`, `bootstrap_failed`, `clone_failed`, `config_invalid`, `config_rejected`, `connect_failed`, `git_missing`, `missing_credentials`, `server_start_failed`. Every kind may also read `exception`, `filesystem_error`, `network`, `other`, `permission`. A raised error without a named class is classified by its Python type only (`PermissionError` reads `permission`, connection and timeout errors `network`, other `OSError`s `filesystem_error`, anything else `exception`, its type name dropped). `registry` is set on skill rows only: the skills-hub adapter that resolved or served the skill, one of `browse-sh`, `clawhub`, `github`, `hermes-index`, `lobehub`, `official`, `skills-sh`, `url`, `well-known` (the adapter ids `tools/skills_hub_search.py::create_source_router` builds), `unresolved` when no adapter answered, `none` for built-in restores and every plugin/MCP row, `other` otherwise. A row whose `failure_class` is outside its kind's set, is `none` on a failure or set on a success, or that names a registry on a plugin/MCP row is invalid. Never the identifier, URL, error text or path; `name` keeps its existing catalog-or-`custom` rule. |-| `hermes.update.run` | failure class | Why `hermes update` fails, next to where (`failed_stage`). `none` unless the outcome is `failed` or `refused`. Derived from the final update receipt only: `aborted_before_apply`, `build_failed`, `deps_failed`, `exception`, `fleet_stale`, `fleet_unverified`, `git_failed`, `interrupted`, `lock_held`, `managed_install`, `os_error`, `restart_failed`, `subprocess_failed`, else `other`; Desktop packaged self-updates report `unknown` (their RPC carries a stage, never a reason). An exception that ended the run is read by its type name alone, never its message; a failed Windows gateway resume after the update reads `restart_failed`. A failed run whose every stage mark passed now reads `failed_stage` `verify` (the post-restart verification wrote `partial`) or `restart` (a skipped restart left the fleet owing one) instead of `other`; a `partial` run with a failed build or restart mark keeps that stage, and its verify stage row is failed only when the fleet has a stale or down row. |+| `hermes.update.run` | failure class | Why `hermes update` fails, next to where (`failed_stage`). `none` unless the outcome is `failed`, `refused` or `partial`. Derived from the final update receipt only: `build_failed`, `deps_failed`, `exception`, `fleet_stale`, `fleet_unverified`, `git_failed`, `interrupted`, `lock_held`, `managed_install`, `os_error`, `disk_full`, `permission_denied`, `restart_failed`, `subprocess_failed`, else `other`; Desktop packaged self-updates report `unknown` (their RPC carries a stage, never a reason). An exception that ended the run is read by its type name alone, never its message (a `PermissionError` reads `permission_denied`, an `OSError` whose errno is ENOSPC reads `disk_full`); a failed Windows gateway resume after the update reads `restart_failed`. Every exit that stops a run before it applies anything records one closed token at the exit itself, and the run reads it: `fetch_failed`, `git_timeout` (a network git call hit the updater's time limit), `channel_unresolved`, `git_in_progress` (a merge/rebase/... was already running), `git_index_locked`, `merge_conflict` (local commits on a custom branch), `checkout_move_failed`, `branch_missing`, `parked_branch_blocked`, `detached_head`, `unexpected_branch`, `head_moved` (a ref moved mid-update), `target_unresolved`, `target_syntax_error` (refused before the move), `syntax_rollback` (moved, failed the syntax check, rolled back), `commit_point_refused` (the commit point could not be armed; nothing moved), `venv_foreign_owner`, `local_changes_blocked` (local changes git could not stash, or a dirty tree the ZIP fallback will not overwrite), `stash_restore_rejected`, `not_git_checkout`, `old_version_handoff` (an older updater's hand-off could not finish), `branch_unsupported`, `download_failed`, `zip_failed`, `disk_full`, `lock_held`, `managed_install`. `aborted_before_apply` is now only the fallback for such an exit with no recorded token. The update-lock refusal, the Git-operation refusal and the managed-install refusal fire before the run's receipt opens; they still write no receipt (the receipt store belongs to the update holding the lock) and record one row with that token. A token is read only while the run has no apply mark, so a reason can never outlive the exit that recorded it. A run that committed and then was interrupted, or whose stashed local changes could not be re-applied, reads outcome `partial` (`interrupted` / `local_changes_parked`, `failed_stage` `apply` for the latter), never `failed`; owed follow-ups alone keep the run a `success` (contract C3). A run the pre-update interpreter finishes is parked with the token, the exit code, the stop reason's leading exception label and the restart/user-action flags (never argv, paths or messages), so it classifies exactly as the same run finished in-process. A failed run whose every stage mark passed now reads `failed_stage` `verify` (the post-restart verification wrote `partial`) or `restart` (a skipped restart left the fleet owing one) instead of `other`; a `partial` run with a failed build or restart mark keeps that stage, and its verify stage row is failed only when the fleet has a stale or down row. |<!-- ---- end iuf c1 ---- --><!-- ---- iuf c2 ---- -->#### Fresh installs