Skip to content

The agent that grows with you

fix(update): pre-apply exits that read exception/subprocess_failed name their reason

Teknium2379b2e2eb4e
diff --git a/hermes_cli/observability/schemas/hermes.shared_metrics.v4.schema.json b/hermes_cli/observability/schemas/hermes.shared_metrics.v4.schema.json
index 622b208b056..3b8cc2f8994 100644
--- a/hermes_cli/observability/schemas/hermes.shared_metrics.v4.schema.json
+++ b/hermes_cli/observability/schemas/hermes.shared_metrics.v4.schema.json
@@ -2721,6 +2721,7 @@
"channel_unresolved",
"checkout_move_failed",
"commit_point_refused",
+ "config_unreadable",
"deps_failed",
"detached_head",
"disk_full",
@@ -2729,6 +2730,7 @@
"fetch_failed",
"fleet_stale",
"fleet_unverified",
+ "gateway_pause_failed",
"git_failed",
"git_in_progress",
"git_index_locked",
diff --git a/hermes_cli/observability/shared_metrics_contract.py b/hermes_cli/observability/shared_metrics_contract.py
index 3aa140cea62..a9af4e04797 100644
--- a/hermes_cli/observability/shared_metrics_contract.py
+++ b/hermes_cli/observability/shared_metrics_contract.py
@@ -493,6 +493,7 @@ UPDATE_STOP_CLASSES = frozenset({
"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
+ "config_unreadable", # config.yaml could not be read or parsed, so the update channel is unknown
"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
@@ -500,6 +501,7 @@ UPDATE_STOP_CLASSES = frozenset({
"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
+ "gateway_pause_failed", # Windows: the gateways could not be paused safely before the venv moves
"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)
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py
index 7b8223900f7..e6f7c4214b9 100644
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@ -1774,6 +1774,25 @@ def _apply_pulled_update(
_complete_source_update(completion_request)
+def _pause_gateways_for_update(opts):
+ """Windows pauses here (venv locks); Linux/macOS only arm a pause the commit point performs."""
+ try:
+ return _m()._pause_windows_gateways_for_update() or _posix_pause.arm_pause(
+ no_gateway_restart=opts.no_gateway_restart)
+ except RuntimeError: # update_cmd_windows._abort_on_error / ServicePauseFailed: nothing moved
+ _record_stop("gateway_pause_failed")
+ raise
+
+
+def _update_run_channel(args) -> str:
+ """``_source_update_channel`` for this run, naming the exit when config.yaml decides nothing."""
+ try:
+ return _source_update_channel(args)
+ except (RuntimeError, ValueError) as exc: # unreadable config.yaml / an invalid configured channel name
+ _record_stop("config_unreadable" if isinstance(exc, RuntimeError) else "channel_unresolved")
+ raise
+
+
def _cmd_update_impl(args, gateway_mode: bool):
"""Apply the update; the command boundary owns errors, receipts and stdio."""
# Marks this frame as the CURRENT updater for
@@ -1816,9 +1835,7 @@ def _cmd_update_impl(args, gateway_mode: bool):
_record_pre_update_backup_outcome(args, pre_update_snapshot_id)
_record_snapshot_stage(args, pre_update_snapshot_id)
- # Windows pauses here (venv locks); Linux/macOS only arm a pause the commit point performs.
- _windows_gateway_resume = _m()._pause_windows_gateways_for_update() or _posix_pause.arm_pause(
- no_gateway_restart=opts.no_gateway_restart)
+ _windows_gateway_resume = _pause_gateways_for_update(opts)
if _windows_gateway_resume:
import atexit as _atexit
_atexit.register(_m()._resume_windows_gateways_after_update, _windows_gateway_resume)
@@ -1840,7 +1857,7 @@ def _cmd_update_impl(args, gateway_mode: bool):
target_ref = f"origin/{branch}"
release_sha = None
target_repository = None
- selected_channel = _source_update_channel(args)
+ selected_channel = _update_run_channel(args)
if not getattr(args, "branch", None):
from hermes_cli.release_channels import retrying_reads
from hermes_cli.source_releases import resolve_source_target
diff --git a/hermes_cli/update_cmd_commit.py b/hermes_cli/update_cmd_commit.py
index 4331ad2e13b..f2af0edee18 100644
--- a/hermes_cli/update_cmd_commit.py
+++ b/hermes_cli/update_cmd_commit.py
@@ -497,7 +497,12 @@ def read_target_files(git_cmd, root: Path, target_ref: str, relpaths) -> dict[st
names = list(dict.fromkeys(relpaths))
found: dict[str, bytes | None] = dict.fromkeys(names)
request = "".join(f"{target_ref}:{rel}\n" for rel in names).encode("utf-8")
- cp = run_git(git_cmd, ["cat-file", "--batch"], cwd=str(root), input=request, capture_output=True, timeout=120)
+ try:
+ cp = run_git(git_cmd, ["cat-file", "--batch"], cwd=str(root), input=request, capture_output=True, timeout=120)
+ except subprocess.TimeoutExpired:
+ # A blobless install (install.sh clones --filter=blob:none) lazily fetches each changed blob
+ # in its own round trip; on a slow link that outlasts the limit. Unread, like an absent file.
+ return found
out, pos = (cp.stdout or b"") if cp.returncode == 0 else b"", 0
for rel in names:
end = out.find(b"\n", pos)
diff --git a/tests/hermes_cli/test_shared_metrics_update_stop_reasons.py b/tests/hermes_cli/test_shared_metrics_update_stop_reasons.py
index 504c6c1d210..f8dc4c7e143 100644
--- a/tests/hermes_cli/test_shared_metrics_update_stop_reasons.py
+++ b/tests/hermes_cli/test_shared_metrics_update_stop_reasons.py
@@ -226,6 +226,79 @@ def test_a_checkout_move_names_a_held_index_lock_apart_from_a_permission_error(r
assert git("rev-parse", "HEAD") == old
[email protected](("site", "raised", "expected"), [
+ ("channel", RuntimeError("Your settings file cannot be read"), "config_unreadable"),
+ ("channel", ValueError("Invalid channel name"), "channel_unresolved"),
+ ("pause", RuntimeError("Could not stop Windows gateway service x"), "gateway_pause_failed"),
+])
+def test_an_exception_before_the_apply_names_its_exit_through_the_command_boundary(
+ rows, monkeypatch, site, raised, expected):
+ """Invariant: an exception that leaves ``_cmd_update_impl`` before the apply mark is recorded by
+ the exit that raised it; the command boundary (main.cmd_update) never has to read its type name,
+ so it never collapses to ``exception``."""
+ from hermes_cli import main, update_cmd, update_lock, update_owning_install
+
+ def boom(*_a, **_k):
+ raise raised
+
+ class Free:
+ holder = None
+
+ def __init__(self, **_kw):
+ pass
+
+ def acquire(self):
+ return True
+
+ def release(self):
+ pass
+
+ 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", Free)
+ monkeypatch.setattr(update_cmd, "git_operation_in_progress", lambda root: None)
+ monkeypatch.setattr(update_cmd._check, "clear_git_debris", lambda root: None)
+ monkeypatch.setattr(update_cmd, "_resolve_update_options", lambda *_: update_cmd._UpdateOptions(
+ pre_update_version=None, gw_input_fn=None, assume_yes=True, keep_stash=False,
+ switch_branch=False, discard_local_changes=False, no_gateway_restart=True))
+ monkeypatch.setattr(update_cmd, "_begin_update_receipt_and_plan",
+ lambda args: update_receipt.begin_update_receipt())
+ monkeypatch.setattr(main, "_run_pre_update_backup", lambda args: None)
+ monkeypatch.setattr(main, "_pause_windows_gateways_for_update", boom if site == "pause" else lambda: None)
+ monkeypatch.setattr(main, "_desktop_packaged_executable", lambda d: None)
+ monkeypatch.setattr(main, "_desktop_dist_exists", lambda d: False)
+ monkeypatch.setattr(main, "_installed_desktop_apps", list)
+ monkeypatch.setattr(update_cmd, "_prepare_git_command", lambda **_: (False, ["git"], False))
+ monkeypatch.setattr(update_cmd, "_source_completion_request", lambda *a: {"home": str(rows.home)})
+ monkeypatch.setattr(main, "_resolve_update_branch", lambda args: "main")
+ monkeypatch.setattr(update_cmd, "_source_update_channel", boom if site == "channel" else lambda args: "main")
+ with pytest.raises(type(raised)):
+ main.cmd_update(SimpleNamespace(gateway=False, branch=None, channel=None))
+
+ (run,) = rows.runs()
+ assert (run["failure_class"], run["outcome"], run["apply_mode"]) == (expected, "failed", "unknown")
+ assert contract.counter_dimensions_are_valid(contract.UPDATE_RUN_METRIC, run)
+
+
+def test_a_timed_out_target_read_skips_the_preflight_instead_of_failing_the_update(monkeypatch):
+ """Invariant: the startup-syntax preflight reads the target from git's object store; a read that
+ times out (a blobless install lazily fetches each blob) is an unread file, never an exception
+ that ends the update as ``subprocess_failed``. The post-move syntax check stays the backstop."""
+ import subprocess
+
+ from pathlib import Path
+
+ from hermes_cli import update_cmd_commit
+
+ def slow(git_cmd, args, **kwargs):
+ raise subprocess.TimeoutExpired([*git_cmd, *args], 120)
+
+ monkeypatch.setattr(update_cmd_commit, "run_git", slow)
+ assert update_cmd_commit.target_syntax_error(["git"], Path("."), "a" * 40, ["cli.py", "run_agent.py"]) is None
+
+
@pytest.mark.parametrize("consent", ["on", "off"])
def test_the_bare_bootstrap_interpreter_parks_and_the_next_start_applies_the_gate(rows, consent, monkeypatch):
"""Invariant: a run finalized by the ``-I -S`` bootstrap interpreter (dependency preparation
diff --git a/website/docs/developer-guide/relay-shared-metrics.md b/website/docs/developer-guide/relay-shared-metrics.md
index 393f6a02b22..682d06e72f6 100644
--- a/website/docs/developer-guide/relay-shared-metrics.md
+++ b/website/docs/developer-guide/relay-shared-metrics.md
@@ -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`, `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 its apply stage mark records one closed token at the exit itself, and the run reads it (a few of these, `syntax_rollback`, `stash_restore_rejected`, `unexpected_branch`, `head_moved`, fire after git moved the tree and put it back or left it for the next launch to restore): `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, with `kind` `desktop` when the update marker names this run's Desktop hand-off (as its delegate or its hand-off partner), never merely because another update holds the marker. A git error that ended the checkout move reads `git_index_locked` only when git reports the index lock already exists; git refused permission to write it (or any file) reads `permission_denied`. 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 type (or one of Hermes' two fixed phrases) 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. |
+| `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 its apply stage mark records one closed token at the exit itself, and the run reads it (a few of these, `syntax_rollback`, `stash_restore_rejected`, `unexpected_branch`, `head_moved`, fire after git moved the tree and put it back or left it for the next launch to restore): `fetch_failed`, `git_timeout` (a network git call hit the updater's time limit), `channel_unresolved` (also an invalid channel name in config.yaml), `config_unreadable` (config.yaml cannot be read or parsed, so the channel is unknown), `gateway_pause_failed` (Windows: the gateways could not be paused safely before the venv moves), `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 startup-syntax preflight reads the target's critical files from git's object store; when that read times out (a blobless install lazily fetches each blob) the preflight skips them like absent files and the post-move syntax check decides, so the run no longer fails as `subprocess_failed`. 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, with `kind` `desktop` when the update marker names this run's Desktop hand-off (as its delegate or its hand-off partner), never merely because another update holds the marker. A git error that ended the checkout move reads `git_index_locked` only when git reports the index lock already exists; git refused permission to write it (or any file) reads `permission_denied`. 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 type (or one of Hermes' two fixed phrases) 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