The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(telemetry): updates that stop before applying say why
Tekniumd56a48d62685
diff --git a/hermes_cli/_old_updater.py b/hermes_cli/_old_updater.pyindex 69250d60af0..a20b1d2cc48 100644--- a/hermes_cli/_old_updater.py+++ b/hermes_cli/_old_updater.py@@ -193,7 +193,11 @@ def stop_for_relaunch(*, incomplete: bool = False) -> NoReturn:"""if incomplete:# A newly retired completion hook has no complete captured worklist.- # It must not start another update or invent a successful receipt.+ # It must not start another update or invent a successful receipt. It names its stop on+ # the receipt the loaded update_receipt keeps open (an older one lacks the call: no-op).+ record = getattr(sys.modules.get("hermes_cli.update_receipt"), "record_stop_reason", None)+ if record is not None:+ record("old_version_handoff")print("You're updating from an older version of Hermes Agent. ""To complete this update, run `hermes update` again.",diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex 48862c376d3..347984bcada 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -2329,6 +2329,9 @@ def _update_preflight_handled(args) -> bool:sys.exit(0)if is_managed():managed_error("update Hermes Agent")+ from hermes_cli.update_cmd_common import _record_stop++ _record_stop("managed_install", without_receipt="refused") # before the lock: a metrics row onlyreturn True# --plan is read-only and deployment-kind aware, so it runs BEFORE the@@ -2423,6 +2426,10 @@ def cmd_update(args):if not _update_lock.acquire():print(describe_holder(_update_lock.holder))_finalize_update_output(_update_io_state)+ from hermes_cli.update_cmd_common import _record_stop++ # No receipt: latest.json and the running record belong to the update holding the lock.+ _record_stop("lock_held", without_receipt="refused")sys.exit(UPDATE_EXIT_CONCURRENT)diff --git a/hermes_cli/observability/schemas/hermes.shared_metrics.v4.schema.json b/hermes_cli/observability/schemas/hermes.shared_metrics.v4.schema.jsonindex d9e674e0b18..1e76f15e540 100644--- a/hermes_cli/observability/schemas/hermes.shared_metrics.v4.schema.json+++ b/hermes_cli/observability/schemas/hermes.shared_metrics.v4.schema.json@@ -2715,21 +2715,48 @@"failure_class": {"enum": ["aborted_before_apply",+ "branch_missing",+ "branch_unsupported","build_failed",+ "channel_unresolved",+ "checkout_move_failed",+ "commit_point_refused","deps_failed",+ "detached_head",+ "disk_full",+ "download_failed","exception",+ "fetch_failed","fleet_stale","fleet_unverified","git_failed",+ "git_in_progress",+ "git_index_locked",+ "git_timeout",+ "head_moved","interrupted",+ "local_changes_blocked",+ "local_changes_parked","lock_held","managed_install",+ "merge_conflict","none",+ "not_git_checkout",+ "old_version_handoff","os_error","other",+ "parked_branch_blocked",+ "permission_denied","restart_failed",+ "stash_restore_rejected","subprocess_failed",- "unknown"+ "syntax_rollback",+ "target_syntax_error",+ "target_unresolved",+ "unexpected_branch",+ "unknown",+ "venv_foreign_owner",+ "zip_failed"]},"from_version_age_bucket": {@@ -2751,6 +2778,7 @@"enum": ["failed","noop",+ "partial","refused","success"]diff --git a/hermes_cli/observability/shared_metrics_contract.py b/hermes_cli/observability/shared_metrics_contract.pyindex 95553695ca8..c774d5a0814 100644--- a/hermes_cli/observability/shared_metrics_contract.py+++ b/hermes_cli/observability/shared_metrics_contract.py@@ -357,6 +357,9 @@ 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"})+# ``partial``: committed, but interrupted after the commit point or the user's changes stay parked+# (only `hermes update` receipts; the Desktop RPC keeps UPDATE_OUTCOMES).+UPDATE_RUN_OUTCOMES = UPDATE_OUTCOMES | {"partial"}# `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)@@ -463,7 +466,7 @@ EXTENSION_REGISTRIES = EXTENSION_REGISTRY_IDS | frozenset({"none", "other", "unr# Why a `hermes update` run failed or was refused, derived from the FINAL receipt only# (shared_metrics_update.update_failure_class); ``none`` unless outcome is failed/refused.UPDATE_FAILURE_CLASSES = frozenset({- "aborted_before_apply", # exited before the checkout moved (fetch, channel, branch, merge, HEAD checks)+ "aborted_before_apply", # fallback: exited before the checkout moved with no reason recorded"build_failed", # the build stage reported failure"deps_failed", # PM dependency preparation failed (no deps mark, or a PM error type)"exception", # the run ended on an uncaught exception (type name dropped)@@ -478,7 +481,42 @@ UPDATE_FAILURE_CLASSES = frozenset({"restart_failed", # the gateway restart failed, or a skipped restart left the fleet owing one"subprocess_failed", # a subprocess error (CalledProcessError, TimeoutExpired) reached the boundary"unknown", # the reporter sent no reason (Desktop packaged updaters)+ "disk_full", # out of disk space (ENOSPC, or no room to stage the ZIP)+ "local_changes_parked", # committed, but the user's stashed changes could not be re-applied (partial)+ "permission_denied", # the run ended on a PermissionError})+# The exit that stopped a run before it applied anything, recorded at the exit itself as one of+# these tokens (update_receipt.record_stop_reason -> the receipt's ``stop_class``).+UPDATE_STOP_CLASSES = frozenset({+ "branch_missing", # the target branch exists neither locally nor on origin+ "branch_unsupported", # --branch on the Windows ZIP fallback+ "channel_unresolved", # the update channel could not be resolved+ "checkout_move_failed", # git could not move the checkout (ff refused, reset or switch failed)+ "commit_point_refused", # the commit point could not be armed durably; nothing moved+ "detached_head", # a detached checkout stayed put, or its commits could not be backed up+ "disk_full", # (see above)+ "download_failed", # the ZIP fallback download failed+ "fetch_failed", # git fetch failed+ "git_in_progress", # a merge/rebase/cherry-pick/... was already in progress+ "git_index_locked", # git refused: another git process's .git/index.lock exists+ "git_timeout", # a network git call hit the updater's time limit+ "head_moved", # a ref moved during the update; HEAD is not the selected commit+ "local_changes_blocked", # local changes git could not stash, or a dirty tree the ZIP will not overwrite+ "lock_held", # (see above)+ "managed_install", # (see above): HERMES_MANAGED installs refuse before any receipt+ "merge_conflict", # local commits on a custom branch conflict with upstream+ "not_git_checkout", # the install is not a git checkout (non-Windows)+ "old_version_handoff", # an older updater's hand-off to this version could not finish+ "parked_branch_blocked", # the checkout is parked on another branch that is unsafe to switch+ "stash_restore_rejected", # re-applied local changes broke Hermes; the update stopped+ "syntax_rollback", # the pulled code failed the syntax check and was rolled back+ "target_syntax_error", # the target failed the syntax check before anything moved+ "target_unresolved", # the fetched target ref did not resolve to a commit+ "unexpected_branch", # the checkout ended on a branch that is not the target+ "venv_foreign_owner", # the venv belongs to another OS user+ "zip_failed", # the ZIP fallback swap failed and was rolled back+})+UPDATE_FAILURE_CLASSES |= UPDATE_STOP_CLASSES# ---- end iuf c1 ----# ---- iuf c2 ----# One fresh-install run of scripts/install.sh / install.ps1, from the local receipt the installer@@ -906,7 +944,7 @@ _COUNTER_DIMENSION_VALUES: dict[str, dict[str, frozenset[str]]] = {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,+ "kind": UPDATE_KINDS, "outcome": UPDATE_RUN_OUTCOMES,# ---- iuf c1 ----"failure_class": UPDATE_FAILURE_CLASSES,# ---- end iuf c1 ----diff --git a/hermes_cli/observability/shared_metrics_update.py b/hermes_cli/observability/shared_metrics_update.pyindex e171e68cffe..c756d0f7299 100644--- a/hermes_cli/observability/shared_metrics_update.py+++ b/hermes_cli/observability/shared_metrics_update.py@@ -68,6 +68,9 @@ _EXCEPTION_TYPE_CLASSES = (_STOP_REASON_PREFIX_CLASSES = (("historical takeover preparation failed", "deps_failed"), ("Windows gateway recovery failed", "restart_failed"),)+# An OSError that ended the run, read by its errno token alone (never the text after it):+# ENOSPC (28 on every platform), Windows ERROR_HANDLE_DISK_FULL (39) / ERROR_DISK_FULL (112).+_DISK_FULL_ERRNO = re.compile(r"[A-Z][A-Za-z0-9_]*: \[(?:Errno 28|WinError (?:39|112))\]")# ---- end iuf c1 ----@@ -89,12 +92,15 @@ def _restart_incomplete(receipt: dict[str, Any]) -> bool:def update_failure_class(receipt: dict[str, Any], stages: list[dict[str, Any]], outcome: str) -> str:- """Why a failed/refused run stopped, from fields the FINAL receipt already carries.+ """Why a failed/refused/partial run stopped, from fields the FINAL receipt already carries.- The parked copy (update_receipt._metric_receipt) keeps outcome, stages, the admission step and- fleet states but no stop_reason / exit_code / gateway_restart, so a parked run can only be told- apart by its stages; full receipts carry every field read here (``schema`` marks one).+ A pre-apply exit names itself (``stop_class``, recorded on the line before the exit by+ update_receipt.record_stop_reason); only a run with no apply mark reads it, so a reason can+ never outlive the exit that recorded it. Parked copies (update_receipt._metric_receipt) carry+ every field read here except the free text; copies parked by older releases have no ``schema``."""+ from .shared_metrics_contract import UPDATE_STOP_CLASSES+if outcome not in {"failed", "refused"}:return "none"raw_steps = receipt.get("steps")@@ -108,6 +114,13 @@ def update_failure_class(receipt: dict[str, Any], stages: list[dict[str, Any]],exc_type = match.group(1) if match else ""if exc_type == "KeyboardInterrupt" or exit_code == 130:return "interrupted"+ if receipt.get("outcome") == "partial" and receipt.get("user_action"):+ # Committed; only the user's stashed changes are owed (record_user_action, exit 1). Since C3+ # this is the only ``partial`` a receipt gets; older releases' verification wrote it too.+ return "local_changes_parked"+ stop_class = receipt.get("stop_class")+ if stop_class in UPDATE_STOP_CLASSES and not any(s["name"] == "apply" for s in stages):+ return stop_classif outcome == "refused":# Exit 2 at the command boundary is the updater's refusal convention; on main the only# open-receipt exit 2 is another updater holding the lock (update_finish).@@ -125,6 +138,10 @@ def update_failure_class(receipt: dict[str, Any], stages: list[dict[str, Any]],return "restart_failed" # a skipped restart left the fleet owing one (completion exit 1)if by_reason := next((cls for prefix, cls in _STOP_REASON_PREFIX_CLASSES if reason.startswith(prefix)), None):return by_reason+ if _DISK_FULL_ERRNO.match(reason):+ return "disk_full"+ if exc_type == "PermissionError":+ return "permission_denied"if exc_type:return next((cls for types, cls in _EXCEPTION_TYPE_CLASSES if exc_type in types), "exception")marked = {s["name"] for s in stages}@@ -218,6 +235,17 @@ def _apply_mode(receipt: dict[str, Any], stages: list[dict[str, Any]]) -> str:return "unknown"+def _committed_with_work_owed(receipt: dict[str, Any]) -> bool:+ """The code moved (an apply mark that did not fail), and the run closed owing work, not failed:+ interrupted after the commit point (finalize_interrupted_update_receipt) or the user's parked+ changes (record_user_action -> ``partial``). Follow-ups alone already finalize ``success`` (C3)."""+ applied = any(isinstance(mark, dict) and mark.get("name") == "apply" and mark.get("outcome") != "failed"+ for mark in receipt.get("stages") or ())+ owed = receipt.get("outcome") == "interrupted" or (+ receipt.get("outcome") == "partial" and bool(receipt.get("user_action")))+ return applied and owed++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@@ -228,18 +256,24 @@ def update_receipt_fields(receipt: dict[str, Any]) -> tuple[dict[str, str], listoutcome = _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"+ if _committed_with_work_owed(receipt):+ outcome = "partial"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+ failure_class = update_failure_class(receipt, stages, "failed" if outcome == "partial" else outcome)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",+ "failed_stage": (+ # The parked autostash is the apply's last step (update_cmd._pull_updates restores it).+ "apply" if failure_class == "local_changes_parked"+ else _failed_stage(stages) if outcome in {"failed", "refused", "partial"} else "none"),"from_version_age_bucket": version_age_bucket(age_ms),"kind": "desktop" if receipt.get("initiator") == "desktop" else "cli","outcome": outcome,# ---- iuf c1 ----- "failure_class": update_failure_class(receipt, stages, outcome),+ "failure_class": failure_class,# ---- end iuf c1 ----}if run["outcome"] == "refused" and not stages:diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex a7563760704..f9a4b8f4bcd 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -21,7 +21,7 @@ from typing import NoReturnfrom hermes_cli._subprocess_compat import no_prompt_git_kwargs as _no_prompt_git_kwargsfrom hermes_cli.config import get_hermes_home # noqa: F401 (re-exported; patched via update_cmd)from hermes_cli import update_handoff as _update_handoff-from hermes_cli.update_cmd_common import _best_effort+from hermes_cli.update_cmd_common import _best_effort, _record_stop# Captured BEFORE a checkout swap: parent transport/lifecycle never imports new code.from hermes_cli.update_completion import run_completionfrom hermes_cli.update_channel import adopt_retired_channel@@ -871,6 +871,7 @@ def _reconcile_diverged_checkout(git_cmd, branch: str, pre_pull_sha, *, target_rprint("✗ Merge conflict between local commits and upstream — update stopped, nothing was changed.")print(f" Resolve manually: cd {_m().PROJECT_ROOT} && git merge origin/{branch}")print(" Then re-run the update. Local work is untouched.")+ _record_stop("merge_conflict")sys.exit(1)return# Same branch and proven non-ancestor: an upstream force-push/rebase may lose nothing,@@ -913,6 +914,7 @@ def _reconcile_diverged_checkout(git_cmd, branch: str, pre_pull_sha, *, target_rif reset_result.stderr.strip():print(f" {reset_result.stderr.strip()}")print(f" Try manually: git fetch origin && git reset --hard origin/{branch}")+ _record_stop("checkout_move_failed")sys.exit(1)@@ -933,7 +935,7 @@ def _rollback_if_pulled_syntax_error(git_cmd, pre_pull_sha, *, rollback_branch=Ndef _roll_back_broken_update(git_cmd, pre_pull_sha, failing_path, syntax_error, *, rollback_branch=None,header="✗ Pulled code has a syntax error in a critical file:",- _windows_gateway_resume=None) -> NoReturn:+ _windows_gateway_resume=None, stop_class="syntax_rollback") -> NoReturn:"""Restore the checkout to *pre_pull_sha* after a startup file failed the syntax check, then``sys.exit(1)``."""print()@@ -1003,6 +1005,7 @@ def _roll_back_broken_update(git_cmd, pre_pull_sha, failing_path, syntax_error,else:print(" Could not capture pre-pull SHA — recover manually with:")print(f" cd {_m().PROJECT_ROOT} && git reflog && git reset --hard <prev-sha>")+ _record_stop(stop_class)sys.exit(1)@@ -1023,6 +1026,7 @@ def _refuse_unselected_head(git_cmd, target_sha: str, unmoved: str | None) -> Noif (landed := _landed_off_target(git_cmd, target_sha)) not in (None, unmoved):print(f"✗ The checkout landed on {landed[:10]}, not the selected commit {target_sha[:10]} ""(a ref moved during the update).")+ _record_stop("head_moved")sys.exit(1)@@ -1078,6 +1082,7 @@ def _move_checkout_to(git_cmd, branch, merge_ref, target_sha, pre_pull_sha) -> Nif ancestry_detail:print(f" {ancestry_detail}")print(" Resolve the Git error and re-run `hermes update`; no reset was attempted.")+ _record_stop("git_index_locked" if "index.lock" in detail else "checkout_move_failed")sys.exit(1)@@ -1105,6 +1110,7 @@ def _pull_updates(if not is_object_id(target_sha):# The marker must name the commit git moves to, or a killed move is unrecoverable.print(f"✗ Could not resolve {merge_ref} to a commit. No update was applied.")+ _record_stop("target_unresolved")sys.exit(1)movement_baseline = _update_movement_baseline(git_cmd, pre_pull_sha, pre_sync_sha, rollback_branch, target_sha)@@ -1112,12 +1118,14 @@ def _pull_updates(# Channel verification is a precondition: refuse before anything moves.print(f"✗ {merge_ref} resolves to {target_sha[:10]}, not the selected channel commit "f"{expected_sha[:10]}. No update was applied.")+ _record_stop("head_moved")sys.exit(1)# The commit point: the tail, the fleet restart and the marker are durable BEFORE git writes.refused = _commit.arm_commit_point(git_cmd, _m().PROJECT_ROOT, target_sha, pre=pre_pull_sha,target=target_sha, stash=auto_stash_ref)if refused:print(f"✗ {refused}.")+ _record_stop("commit_point_refused")sys.exit(1)try:# The paused gateways' tree gate must know this move's target before git writes a file.@@ -1276,6 +1284,7 @@ def _exit_after_failed_branch_switch(print(f" ℹ️ Local changes preserved in stash (ref: {auto_stash_ref})")print(" Restore manually with: git stash apply")_clear_pending_autostash()+ _record_stop("checkout_move_failed")sys.exit(1)# Nothing moved: restore the stash before bailing so the user isn't stranded.if auto_stash_ref is not None:@@ -1284,10 +1293,13 @@ def _exit_after_failed_branch_switch(checkout_move=_moves_for(_windows_gateway_resume))if track_result.args in (_ARM_REFUSED, _REF_MOVED):print(f"✗ {detail}.")+ _record_stop("commit_point_refused" if track_result.args is _ARM_REFUSED else "head_moved")else:print(f"✗ Branch '{branch}' does not exist locally or on origin.")if detail:print(f" {detail.splitlines()[0]}")+ _record_stop("checkout_move_failed" if any(_resolved_commit(git_cmd, ref) for ref in (+ f"refs/heads/{branch}", f"origin/{branch}")) else "branch_missing")sys.exit(1)@@ -1330,6 +1342,7 @@ def _apply_parked_branch_guard(print()print(f"⚠ Update finished — code update SKIPPED{_branch_head_suffix(git_cmd, _m().PROJECT_ROOT)}")_m()._resume_windows_gateways_after_update(_windows_gateway_resume)+ _record_stop("parked_branch_blocked")sys.exit(1)if not switch_block_reason.startswith("unmerged:"):print(f" ⚠ Checkout was parked on '{current_branch}' (fully merged) — switching back to {branch}...")@@ -1345,6 +1358,7 @@ def _apply_parked_branch_guard(# --branch typos used to surface via the checkout failing, which this path skips.if _git_run(git_cmd, ["rev-parse", "--verify", "--quiet", f"origin/{branch}"]).returncode != 0:print(f"✗ Branch '{branch}' does not exist locally or on origin.")+ _record_stop("branch_missing")sys.exit(1)print(f" ℹ On branch '{current_branch}' — updating it in place from "@@ -1453,7 +1467,8 @@ def _prepare_checkout_for_update(_clear_pending_autostash()_roll_back_broken_update(git_cmd, pre_sync_sha, broken.path, broken.error,header=_upstream_broken_header(broken),- _windows_gateway_resume=_windows_gateway_resume)+ _windows_gateway_resume=_windows_gateway_resume,+ stop_class="target_syntax_error")post_sync_sha = _capture_head_sha(git_cmd, _m().PROJECT_ROOT)if pre_sync_sha and post_sync_sha and pre_sync_sha != post_sync_sha:synced_count = _count_commits_between(@@ -1567,6 +1582,7 @@ def _prepare_git_command(*, checkout_move=None) -> tuple[bool, list, bool]:if use_zip_update and sys.platform != "win32":print("✗ Not a git repository. Please reinstall:")print(" curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash")+ _record_stop("not_git_checkout")sys.exit(1)from hermes_cli._subprocess_compat import expose_pm_git@@ -1624,6 +1640,7 @@ def _verify_head_after_pull(f"git -C {_m().PROJECT_ROOT} checkout {branch} && hermes update")_commit.disarm_commit_obligations() # nothing moved: no tail is owed (refused if HEAD did)_m()._resume_windows_gateways_after_update(_windows_gateway_resume)+ _record_stop("detached_head")sys.exit(1)# HEAD must be on the target or "Code updated!" is a lie; an IN-PLACE update is the one@@ -1638,6 +1655,7 @@ def _verify_head_after_pull(" Switch to the target branch and retry: "f"git -C {_m().PROJECT_ROOT} checkout {branch} && hermes update")_m()._resume_windows_gateways_after_update(_windows_gateway_resume)+ _record_stop("unexpected_branch")sys.exit(1)return post_pull_sha@@ -1679,6 +1697,8 @@ def _handle_update_called_process_error(print(f"✗ {stage}.")print(f" Details: {e}")_print_called_process_error_tail(e)+ if stop := _completion_receipt.git_error_stop_class(e):+ _record_stop(stop)_finalize_receipt("failed", 'Update receipt finalize failed: %s')sys.exit(1)@@ -1736,6 +1756,7 @@ def _apply_pulled_update(if pinned is not None and observed != pinned:print("✗ Checkout no longer matches the selected channel commit. No completion was applied.")_m()._resume_windows_gateways_after_update(_windows_gateway_resume)+ _record_stop("head_moved")sys.exit(1)completion_request["expected_sha"] = pinned or observed_complete_source_update(completion_request)@@ -1753,6 +1774,7 @@ def _cmd_update_impl(args, gateway_mode: bool):root = _m().PROJECT_ROOTprint(f"✗ Cannot update while a Git {git_operation} is in progress in {root}.")print(f" Finish it or run `git {git_operation} --abort`, then re-run `hermes update`.")+ _record_stop("git_in_progress", without_receipt="failed") # before the receipt opens: a metrics row onlysys.exit(1)opts = _resolve_update_options(args, gateway_mode)@@ -1813,6 +1835,7 @@ def _cmd_update_impl(args, gateway_mode: bool):except (OSError, ValueError, subprocess.SubprocessError) as exc:print(f"✗ Could not resolve the {selected_channel} source channel: {exc}. No update was applied.")_m()._resume_windows_gateways_after_update(_windows_gateway_resume)+ _record_stop("channel_unresolved")sys.exit(1)if target.retired:print(f"→ {selected_channel} retired; source destination: {target.channel}")@@ -1891,6 +1914,8 @@ def _cmd_update_impl(args, gateway_mode: bool):" should_include_obj' in https://hermes-agent.nousresearch.com/docs/getting-started/updating")_print_fetch_failure(fetch_result.stderr)_m()._resume_windows_gateways_after_update(_windows_gateway_resume)+ _record_stop("git_timeout" if fetch_result.returncode == 124 else "disk_full"+ if "No space left on device" in (fetch_result.stderr or "") else "fetch_failed")sys.exit(1)current_branch = _current_branch_name(git_cmd, check=True)diff --git a/hermes_cli/update_cmd_commit.py b/hermes_cli/update_cmd_commit.pyindex cc4abd2e3b6..4331ad2e13b 100644--- a/hermes_cli/update_cmd_commit.py+++ b/hermes_cli/update_cmd_commit.py@@ -36,6 +36,7 @@ from hermes_cli._early_recovery import (restore_interrupted_pull,write_durable_text,)+from hermes_cli.update_cmd_common import _record_stopfrom hermes_cli.update_custody import run_gitlogger = logging.getLogger("hermes_cli.update_cmd")@@ -601,10 +602,12 @@ def preflight_refusal(git_cmd, root: Path, target_ref: str, critical_files) -> sexcept ImportError:passexcept Exception as exc: # health: allow BLE001 -- fail closed: any probe error refuses before the first move+ _record_stop("venv_foreign_owner")return f"✗ {exc}" # pm's refusal carries its own remediation textbroken = target_syntax_error(git_cmd, root, target_ref, critical_files)if broken is not None:path, error = broken+ _record_stop("target_syntax_error")return (f"✗ The update target has a syntax error in a critical file:\n {path}\n "+ "\n ".join(error.splitlines()[:6]))return Nonediff --git a/hermes_cli/update_cmd_common.py b/hermes_cli/update_cmd_common.pyindex 1de471b348f..677ae5226e3 100644--- a/hermes_cli/update_cmd_common.py+++ b/hermes_cli/update_cmd_common.py@@ -1,12 +1,30 @@"""Shared leaf helpers for the ``hermes update`` modules (no Hermes imports; no cycle)."""import logging+import sysfrom contextlib import contextmanager# Log-record parity with the origin module.logger = logging.getLogger("hermes_cli.update_cmd")+def _record_stop(reason: str, *, without_receipt: "str | None" = None) -> None:+ """Name the exit about to stop this update as one closed token (see update_receipt.record_stop_reason).++ ``without_receipt`` (``refused``/``failed``) is for an exit that fires before the receipt+ opens: a metrics row only. The receipt module is read from ``sys.modules``, never imported:+ an older updater can load this tree after the swap while its own, older ``update_receipt``+ (without these calls) stays loaded.+ """+ receipt = sys.modules.get("hermes_cli.update_receipt")+ if without_receipt is None:+ record = getattr(receipt, "record_stop_reason", None)+ if record is not None:+ record(reason)+ elif (record := getattr(receipt, "record_stop_without_receipt", None)) is not None:+ record(reason, without_receipt)++@contextmanagerdef _best_effort(message: str):"""Run a non-critical update step; swallow ``Exception`` and log it at debug.diff --git a/hermes_cli/update_cmd_git.py b/hermes_cli/update_cmd_git.pyindex 7ceb1307316..883f87e1707 100644--- a/hermes_cli/update_cmd_git.py+++ b/hermes_cli/update_cmd_git.py@@ -14,6 +14,7 @@ from pathlib import Pathfrom typing import Optionalfrom hermes_cli._subprocess_compat import NO_LAZY_FETCH_ENV, noninteractive_git_env, windows_hide_flags+from hermes_cli.update_cmd_common import _record_stoplogger = logging.getLogger("hermes_cli.update_cmd") # log-record parity with the origin module@@ -134,6 +135,7 @@ def _park_detached_head(git_cmd, cwd, branch) -> None:f"to {rescue_ref} failed.")print(f" Update stopped so those commits are not orphaned. Keep them with: "f"git -C {cwd} branch <name> {sha[:12]}")+ _record_stop("detached_head")sys.exit(1)count = (_git_run(git_cmd, ["rev-list", "--count", sha, "--not", "--branches", "--tags", "--remotes"],cwd).stdout or "").strip()diff --git a/hermes_cli/update_cmd_stash.py b/hermes_cli/update_cmd_stash.pyindex 75bde52b835..4f5fb6648ed 100644--- a/hermes_cli/update_cmd_stash.py+++ b/hermes_cli/update_cmd_stash.py@@ -11,6 +11,8 @@ from datetime import datetime, timedelta, timezonefrom pathlib import Pathfrom typing import Optional+from hermes_cli.update_cmd_common import _record_stop+# Log-record parity with the origin module.logger = logging.getLogger("hermes_cli.update_cmd")@@ -415,6 +417,7 @@ def _reject_unsafe_stash_restore(print(f" Inspect them with: git stash show --stat {stash_ref}")print(f" Restore manually after fixing them: git stash apply {stash_ref}")_clear_pending_autostash() # named right above, and the update fails+ _record_stop("stash_restore_rejected")raise SystemExit(1)diff --git a/hermes_cli/update_cmd_zip.py b/hermes_cli/update_cmd_zip.pyindex 11ef7bc699c..6c8a8c451df 100644--- a/hermes_cli/update_cmd_zip.py+++ b/hermes_cli/update_cmd_zip.py@@ -17,6 +17,7 @@ from typing import Collection, Optionalfrom hermes_cli._early_recovery import _keep_asidefrom hermes_cli._early_recovery_zip import (ZIP_SWAP_JOURNAL, restore_interrupted_zip_swap, write_zip_swap_journal, zip_entry_identity, zip_swap_owner_lock)+from hermes_cli.update_cmd_common import _record_stop# Log-record parity with the origin module.logger = logging.getLogger("hermes_cli.update_cmd")@@ -342,6 +343,7 @@ def _abort_zip_update_if_dirty_tree() -> None:print(" Overlaying the ZIP would overwrite uncommitted edits and permanently delete untracked files.")print(_STASH_HINT)print(" To inspect: git status --porcelain")+ _record_stop("local_changes_blocked")_m().sys.exit(1)@@ -514,6 +516,7 @@ def _journaled_stage_and_swap(extracted: str, entries: list[str], root: Path, taprint(f"✗ ZIP fallback aborted before the swap: {recheck_reason}.")print(" Files appeared in the checkout while the update was downloading; committing the swap would delete them.")print(_STASH_HINT)+ _record_stop("local_changes_blocked")_m().sys.exit(1)# Pre-commit gate: a target whose startup modules do not compile is refused untouched, judged# under the interpreter the target admits (``startup_syntax_error``, review N15).@@ -545,6 +548,18 @@ def _journaled_stage_and_swap(extracted: str, entries: list[str], root: Path, tareturn staged+def _zip_stop_class(exc: BaseException, *, downloaded: bool) -> str:+ """Closed stop token for a failed ZIP update: by exception type and errno, never its text."""+ import errno++ if getattr(exc, "errno", None) == errno.ENOSPC or (+ isinstance(exc, RuntimeError) and str(exc).startswith("not enough free disk space")):+ return "disk_full" # _require_staging_space's own refusal, or ENOSPC mid-copy+ if isinstance(exc, SyntaxError):+ return "target_syntax_error" # the pre-commit gate refused the extracted tree; nothing moved+ return "zip_failed" if downloaded else "download_failed"++def _download_and_swap_zip(branch: str, zip_url: str, target_sha: str | None = None) -> Optional[str]:"""Download the source ZIP for *branch* and two-phase swap it into the checkout; return the commit itinstalled: the archive's own, which must equal ``target_sha`` when one is pinned.@@ -558,9 +573,11 @@ def _download_and_swap_zip(branch: str, zip_url: str, target_sha: str | None = Nfrom urllib.request import urlretrieveprint("→ Downloading latest version...")tmp_dir = tempfile.mkdtemp(prefix="hermes-update-")+ downloaded = Falsetry:zip_path = os.path.join(tmp_dir, f"hermes-agent-{branch}.zip")urlretrieve(zip_url, zip_path)+ downloaded = Trueprint("→ Extracting...")_extract_zip_safely(zip_path, tmp_dir)# The installed identity comes from the downloaded bytes (``git archive``'s comment), pinned or@@ -589,6 +606,7 @@ def _download_and_swap_zip(branch: str, zip_url: str, target_sha: str | None = N# Two-phase replace commits all or rolls all back, so no mixed tree here — don't push a needless reinstall.print(" Your existing install was left in place.")print(" Re-run `hermes update` to retry; if the agent won't start, reinstall from https://hermes-agent.nousresearch.com")+ _record_stop(_zip_stop_class(e, downloaded=downloaded))_m().sys.exit(1)finally:shutil.rmtree(tmp_dir, ignore_errors=True)@@ -614,6 +632,7 @@ def _update_via_zip(args, *, had_desktop_app_before_update: bool = False,"or NTFS filter holding files open) and rerun `hermes update "f"--branch {branch}`, or update against main with `hermes update`.")+ _record_stop("branch_unsupported")_m().sys.exit(1)_abort_zip_update_if_dirty_tree()# Older callers lack the snapshot/receipt/lifecycle handoff. Refuse before swap.diff --git a/hermes_cli/update_receipt.py b/hermes_cli/update_receipt.pyindex 4682bff304c..7c08283143b 100644--- a/hermes_cli/update_receipt.py+++ b/hermes_cli/update_receipt.py@@ -35,6 +35,7 @@ import jsonimport loggingimport osimport re+import subprocessimport sysimport timeimport uuid@@ -516,6 +517,61 @@ def record_gateway_restart(**kwargs: Any) -> None:_record("gateway_restart_result", "gateway restart result", **kwargs)+def record_stop_reason(reason: str) -> None:+ """Name the exit that is about to stop this run, as one closed token (``stop_class``).++ Called on the line before the ``sys.exit``/raise it names, so the last one recorded is the+ exit that fired. The token must be one of ``shared_metrics_contract.UPDATE_STOP_CLASSES``+ (anything else is ignored by the metric); the human ``stop_reason`` and printed text are+ untouched. No-op when no receipt is open; never raises.+ """+ _record("fact", f"update stop {reason}", "stop_class", reason)+++def git_error_stop_class(exc: BaseException) -> Optional[str]:+ """The closed stop token for a git ``CalledProcessError`` that is about to end the run, or None.++ Reads only the failed argv and fixed git/Hermes phrases in its output, never stores either.+ """+ if not isinstance(exc, subprocess.CalledProcessError):+ return None+ output = exc.stderr or exc.output or ""+ output = output.decode("utf-8", "replace") if isinstance(output, bytes) else str(output)+ argv = [str(part) for part in exc.cmd] if isinstance(exc.cmd, (list, tuple)) else str(exc.cmd or "").split()+ if "index.lock" in output and "File exists" in output:+ return "git_index_locked" # another git (or a killed one, #132089) holds the index lock+ if exc.returncode == 124 and "timed out after" in output:+ return "git_timeout" # update_cmd._git_run's own timeout text+ if "No space left on device" in output:+ return "disk_full"+ if "stash" in argv:+ return "local_changes_blocked" # update_cmd_stash._push_stash saved nothing+ if {"checkout", "merge", "reset"} & set(argv):+ return "checkout_move_failed"+ return None+++def record_stop_without_receipt(reason: str, outcome: str) -> None:+ """Count an exit that fires before this run's receipt opens, in shared metrics only.++ No receipt is written, so the exit behaves exactly as before: at the update-lock refusal+ ``latest.json`` and the running record belong to the update holding the lock (opening one+ would replace its pointer and reconcile its archive), and the Git-operation refusal runs before+ the receipt, plan and snapshot by design. The row is derived from the same fields a final+ receipt carries (``outcome`` is ``refused`` or ``failed``). Never raises.+ """+ with suppress(Exception):+ now = _utc_now_iso()+ data = {+ "schema": 1, "update_id": uuid.uuid4().hex, "started_at": now, "finished_at": now,+ "outcome": "refused" if outcome == "refused" else "failed",+ "stop_class": reason, "pre_update": {}, "stages": [], "steps": [], "fleet": [],+ }+ from hermes_cli.observability.shared_metrics_update import record_update_receipt++ record_update_receipt(data)++def finalize_update_receipt(outcome: str, fleet: list | None = None, stop_reason: str = "") -> Optional[Path]:"""Finalize + persist the receipt (``success``/``partial``/``failed``/``refused``); path or None.@@ -627,10 +683,28 @@ def _collection_enabled_now() -> Optional[bool]:return isinstance(config, dict) and config.get("enabled") is True+#: The leading label of a stop reason the parked copy may keep: an exception type name or a fixed+#: phrase Hermes writes, plus an errno token; never the message after it.+_PARKED_REASON_LABEL = re.compile(r"[A-Za-z_][A-Za-z0-9_ ]{0,60}:(?: \[(?:Errno|WinError) \d+\])?")+_STOP_CLASS_TOKEN = re.compile(r"[a-z][a-z0-9_]{0,39}")++def _metric_receipt(data: dict[str, Any]) -> dict[str, Any]:- """Only what shared_metrics_update.update_receipt_fields reads; never argv or step text."""- pre = data.get("pre_update") if isinstance(data.get("pre_update"), dict) else {}+ """Only what shared_metrics_update.update_receipt_fields reads; never argv or step text.++ Every field the classifier reads is kept in closed form so a parked run classifies exactly as+ the same run finalized in-process: the exit's ``stop_class`` token, the exit code, the stop+ reason's leading label (``-`` for any other text), and flags for the restart/user-action facts.+ """+ raw_pre, raw_restart, raw_reason = (data.get(key) for key in ("pre_update", "gateway_restart", "stop_reason"))+ pre: dict[str, Any] = raw_pre if isinstance(raw_pre, dict) else {}+ restart: dict[str, Any] = raw_restart if isinstance(raw_restart, dict) else {}+ reason: str = raw_reason if isinstance(raw_reason, str) else ""+ label = _PARKED_REASON_LABEL.match(reason)+ stop_class = data.get("stop_class")+ exit_code = data.get("exit_code")return {+ "schema": data.get("schema"),"update_id": data.get("update_id"), "started_at": data.get("started_at"),"finished_at": data.get("finished_at"), "outcome": data.get("outcome"),"initiator": "desktop" if data.get("initiator") == "desktop" else None,@@ -644,6 +718,15 @@ def _metric_receipt(data: dict[str, Any]) -> dict[str, Any]:for step in data.get("steps") or () if isinstance(step, dict) and step.get("name") == "admission"],"fleet": [{"state": row.get("state")} for row in data.get("fleet") or () if isinstance(row, dict)],+ "stop_class": stop_class if isinstance(stop_class, str) and _STOP_CLASS_TOKEN.fullmatch(stop_class) else None,+ "exit_code": exit_code if isinstance(exit_code, int) and not isinstance(exit_code, bool) else None,+ "stop_reason": label.group(0) if label else ("-" if reason else ""),+ "user_action": bool(data.get("user_action")),+ "gateway_restart": {key: bool(restart.get(key)) for key in ("incomplete", "phase_error", "failed_units")},+ "runtime_outcomes": [+ {"outcome": "failed"} for row in data.get("runtime_outcomes") or ()+ if isinstance(row, dict) and row.get("outcome") == "failed"+ ],}