The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(metrics): hermes.update.run/stage derived from the final update receipt
teknium1fd14f50b5da9
diff --git a/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.json b/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.jsonindex e8711194a98..c5d06292030 100644--- a/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.json+++ b/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.json@@ -186,6 +186,15 @@},{"$ref": "#/$defs/startup_latency_counter"+ },+ {+ "$ref": "#/$defs/update_run_counter"+ },+ {+ "$ref": "#/$defs/update_stage_counter"+ },+ {+ "$ref": "#/$defs/process_exit_counter"}]}@@ -2252,6 +2261,218 @@"minimum": 1}}+ },+ "update_run_counter": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "type",+ "dimensions",+ "value"+ ],+ "properties": {+ "name": {+ "const": "hermes.update.run"+ },+ "type": {+ "const": "counter"+ },+ "dimensions": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "apply_mode",+ "duration_bucket",+ "failed_stage",+ "from_version_age_bucket",+ "kind",+ "outcome"+ ],+ "properties": {+ "apply_mode": {+ "enum": [+ "external",+ "git",+ "package",+ "unknown",+ "zip"+ ]+ },+ "duration_bucket": {+ "enum": [+ "2m_to_5m",+ "30s_to_2m",+ "5m_to_15m",+ "gte_15m",+ "lt_30s"+ ]+ },+ "failed_stage": {+ "enum": [+ "apply",+ "build",+ "deps",+ "download",+ "none",+ "other",+ "plan",+ "restart",+ "snapshot",+ "verify"+ ]+ },+ "from_version_age_bucket": {+ "enum": [+ "30d_to_90d",+ "7d_to_30d",+ "gte_90d",+ "lt_7d",+ "unknown"+ ]+ },+ "kind": {+ "enum": [+ "cli",+ "desktop"+ ]+ },+ "outcome": {+ "enum": [+ "failed",+ "noop",+ "refused",+ "success"+ ]+ }+ }+ },+ "value": {+ "type": "integer",+ "minimum": 1+ }+ }+ },+ "update_stage_counter": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "type",+ "dimensions",+ "value"+ ],+ "properties": {+ "name": {+ "const": "hermes.update.stage"+ },+ "type": {+ "const": "counter"+ },+ "dimensions": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "duration_bucket",+ "outcome",+ "stage"+ ],+ "properties": {+ "duration_bucket": {+ "enum": [+ "2m_to_5m",+ "30s_to_2m",+ "5m_to_15m",+ "gte_15m",+ "lt_30s"+ ]+ },+ "outcome": {+ "enum": [+ "failed",+ "skipped",+ "success"+ ]+ },+ "stage": {+ "enum": [+ "apply",+ "build",+ "deps",+ "plan",+ "restart",+ "snapshot",+ "verify"+ ]+ }+ }+ },+ "value": {+ "type": "integer",+ "minimum": 1+ }+ }+ },+ "process_exit_counter": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "type",+ "dimensions",+ "value"+ ],+ "properties": {+ "name": {+ "const": "hermes.process.exit"+ },+ "type": {+ "const": "counter"+ },+ "dimensions": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "crash_class",+ "exit_kind",+ "process_kind"+ ],+ "properties": {+ "crash_class": {+ "enum": [+ "import_error",+ "memory_error",+ "none",+ "os_error",+ "other",+ "runtime_error"+ ]+ },+ "exit_kind": {+ "enum": [+ "clean",+ "crash",+ "killed",+ "watchdog"+ ]+ },+ "process_kind": {+ "enum": [+ "cli",+ "cron",+ "gateway",+ "other",+ "serve",+ "tui"+ ]+ }+ }+ },+ "value": {+ "type": "integer",+ "minimum": 1+ }+ }}}}diff --git a/hermes_cli/observability/shared_metrics_contract.py b/hermes_cli/observability/shared_metrics_contract.pyindex 8d535edf84f..cefa9e867c8 100644--- a/hermes_cli/observability/shared_metrics_contract.py+++ b/hermes_cli/observability/shared_metrics_contract.py@@ -275,6 +275,45 @@ _INSTALL_V4_SNAPSHOT_DIMENSIONS = {"ram_bucket": RAM_BUCKETS, "release_channel": RELEASE_CHANNELS, "version_age_bucket": VERSION_AGE_BUCKETS,}+# ---- v4 reliability ----+UPDATE_RUN_MARK = UPDATE_RUN_METRIC = "hermes.update.run"+UPDATE_STAGE_MARK = UPDATE_STAGE_METRIC = "hermes.update.stage"+PROCESS_EXIT_MARK = PROCESS_EXIT_METRIC = "hermes.process.exit"+UPDATE_KINDS = frozenset({"cli", "desktop"})+UPDATE_OUTCOMES = frozenset({"failed", "noop", "refused", "success"})+# `hermes update` pipeline stages, in pipeline order (the receipt's stage marks use these names).+UPDATE_STAGE_ORDER = ("plan", "snapshot", "apply", "deps", "build", "restart", "verify")+UPDATE_STAGES = frozenset(UPDATE_STAGE_ORDER)+# Desktop's packaged updaters (electron-updater, App Installer, Store) fail at their own steps.+DESKTOP_UPDATE_STAGES = frozenset({"apply", "download", "restart", "verify"})+UPDATE_FAILED_STAGES = UPDATE_STAGES | DESKTOP_UPDATE_STAGES | {"none", "other"}+UPDATE_STAGE_OUTCOMES = frozenset({"failed", "skipped", "success"})+UPDATE_DURATION_BUCKETS = frozenset({"lt_30s", "30s_to_2m", "2m_to_5m", "5m_to_15m", "gte_15m"})+VERSION_AGE_BUCKETS = frozenset({"lt_7d", "7d_to_30d", "30d_to_90d", "gte_90d", "unknown"})+# package = an OS/app-store style installer applied the update (Desktop packaged builds).+UPDATE_APPLY_MODES = frozenset({"external", "git", "package", "unknown", "zip"})+PROCESS_KINDS = frozenset({"cli", "cron", "gateway", "other", "serve", "tui"})+PROCESS_EXIT_KINDS = frozenset({"clean", "crash", "killed", "watchdog"})+CRASH_CLASSES = frozenset({"import_error", "memory_error", "none", "os_error", "other", "runtime_error"})+_UPDATE_DURATION_THRESHOLDS = (+ (30_000, "lt_30s"), (120_000, "30s_to_2m"), (300_000, "2m_to_5m"), (900_000, "5m_to_15m"),+)+_DAY_MS = 86_400_000+_VERSION_AGE_THRESHOLDS = ((7 * _DAY_MS, "lt_7d"), (30 * _DAY_MS, "7d_to_30d"), (90 * _DAY_MS, "30d_to_90d"))+++def update_duration_bucket(duration_ms: Any) -> str:+ """Bucket an update (or update stage) wall time; non-numbers count as instant."""+ value = _non_negative_number(duration_ms) or 0+ return _bucket(value, _UPDATE_DURATION_THRESHOLDS, "gte_15m")+++def version_age_bucket(age_ms: Any) -> str:+ """Bucket the age of the version an update started from; unknown when not measurable."""+ value = _non_negative_number(age_ms)+ return "unknown" if value is None else _bucket(value, _VERSION_AGE_THRESHOLDS, "gte_90d")+# ---- end v4 reliability ----+_ARCHITECTURE_ALIASES = {"amd64": "x86_64", "x64": "x86_64", "x86_64": "x86_64","aarch64": "arm64", "arm64": "arm64",@@ -454,6 +493,19 @@ _COUNTER_DIMENSION_VALUES: dict[str, dict[str, frozenset[str]]] = {# ---- end v4 model ----# ---- v4 install ----STARTUP_LATENCY_METRIC: {"latency_bucket": STARTUP_LATENCY_BUCKETS, "surface": STARTUP_SURFACES},+ # ---- v4 reliability ----+ UPDATE_RUN_METRIC: {+ "apply_mode": UPDATE_APPLY_MODES, "duration_bucket": UPDATE_DURATION_BUCKETS,+ "failed_stage": UPDATE_FAILED_STAGES, "from_version_age_bucket": VERSION_AGE_BUCKETS,+ "kind": UPDATE_KINDS, "outcome": UPDATE_OUTCOMES,+ },+ UPDATE_STAGE_METRIC: {+ "duration_bucket": UPDATE_DURATION_BUCKETS, "outcome": UPDATE_STAGE_OUTCOMES, "stage": UPDATE_STAGES,+ },+ PROCESS_EXIT_METRIC: {+ "crash_class": CRASH_CLASSES, "exit_kind": PROCESS_EXIT_KINDS, "process_kind": PROCESS_KINDS,+ },+ # ---- end v4 reliability ----}_MODEL_ROUTE_MAX_LENGTHS = {"model": MODEL_IDENTIFIER_MAX_LENGTH, "provider": PROVIDER_IDENTIFIER_MAX_LENGTH,@@ -518,6 +570,10 @@ _DECISION_MARK_METRICS = {# ---- end v4 model ----# ---- v4 install ----STARTUP_LATENCY_MARK: STARTUP_LATENCY_METRIC,+ # ---- v4 reliability ----+ UPDATE_RUN_MARK: UPDATE_RUN_METRIC, UPDATE_STAGE_MARK: UPDATE_STAGE_METRIC,+ PROCESS_EXIT_MARK: PROCESS_EXIT_METRIC,+ # ---- end v4 reliability ----}diff --git a/hermes_cli/observability/shared_metrics_update.py b/hermes_cli/observability/shared_metrics_update.pynew file mode 100644index 00000000000..225af640e1c--- /dev/null+++ b/hermes_cli/observability/shared_metrics_update.py@@ -0,0 +1,215 @@+"""Shared-metrics facts for ``hermes update`` runs and Desktop self-updates.++``hermes.update.run`` / ``hermes.update.stage`` are DERIVED from the final update receipt in the+process that finalizes it (``update_receipt.finalize_update_receipt``): the receipt already carries+the outcome, the stage marks with timestamps, the admission refusal and the fleet matrix, so no+stage is instrumented for metrics. A pre-pull interpreter must never import pulled code, so when+it is the finalizer it parks the receipt under the store dir (stdlib-only code in update_receipt)+and :func:`report_pending_updates` records it on the next Hermes start.++Desktop's packaged updaters (electron-updater, App Installer, Store) never run ``hermes update``;+Desktop reports their outcome through the ``shared_metrics.update_run`` RPC instead. Desktop's+source-checkout hand-off DOES run ``hermes update``; that receipt is tagged ``initiator=desktop``+and counted here, never by the RPC, so no run is counted twice.+"""++from __future__ import annotations++import json+import logging+import time+from datetime import datetime+from pathlib import Path+from typing import Any++logger = logging.getLogger(__name__)++PENDING_DIRNAME = "pending_updates"+# Receipt pm/Desktop outcome words → hermes.update.run outcome; anything else failed.+_RUN_OUTCOMES = {"success": "success", "refused": "refused", "noop": "noop"}+_FLEET_BAD_STATES = frozenset({"stale", "down"})+# Desktop mechanism (updater strategy kind) → apply_mode.+_DESKTOP_APPLY_MODES = {+ "electron-updater": "package", "app-installer": "package", "microsoft-store": "package",+ "windows-handoff": "git", "posix-handoff": "git",+}+++def _epoch(value: Any) -> float | None:+ if isinstance(value, (int, float)) and not isinstance(value, bool):+ return float(value)+ try:+ return datetime.fromisoformat(str(value)).timestamp()+ except (TypeError, ValueError):+ return None+++def _elapsed_ms(start: Any, end: Any) -> float | None:+ first, last = _epoch(start), _epoch(end)+ return None if first is None or last is None or last < first else (last - first) * 1000+++def _receipt_stages(receipt: dict[str, Any]) -> list[dict[str, Any]]:+ """Stage marks in order, each with a duration since the previous mark (or the run start)."""+ from .shared_metrics_contract import UPDATE_STAGES++ stages: list[dict[str, Any]] = []+ previous = receipt.get("started_at")+ for mark in receipt.get("stages") or ():+ if not isinstance(mark, dict) or mark.get("name") not in UPDATE_STAGES:+ continue+ stages.append({**mark, "duration_ms": _elapsed_ms(previous, mark.get("at"))})+ previous = mark.get("at") or previous+ fleet = receipt.get("fleet")+ # The fleet matrix is only passed to finalize by the post-restart verification.+ if isinstance(fleet, list) and fleet and not any(s["name"] == "verify" for s in stages):+ bad = any(isinstance(row, dict) and row.get("state") in _FLEET_BAD_STATES for row in fleet)+ stages.append({+ "name": "verify", "outcome": "failed" if bad else "success",+ "duration_ms": _elapsed_ms(previous, receipt.get("finished_at")),+ })+ return stages+++def _failed_stage(stages: list[dict[str, Any]]) -> str:+ """Where a failed/refused run stopped: the failing stage, else the stage it never reached."""+ from .shared_metrics_contract import UPDATE_STAGE_ORDER++ if not stages:+ return "other"+ last = stages[-1]+ terminal = last["name"] == "verify" or (last["name"] == "restart" and last.get("outcome") == "skipped")+ if last.get("outcome") == "failed" or terminal:+ failed = [s["name"] for s in stages if s.get("outcome") == "failed"]+ return failed[-1] if failed else "other"+ index = UPDATE_STAGE_ORDER.index(last["name"])+ return UPDATE_STAGE_ORDER[index + 1] if index + 1 < len(UPDATE_STAGE_ORDER) else "other"+++def _apply_mode(receipt: dict[str, Any], stages: list[dict[str, Any]]) -> str:+ for stage in stages:+ if stage["name"] == "apply" and stage.get("mode") in {"git", "zip"}:+ return stage["mode"]+ # An admission refusal means the install is owned by something else (Docker, Nix, a package).+ if any(isinstance(s, dict) and s.get("name") == "admission" and not s.get("ok") for s in receipt.get("steps") or ()):+ return "external"+ return "unknown"+++def update_receipt_fields(receipt: dict[str, Any]) -> tuple[dict[str, str], list[dict[str, str]]] | None:+ """Bounded hermes.update.run + hermes.update.stage dimensions for one FINAL receipt."""+ from .shared_metrics_contract import update_duration_bucket, version_age_bucket++ if not isinstance(receipt, dict) or not receipt.get("finished_at"):+ return None+ stages = _receipt_stages(receipt)+ outcome = _RUN_OUTCOMES.get(str(receipt.get("outcome") or ""), "failed")+ if outcome == "success" and any(s["name"] == "apply" and s.get("outcome") == "skipped" for s in stages):+ outcome = "noop"+ started = _epoch(receipt.get("started_at"))+ committed = _epoch((receipt.get("pre_update") or {}).get("commit_date"))+ age_ms = None if started is None or committed is None else (started - committed) * 1000+ run = {+ "apply_mode": _apply_mode(receipt, stages),+ "duration_bucket": update_duration_bucket(_elapsed_ms(receipt.get("started_at"), receipt.get("finished_at"))),+ "failed_stage": _failed_stage(stages) if outcome in {"failed", "refused"} else "none",+ "from_version_age_bucket": version_age_bucket(age_ms),+ "kind": "desktop" if receipt.get("initiator") == "desktop" else "cli",+ "outcome": outcome,+ }+ if run["outcome"] == "refused" and not stages:+ run["failed_stage"] = "none"+ stage_rows = [+ {+ "duration_bucket": update_duration_bucket(stage["duration_ms"]),+ "outcome": stage.get("outcome") if stage.get("outcome") in {"success", "failed", "skipped"} else "failed",+ "stage": stage["name"],+ }+ for stage in stages+ ]+ return run, stage_rows+++def _collection_on() -> bool:+ """Cheap pre-gate so a disabled install never loads the Relay runtime; `_emit` re-checks."""+ from hermes_cli.config import read_raw_config_readonly++ config: Any = read_raw_config_readonly() or {}+ 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+++def record_update_receipt(receipt: dict[str, Any]) -> None:+ """Record one run row plus its stage rows from a final receipt. Never raises."""+ try:+ if not _collection_on():+ return+ from . import shared_metrics_contract as contract+ from .shared_metrics_events import _emit++ derived = update_receipt_fields(receipt)+ if derived is None:+ return+ run, stage_rows = derived+ _emit(contract.UPDATE_RUN_MARK, lambda: run)+ for row in stage_rows:+ _emit(contract.UPDATE_STAGE_MARK, lambda row=row: row)+ except Exception:+ logger.debug("Update shared metrics not recorded", exc_info=True)+++def pending_updates_dir(home: Path) -> Path:+ return home / "telemetry" / "shared_metrics" / PENDING_DIRNAME+++def report_pending_updates() -> None:+ """Record receipts a pre-pull interpreter parked (it must not import pulled code). Never raises."""+ try:+ from hermes_constants import get_hermes_home++ directory = pending_updates_dir(get_hermes_home())+ if not directory.is_dir():+ return+ for path in sorted(directory.glob("*.json")):+ try:+ receipt = json.loads(path.read_text(encoding="utf-8"))+ path.unlink() # claim first: a concurrent start that loses the unlink records nothing+ except (OSError, ValueError):+ continue+ record_update_receipt(receipt)+ except Exception:+ logger.debug("Pending update shared metrics not reported", exc_info=True)+++def desktop_update_fields(+ *, outcome: Any, failed_stage: Any, duration_ms: Any, mechanism: Any, from_commit_date: Any = None,+) -> dict[str, str]:+ """hermes.update.run dims for a Desktop packaged self-update (RPC-reported)."""+ from .shared_metrics_contract import (+ DESKTOP_UPDATE_STAGES, UPDATE_OUTCOMES, update_duration_bucket, version_age_bucket,+ )++ outcome_value = str(outcome or "").strip().lower()+ outcome_value = outcome_value if outcome_value in UPDATE_OUTCOMES else "failed"+ stage = str(failed_stage or "").strip().lower()+ commit = _epoch(from_commit_date)+ # Desktop sends seconds since epoch (install stamp commitDate); age is measured now.+ age_ms = None if commit is None else (time.time() - commit) * 1000+ return {+ "apply_mode": _DESKTOP_APPLY_MODES.get(str(mechanism or "").strip().lower(), "unknown"),+ "duration_bucket": update_duration_bucket(duration_ms),+ "failed_stage": (stage if stage in DESKTOP_UPDATE_STAGES else "other") if outcome_value == "failed" else "none",+ "from_version_age_bucket": version_age_bucket(age_ms),+ "kind": "desktop",+ "outcome": outcome_value,+ }+++def record_desktop_update(**raw: Any) -> None:+ """Emit one Desktop self-update run through the enabled() gate. Never raises."""+ from . import shared_metrics_contract as contract+ from .shared_metrics_events import _emit++ _emit(contract.UPDATE_RUN_MARK, desktop_update_fields, **raw)+diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex fa6925b3b00..73f552f97bc 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -256,6 +256,11 @@ def _record_pre_update_backup_outcome(args, snapshot_id) -> None:_record_update_step("pre_update_backup", False, "no snapshot captured")+def _record_snapshot_stage(args, snapshot_id) -> None:+ skipped = not snapshot_id and _resolve_pre_update_backup_mode(args) == "off"+ _completion_receipt.record_stage("snapshot", "success" if snapshot_id else "skipped" if skipped else "failed")++def _git_run(git_cmd, args, cwd=None, *, check=False, network=False):"""Run git capturing utf-8 text (default cwd: checkout); ``network=True`` disables the@@ -729,6 +734,8 @@ def _complete_source_update(request: dict | None) -> None:if unrestored:request["completion_message"] = unrestoredfrom copy import deepcopy+ _completion_receipt.record_stage(+ "apply", "skipped" if request.get("completion_message") else "success", mode=request.get("apply_mode", "git"))current = _completion_receipt._current.get()if current is not None:request["receipt"] = deepcopy(current.data)@@ -1198,6 +1205,7 @@ def _begin_update_receipt_and_plan(args):# See #74973, #81193, #85753, #88848, #91277.from hermes_cli.update_receipt import begin_update_receiptbegin_update_receipt()+ _record_update_initiator()# Plan phase: snapshot runtimes/supervisors/version (read-only; probe failure records# nothing). Re-read AFTER the restart phase to reconcile — the plan is the worklist.@@ -1215,10 +1223,20 @@ def _begin_update_receipt_and_plan(args):_n = len(_pre_update_plan.runtimes)_profiles = ", ".join(sorted({r.profile for r in _pre_update_plan.runtimes}))print(f"→ Fleet: {_n} running service(s) across profiles: {_profiles}")-+ _completion_receipt.record_stage("plan", "failed" if _pre_update_plan is None else "success")return _pre_update_plan+def _record_update_initiator() -> None:+ """We hold the update lock, so a live claim naming another pid is our orchestrator's: the+ Desktop hand-off (posix shim, windows script, Tauri updater) — the metric's ``kind``."""+ with _best_effort('Update initiator unavailable: %s'):+ from hermes_cli.update_lock import read_live_update+ holder = read_live_update()+ if holder is not None and holder.pid != os.getpid():+ _completion_receipt.record_fact("initiator", "desktop")++def _prepare_git_command() -> tuple[bool, list, bool]:"""Return ``(use_zip_update, git_cmd, is_fork)``; ``sys.exit(1)`` when not a git repoon a non-Windows host (Windows falls back to ZIP: broken git file I/O, AV, NTFS filters)."""@@ -1422,6 +1440,7 @@ def _cmd_update_impl(args, gateway_mode: bool):# reason, not as a failed step (see _record_pre_update_backup_outcome).pre_update_snapshot_id = _m()._run_pre_update_backup(args)_record_pre_update_backup_outcome(args, pre_update_snapshot_id)+ _record_snapshot_stage(args, pre_update_snapshot_id)_windows_gateway_resume = _m()._pause_windows_gateways_for_update()if _windows_gateway_resume:diff --git a/hermes_cli/update_cmd_zip.py b/hermes_cli/update_cmd_zip.pyindex d04b7c6c09c..ce8db1ca96d 100644--- a/hermes_cli/update_cmd_zip.py+++ b/hermes_cli/update_cmd_zip.py@@ -406,5 +406,6 @@ def _update_via_zip(args, *, had_desktop_app_before_update: bool = False,raise ValueError("ZIP update requires a GitHub owner/repository")_download_and_swap_zip(branch, f"https://github.com/{repository}/archive/{ref}.zip")completion_request["expected_sha"] = target_sha+ completion_request["apply_mode"] = "zip"_complete_source_update(completion_request)return Truediff --git a/hermes_cli/update_completion.py b/hermes_cli/update_completion.pyindex d06c5ff6f38..7a57ee80ad9 100644--- a/hermes_cli/update_completion.py+++ b/hermes_cli/update_completion.py@@ -189,6 +189,8 @@ def _complete_selected(request: dict) -> None:pre_update_version=request["pre_update_version"],completion_message=request.get("completion_message"),announce=None if request.get("completion_message") else "\n✓ Code updated!")+ from hermes_cli.update_receipt import record_stage+ record_stage("build", "success" if complete else "failed")if complete:from hermes_cli.venv_sync import clear_completionclear_completion(root)@@ -200,6 +202,7 @@ def _complete_selected(request: dict) -> None:from hermes_cli.update_receipt import record_skiprecord_skip("gateway_restart", "--no-gateway-restart: deferred, marker kept")+ record_stage("restart", "skipped")print("→ Gateway restart deferred (--no-gateway-restart); restart gateways separately.")if not complete:raise SystemExit(1)@@ -209,6 +212,7 @@ def _complete_selected(request: dict) -> None:from hermes_cli.update_receipt import record_skiprecord_skip("gateway_restart", skip)+ record_stage("restart", "skipped")print(f" ✓ Gateway restart skipped: {skip}.")# Discharges the obligation this run armed when the live fleet vouches for it; a# fleet still owing the restart fails closed exactly like a stale matrix would.@@ -219,6 +223,7 @@ def _complete_selected(request: dict) -> None:raise SystemExit(1)returnrestart = update_cmd._restart_gateway_fleet_after_update(plan, request["gateway_mode"])+ record_stage("restart", "failed" if getattr(restart, "incomplete", False) else "success")update_cmd._resume_windows_gateways_and_merge_outcome(restart, request["windows_resume"], request["gateway_mode"])update_cmd._verify_fleet_after_update(restart, _pre_update_plan=plan, _windows_gateway_resume=request["windows_resume"], update_complete=complete)@@ -243,6 +248,7 @@ def _finish(request: dict, result_path: Path) -> int:_resume_receipt(request["receipt"])accept_worker_receipt(request.get("pm_receipt"), request["receipt"]["update_id"])+ update_receipt.record_stage("deps", "success") # only a completed PM preparation reaches --preparedcode, reason = 0, "source update completion"try:_complete_selected(request)diff --git a/hermes_cli/update_receipt.py b/hermes_cli/update_receipt.pyindex c1d6ddf4664..198678f8b2d 100644--- a/hermes_cli/update_receipt.py+++ b/hermes_cli/update_receipt.py@@ -125,6 +125,13 @@ class UpdateReceipt:def skip(self, name: str, reason: str) -> None:self.data["skips"].append({"name": name, "reason": reason, "at": _utc_now_iso()})+ def stage(self, name: str, outcome: str, **facts: str) -> None:+ # Stage END marks: a stage's duration is the gap since the previous mark (or started_at).+ self.data.setdefault("stages", []).append({"name": name, "outcome": outcome, "at": _utc_now_iso(), **facts})++ def fact(self, key: str, value: Any) -> None:+ self.data[key] = value+def gateway_restart_result(self, *, restarted_services: list | None = None, relaunched_profiles: list | None = None,externally_supervised_profiles: list | None = None, killed_pids: list | None = None,@@ -232,6 +239,16 @@ def record_skip(name: str, reason: str) -> None:_record("skip", f"update skip {name}", name, reason)+def record_stage(name: str, outcome: str, **facts: str) -> None:+ """Mark the END of a pipeline stage (``success``/``failed``/``skipped``) with a timestamp."""+ _record("stage", f"update stage {name}", name, outcome, **facts)+++def record_fact(key: str, value: Any) -> None:+ """Set one top-level receipt field (e.g. ``initiator``)."""+ _record("fact", f"update fact {key}", key, value)++def record_gateway_restart(**kwargs: Any) -> None:"""Record the gateway restart phase outcome (see UpdateReceipt)."""_record("gateway_restart_result", "gateway restart result", **kwargs)@@ -315,6 +332,7 @@ def finalize_update_receipt(outcome: str, fleet: list | None = None, stop_reasonwith suppress(Exception): # stable pointer for the dashboard/desktop_atomic_bytes(directory / "latest.json", payload)_prune_old_receipts(directory)+ _publish_shared_metrics(receipt.data)return pathexcept Exception as exc:# Visible, not debug: a run that pulled code and left no receipt is exactly the run@@ -324,6 +342,27 @@ def finalize_update_receipt(outcome: str, fleet: list | None = None, stop_reasonreturn None+def _publish_shared_metrics(data: dict[str, Any]) -> None:+ """hermes.update.run/stage from this FINAL receipt; must never fail or slow the update."""+ with suppress(Exception):+ pre, post = data.get("pre_update") or {}, data.get("post_update") or {}+ if data.get("pid") == os.getpid() and not (pre.get("sha") and pre.get("sha") == post.get("sha")):+ # This interpreter began the run before the checkout swap: importing now would load+ # pulled code into it. Park the receipt (stdlib only); the next Hermes start records it.+ from hermes_constants import get_hermes_home+ from hermes_cli.runtime_state import _atomic_bytes++ store = get_hermes_home() / "telemetry" / "shared_metrics"+ if store.is_dir(): # never enabled on this profile: nothing to park+ pending = store / "pending_updates" # = shared_metrics_update.PENDING_DIRNAME+ pending.mkdir(exist_ok=True)+ _atomic_bytes(pending / f"{data.get('update_id')}.json", json.dumps(data, default=str).encode())+ return+ from hermes_cli.observability.shared_metrics_update import record_update_receipt++ record_update_receipt(data)++def finalize_pending_update_receipt(exit_code: Optional[int] = None, stop_reason: str = "") -> Optional[Path]:"""Command-boundary safety net: persist a still-open receipt, if any. Never raises.diff --git a/hermes_cli/version_info.py b/hermes_cli/version_info.pyindex dd90971bb18..fd0c38ffe8a 100644--- a/hermes_cli/version_info.py+++ b/hermes_cli/version_info.py@@ -303,7 +303,7 @@ def get_code_identity(refresh: bool = False) -> dict:"""Return the running install's code identity as a flat dict.Shape: ``{"sha": full sha | None, "short_sha": str | None, "version":- base package version | None, "source": str}`` — what the update+ base package version | None, "source": str, "commit_date": epoch s | None}`` — what the updatereceipt, runtime inventory, and gateway status stamping consume.Backed by :func:`get_version_info` (install stamp first, live gitsecond, unknown third), so every consumer shares one resolution@@ -322,4 +322,5 @@ def get_code_identity(refresh: bool = False) -> dict:"short_sha": info.commit[:8] if info.commit else None,"version": info.base_version,"source": info.source,+ "commit_date": info.commit_date,}diff --git a/tests/hermes_cli/test_update_completion_process.py b/tests/hermes_cli/test_update_completion_process.pyindex 3d89fddfeae..dd2be1780bc 100644--- a/tests/hermes_cli/test_update_completion_process.py+++ b/tests/hermes_cli/test_update_completion_process.py@@ -136,6 +136,7 @@ def transition(tmp_path):"import contextvars, json, os, pathlib\n""_current = contextvars.ContextVar('receipt', default=None)\n""class UpdateReceipt: pass\n"+ "def record_stage(*args, **kwargs): pass\n""def finalize_pending_update_receipt(code, reason):\n"" r = _current.get()\n"" if r is None: return\n"diff --git a/website/docs/developer-guide/relay-shared-metrics.md b/website/docs/developer-guide/relay-shared-metrics.mdindex 9806cf947f4..9e5af8b2ced 100644--- a/website/docs/developer-guide/relay-shared-metrics.md+++ b/website/docs/developer-guide/relay-shared-metrics.md@@ -313,6 +313,9 @@ 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. |+| `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 (`kind` is `desktop` when Desktop's source-checkout hand-off ran it); 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. Turns aborted by a turn watchdog also count as `exit_kind=watchdog`. |Sessions are summarized when they close (finalize, reset or process exit);delegated child sessions are not counted separately. Milestones latch in the