Skip to content

The agent that grows with you

feat(observability): hermes.install.run from a local installer receipt

Teknium74e02253778e
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 33fc6023985..8c31546b612 100644
--- a/hermes_cli/observability/schemas/hermes.shared_metrics.v4.schema.json
+++ b/hermes_cli/observability/schemas/hermes.shared_metrics.v4.schema.json
@@ -273,6 +273,9 @@
},
{
"$ref": "#/$defs/feature_disabled_counter"
+ },
+ {
+ "$ref": "#/$defs/install_run_counter"
}
]
}
@@ -4956,6 +4959,106 @@
"minimum": 1
}
}
+ },
+ "install_run_counter": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "name",
+ "type",
+ "dimensions",
+ "value"
+ ],
+ "properties": {
+ "name": {
+ "const": "hermes.install.run"
+ },
+ "type": {
+ "const": "counter"
+ },
+ "dimensions": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "duration_bucket",
+ "failed_stage",
+ "failure_class",
+ "installer",
+ "outcome"
+ ],
+ "properties": {
+ "duration_bucket": {
+ "enum": [
+ "2m_to_5m",
+ "30s_to_2m",
+ "5m_to_15m",
+ "gte_15m",
+ "lt_30s"
+ ]
+ },
+ "failed_stage": {
+ "enum": [
+ "complete",
+ "config",
+ "gateway",
+ "none",
+ "other",
+ "prerequisites",
+ "products",
+ "python_deps",
+ "repository",
+ "setup",
+ "venv"
+ ]
+ },
+ "failure_class": {
+ "enum": [
+ "commit_not_on_branch",
+ "curl_missing",
+ "deps_install_failed",
+ "dir_not_checkout",
+ "download_digest_mismatch",
+ "download_failed",
+ "filesystem_error",
+ "gateway_failed",
+ "git_checkout_failed",
+ "git_clone_failed",
+ "git_extract_failed",
+ "git_fetch_failed",
+ "git_missing",
+ "git_reset_failed",
+ "interrupted",
+ "libstdcxx_missing",
+ "local_changes_blocked",
+ "none",
+ "other",
+ "products_build_failed",
+ "python_install_failed",
+ "setup_failed",
+ "unsupported_platform",
+ "uv_unusable"
+ ]
+ },
+ "installer": {
+ "enum": [
+ "install_ps1",
+ "install_sh",
+ "other"
+ ]
+ },
+ "outcome": {
+ "enum": [
+ "failed",
+ "success"
+ ]
+ }
+ }
+ },
+ "value": {
+ "type": "integer",
+ "minimum": 1
+ }
+ }
}
}
}
diff --git a/hermes_cli/observability/shared_metrics_contract.py b/hermes_cli/observability/shared_metrics_contract.py
index 2b3a65d2000..b700cef3efe 100644
--- a/hermes_cli/observability/shared_metrics_contract.py
+++ b/hermes_cli/observability/shared_metrics_contract.py
@@ -480,6 +480,26 @@ UPDATE_FAILURE_CLASSES = frozenset({
"unknown", # the reporter sent no reason (Desktop packaged updaters)
})
# ---- end iuf c1 ----
+# ---- iuf c2 ----
+# One fresh-install run of scripts/install.sh / install.ps1, from the local receipt the installer
+# leaves (the installer itself never sends); counted by a later Hermes start while collection is on.
+INSTALL_RUN_MARK = INSTALL_RUN_METRIC = "hermes.install.run"
+INSTALL_RUN_INSTALLERS = frozenset({"install_ps1", "install_sh", "other"})
+INSTALL_RUN_OUTCOMES = frozenset({"failed", "success"})
+# The installers' stage_names / $Stages ladder (hyphens as underscores).
+INSTALL_RUN_STAGES = frozenset({
+ "complete", "config", "gateway", "prerequisites", "products", "python_deps", "repository", "setup", "venv",
+})
+INSTALL_RUN_FAILED_STAGES = INSTALL_RUN_STAGES | {"none", "other"}
+# The code each installer fail()/Fail call site passes; `none` on success.
+INSTALL_RUN_FAILURE_CLASSES = frozenset({
+ "commit_not_on_branch", "curl_missing", "deps_install_failed", "dir_not_checkout", "download_digest_mismatch",
+ "download_failed", "filesystem_error", "gateway_failed", "git_checkout_failed", "git_clone_failed",
+ "git_extract_failed", "git_fetch_failed", "git_missing", "git_reset_failed", "interrupted",
+ "libstdcxx_missing", "local_changes_blocked", "none", "other", "products_build_failed",
+ "python_install_failed", "setup_failed", "unsupported_platform", "uv_unusable",
+})
+# ---- end iuf c2 ----
def update_duration_bucket(duration_ms: Any) -> str:
@@ -960,6 +980,13 @@ _COUNTER_DIMENSION_VALUES: dict[str, dict[str, frozenset[str]]] = {
"event": FEATURE_DISABLED_EVENTS, "kind": FEATURE_DISABLED_KINDS, "surface": FEATURE_DISABLED_SURFACES,
},
# ---- end v5 signals ----
+ # ---- iuf c2 ----
+ INSTALL_RUN_METRIC: {
+ "duration_bucket": UPDATE_DURATION_BUCKETS, "failed_stage": INSTALL_RUN_FAILED_STAGES,
+ "failure_class": INSTALL_RUN_FAILURE_CLASSES, "installer": INSTALL_RUN_INSTALLERS,
+ "outcome": INSTALL_RUN_OUTCOMES,
+ },
+ # ---- end iuf c2 ----
}
_MODEL_ROUTE_MAX_LENGTHS = {
"model": MODEL_IDENTIFIER_MAX_LENGTH, "provider": PROVIDER_IDENTIFIER_MAX_LENGTH,
@@ -1105,6 +1132,9 @@ _DECISION_MARK_METRICS = {
TOOL_UNAVAILABLE_MARK: TOOL_UNAVAILABLE_METRIC, PROVIDER_SETUP_MARK: PROVIDER_SETUP_METRIC,
FEATURE_DISABLED_MARK: FEATURE_DISABLED_METRIC,
# ---- end v5 signals ----
+ # ---- iuf c2 ----
+ INSTALL_RUN_MARK: INSTALL_RUN_METRIC,
+ # ---- end iuf c2 ----
}
diff --git a/hermes_cli/observability/shared_metrics_install_run.py b/hermes_cli/observability/shared_metrics_install_run.py
new file mode 100644
index 00000000000..e82047e40d5
--- /dev/null
+++ b/hermes_cli/observability/shared_metrics_install_run.py
@@ -0,0 +1,121 @@
+"""hermes.install.run: fresh installs through scripts/install.sh and scripts/install.ps1.
+
+The installer runs before the user is asked about shared metrics and must never send anything, so a
+full-ladder run only leaves ONE small local receipt (closed tokens plus two epoch timestamps) under
+the profile's store dir. The next Hermes start that runs the process-exit reporter reads it: with
+collection on it records one row per receipt id and deletes the receipt once the row is saved; with
+collection off ``shared_metrics_process.begin_process`` deletes every receipt unreported (the same
+rule as parked update receipts). A receipt with any value outside the contract is deleted unreported.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import re
+import shutil
+from pathlib import Path
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+PENDING_DIRNAME = "pending_installs"
+# One empty file per receipt id already counted: a delete that failed after the row was saved must
+# not count the same install again on the next start.
+RECORDED_DIRNAME = "recorded_installs"
+_RECORDED_KEEP = 64
+_RECEIPT_ID = re.compile(r"[0-9a-f]{32}")
+_RECEIPT_KEYS = frozenset({"id", "installer", "outcome", "failed_stage", "failure_class", "started_at", "finished_at"})
+
+
+def pending_installs_dir(home: Path) -> Path:
+ return home / "telemetry" / "shared_metrics" / PENDING_DIRNAME
+
+
+def purge_pending_installs(home: Path) -> None:
+ shutil.rmtree(pending_installs_dir(home), ignore_errors=True)
+
+
+def _epoch(value: Any) -> int | None:
+ return value if isinstance(value, int) and not isinstance(value, bool) and value > 0 else None
+
+
+def install_run_fields(receipt: Any) -> dict[str, str] | None:
+ """hermes.install.run dims for one receipt, or None when anything is outside the contract."""
+ from . import shared_metrics_contract as contract
+
+ if not isinstance(receipt, dict) or set(receipt) != _RECEIPT_KEYS:
+ return None
+ if not isinstance(receipt["id"], str) or not _RECEIPT_ID.fullmatch(receipt["id"]):
+ return None
+ started, finished = _epoch(receipt["started_at"]), _epoch(receipt["finished_at"])
+ if started is None or finished is None or finished < started:
+ return None
+ fields = {
+ "duration_bucket": contract.update_duration_bucket((finished - started) * 1000),
+ "failed_stage": receipt["failed_stage"],
+ "failure_class": receipt["failure_class"],
+ "installer": receipt["installer"],
+ "outcome": receipt["outcome"],
+ }
+ if not contract.counter_dimensions_are_valid(contract.INSTALL_RUN_METRIC, fields):
+ return None
+ # A success names no stage and no class; a failure names both.
+ succeeded = fields["outcome"] == "success"
+ if succeeded != (fields["failed_stage"] == "none") or succeeded != (fields["failure_class"] == "none"):
+ return None
+ return fields
+
+
+def _claim_receipt_id(home: Path, receipt_id: str) -> Path | None:
+ """The new latch for ``receipt_id``, or None when this profile already counted it."""
+ directory = home / "telemetry" / "shared_metrics" / RECORDED_DIRNAME
+ directory.mkdir(parents=True, exist_ok=True)
+ latch = directory / receipt_id
+ try:
+ os.close(os.open(latch, os.O_CREAT | os.O_EXCL | os.O_WRONLY))
+ except FileExistsError:
+ return None
+ try:
+ for stale in sorted(directory.iterdir(), key=lambda p: p.stat().st_mtime, reverse=True)[_RECORDED_KEEP:]:
+ stale.unlink(missing_ok=True)
+ except OSError: # a concurrent prune won; the next claim prunes again
+ pass
+ return latch
+
+
+def report_pending_installs(home: Path) -> None:
+ """Record each receipt once (the caller runs only with collection on). Never raises."""
+ try:
+ from . import shared_metrics_contract as contract
+ from .shared_metrics_events import emit_saved
+ from .shared_metrics_process import _claim, settle_claim
+
+ directory = pending_installs_dir(home)
+ if not directory.is_dir():
+ return
+ for path in sorted(directory.iterdir()):
+ if path.name.startswith(".") or ".json" not in path.name:
+ continue
+ claimed = _claim(path) # a concurrent start that loses the rename records nothing
+ if claimed is None:
+ continue
+ try:
+ receipt = json.loads(claimed.read_text(encoding="utf-8-sig"))
+ except (OSError, ValueError):
+ receipt = None
+ fields = install_run_fields(receipt)
+ if fields is None or not isinstance(receipt, dict): # out of contract or unreadable
+ settle_claim(claimed, path, True)
+ continue
+ latch = _claim_receipt_id(home, receipt["id"])
+ if latch is None: # counted before; only the delete had failed
+ settle_claim(claimed, path, True)
+ continue
+ saved = emit_saved([(contract.INSTALL_RUN_MARK, fields)]) == 1
+ if not saved:
+ latch.unlink(missing_ok=True) # nothing landed: the next start counts it
+ settle_claim(claimed, path, saved)
+ except Exception:
+ logger.debug("Pending install receipts not reported", exc_info=True)
diff --git a/hermes_cli/observability/shared_metrics_process.py b/hermes_cli/observability/shared_metrics_process.py
index 1d621e9b05f..e7f46847bd2 100644
--- a/hermes_cli/observability/shared_metrics_process.py
+++ b/hermes_cli/observability/shared_metrics_process.py
@@ -86,6 +86,11 @@ def begin_process(kind: str) -> None:
if not _collection_on():
home = get_hermes_home()
purge_pending_updates(home) # parked while on, never to be counted once off
+ # ---- iuf c2 ----
+ from .shared_metrics_install_run import purge_pending_installs
+
+ purge_pending_installs(home) # an installer receipt is counted only while collection is on
+ # ---- end iuf c2 ----
latches = home / "telemetry" / "shared_metrics" / ONBOARDING_LATCH_DIRNAME # an opt-out outside Desktop
for directory in (markers_dir(home), setup_markers_dir(home), latches): # likewise pending exits/setups
shutil.rmtree(directory, ignore_errors=True)
@@ -200,6 +205,11 @@ def _report_dead_markers(home: Path, own: Path) -> None:
report_pending_updates()
report_abandoned_setups(home)
+ # ---- iuf c2 ----
+ from .shared_metrics_install_run import report_pending_installs
+
+ report_pending_installs(home)
+ # ---- end iuf c2 ----
except Exception:
logger.debug("Dead process markers not reported", exc_info=True)
finally:
diff --git a/scripts/install.ps1 b/scripts/install.ps1
index f8dfe382005..31e04987614 100644
--- a/scripts/install.ps1
+++ b/scripts/install.ps1
@@ -344,7 +344,7 @@ function Initialize-ResolvedPaths {
$storeInside = $cmpStore -eq $cmpDir -or
$cmpStore.StartsWith($dirPrefix, [StringComparison]::OrdinalIgnoreCase)
if ($storeInside) {
- Fail "HermesHome ($resolvedHome) cannot be the install directory or live inside it ($resolvedDir): the tool store would land inside the checkout. Use a separate -HermesHome, or point HERMES_RUNTIME_DIR outside -InstallDir."
+ Fail "HermesHome ($resolvedHome) cannot be the install directory or live inside it ($resolvedDir): the tool store would land inside the checkout. Use a separate -HermesHome, or point HERMES_RUNTIME_DIR outside -InstallDir." other
}
# The param() variables live in the CALLER's scope, which is the script
# scope only under -File. Under the documented
@@ -422,13 +422,13 @@ function Invoke-VerifiedDownload {
if ($digest -eq $Sha256.ToLowerInvariant()) { return }
Remove-Item -Path $OutFile -Force -ErrorAction SilentlyContinue
# Wrong bytes = tampering or a corrupt mirror, not a routing problem.
- Fail "download digest mismatch for $candidate (expected $Sha256, got $digest)"
+ Fail "download digest mismatch for $candidate (expected $Sha256, got $digest)" download_digest_mismatch
}
$tried = $urls -join " or "
if ($httpFailure) {
- Fail "failed to download from $tried : $httpFailure"
+ Fail "failed to download from $tried : $httpFailure" download_failed
}
- Fail "failed to download from $tried"
+ Fail "failed to download from $tried" download_failed
}
# Best-effort: how big is $Uri, per the server? Returns 0 when the server
@@ -517,7 +517,7 @@ function Get-Uv {
$target = "win32-$(Get-WindowsArch)"
$pin = $script:UvPinFiles[$target]
if (-not $pin) {
- Fail "no pinned uv artifact for $target; Hermes does not support this host"
+ Fail "no pinned uv artifact for $target; Hermes does not support this host" unsupported_platform
}
$entry = Join-Path (Get-PmStoreRoot) "uv-$($script:UvPinVersion)-$target"
$uvExe = Join-Path $entry "uv.exe"
@@ -537,7 +537,7 @@ function Get-Uv {
# The zip carries uv.exe (+ uvx.exe) at the root or under one
# versioned wrapper dir — take whichever layout arrived.
$found = Get-ChildItem -Path $extractDir -Filter "uv.exe" -Recurse | Select-Object -First 1
- if (-not $found) { Fail "uv.exe not found in the downloaded archive" }
+ if (-not $found) { Fail "uv.exe not found in the downloaded archive" uv_unusable }
New-Item -ItemType Directory -Force -Path $entry | Out-Null
Move-Item -Path $found.FullName -Destination $uvExe -Force
$uvx = Get-ChildItem -Path $extractDir -Filter "uvx.exe" -Recurse | Select-Object -First 1
@@ -545,7 +545,7 @@ function Get-Uv {
} finally {
Remove-Item -Path $tmpDir -Recurse -Force -ErrorAction SilentlyContinue
}
- if (-not (Test-UvAtLeastPin $uvExe)) { Fail "pinned uv staged but does not run on this host" }
+ if (-not (Test-UvAtLeastPin $uvExe)) { Fail "pinned uv staged but does not run on this host" uv_unusable }
return $uvExe
}
@@ -578,12 +578,12 @@ function Get-PinnedGit {
if (-not $sfx.WaitForExit(600000)) {
Invoke-Native { taskkill.exe /T /F /PID $sfx.Id 2>&1 | Out-Null }
$sfx.WaitForExit()
- Fail "pinned git self-extractor timed out after 600s"
+ Fail "pinned git self-extractor timed out after 600s" git_extract_failed
}
if ($sfx.ExitCode) {
- Fail "pinned git self-extractor exited $($sfx.ExitCode) (it reports nothing under -y; usual causes: disk full, path-length limit, antivirus lock)"
+ Fail "pinned git self-extractor exited $($sfx.ExitCode) (it reports nothing under -y; usual causes: disk full, path-length limit, antivirus lock)" git_extract_failed
}
- if (-not (Test-Path (Join-Path $extractDir "cmd\git.exe"))) { Fail "git.exe not found in the downloaded archive" }
+ if (-not (Test-Path (Join-Path $extractDir "cmd\git.exe"))) { Fail "git.exe not found in the downloaded archive" git_extract_failed }
if (Test-Path $entry) { Remove-Item -Recurse -Force $entry }
# Prerequisites run first, so on a fresh host the store root does not
# exist yet; Move-Item never creates the destination's parent.
@@ -728,12 +728,32 @@ function Test-UvAtLeastPin([string]$Path) {
$have = ("$out".Trim() -split '\s+')[1] -replace '[^0-9.].*$', ''
try { return ([version]$have -ge [version]$script:UvPinVersion) } catch { return $false }
}
-function Fail([string]$msg) {
+function Fail([string]$msg, [string]$Class = "other") {
# Throw, never exit: the entry points below own reporting and the exit
# code, and the stage dispatcher's catch emits the -Json failure frame.
+ # $Class: closed failure class for the local install receipt.
+ $script:FailureClass = $Class
throw $msg
}
+# One local receipt per full-ladder run, under the profile's shared-metrics dir.
+# Only closed tokens and two timestamps (never the error text, paths or URLs);
+# the installer never sends anything. Hermes reports it as hermes.install.run on
+# a later start only while shared metrics collection is on, and deletes it
+# unreported when collection is off. Best effort: never fails the install.
+function Write-InstallReceipt([string]$Outcome, [string]$FailedStage, [string]$Class) {
+ try {
+ $dir = Join-Path $HermesHome "telemetry\shared_metrics\pending_installs"
+ New-Item -ItemType Directory -Force -Path $dir | Out-Null
+ $id = [guid]::NewGuid().ToString("N")
+ $json = '{{"id":"{0}","installer":"install_ps1","outcome":"{1}","failed_stage":"{2}","failure_class":"{3}","started_at":{4},"finished_at":{5}}}' -f `
+ $id, $Outcome, ($FailedStage -replace '-', '_'), $Class, $script:InstallStarted, [DateTimeOffset]::UtcNow.ToUnixTimeSeconds()
+ $tmp = Join-Path $dir ".$id.tmp"
+ [IO.File]::WriteAllText($tmp, $json, (New-Object System.Text.UTF8Encoding $false))
+ Move-Item -LiteralPath $tmp -Destination (Join-Path $dir "$id.json") -Force
+ } catch {}
+}
+
function Emit-Frame([bool]$ok, [string]$name, [bool]$skipped, [string]$reason = "") {
$frame = [ordered]@{ ok = $ok; stage = $name; skipped = $skipped }
if ($reason) { $frame.reason = $reason }
@@ -757,7 +777,7 @@ $Stages = @(
$Stages += @{ name = "complete"; title = "Finish install"; category = "runtime"; needs_user_input = $false }
function Stage-Prerequisites {
if (-not (Ensure-Git)) {
- Fail "no pinned Git artifact for this Windows architecture"
+ Fail "no pinned Git artifact for this Windows architecture" unsupported_platform
}
Write-Ok "prerequisites ok (git)"
}
@@ -779,10 +799,10 @@ function Stage-Repository {
$item = Get-Item -LiteralPath $InstallDir -Force
$empty = $item.PSIsContainer -and -not $item.LinkType -and -not (Get-ChildItem -LiteralPath $InstallDir -Force | Select-Object -First 1)
if (-not $empty) {
- Fail "$InstallDir exists and is not a Hermes git checkout. Move it aside, or install elsewhere with -InstallDir <path>."
+ Fail "$InstallDir exists and is not a Hermes git checkout. Move it aside, or install elsewhere with -InstallDir <path>." dir_not_checkout
}
}
- if (-not (Ensure-Git)) { Fail "no pinned Git artifact for this Windows architecture" }
+ if (-not (Ensure-Git)) { Fail "no pinned Git artifact for this Windows architecture" unsupported_platform }
# An interrupted clone from an older installer can leave a .git with no
# initial commit, where stash/checkout abort ("You do not have the initial
# commit yet", #40998). Move it aside -- never delete it, it may hold
@@ -801,7 +821,7 @@ function Stage-Repository {
# just the first clone.
if ($env:HERMES_REPO_URL) {
Invoke-Native { git -C $InstallDir remote set-url origin $RepoUrl }
- if ($LASTEXITCODE) { Fail "cannot point origin at $RepoUrl" }
+ if ($LASTEXITCODE) { Fail "cannot point origin at $RepoUrl" git_fetch_failed }
}
# Explicit refspec: a tag-pinned --single-branch checkout from an older installer maps only
# the tag, so a by-name fetch never writes the origin/$Branch used below (#125112).
@@ -834,7 +854,7 @@ function Stage-Repository {
}
}
Invoke-Logged "Fetching origin/$Branch" { git -C $InstallDir fetch origin "+refs/heads/${Branch}:refs/remotes/origin/${Branch}" }
- if ($LASTEXITCODE) { Fail "git fetch failed" }
+ if ($LASTEXITCODE) { Fail "git fetch failed" git_fetch_failed }
$stamp = (Get-Date -Format 'yyyyMMdd-HHmmss')
# Park local work BEFORE switching branches: checkout refuses a dirty
# tree that conflicts, and the reset below would discard it. Work that
@@ -847,10 +867,10 @@ function Stage-Repository {
if (Invoke-Native { git -C $InstallDir ls-files --unmerged }) {
Write-Warn "clearing unmerged index entries from a previous conflict"
Invoke-Native { git -C $InstallDir reset -q }
- if ($LASTEXITCODE) { Fail "cannot clear the unmerged index in $InstallDir" }
+ if ($LASTEXITCODE) { Fail "cannot clear the unmerged index in $InstallDir" local_changes_blocked }
}
Invoke-Logged "Stashing local changes" { git -C $InstallDir stash push --include-untracked -m "hermes-install-autostash-$stamp" }
- if ($LASTEXITCODE) { Fail "could not stash local changes in $InstallDir; commit or move them aside, then rerun" }
+ if ($LASTEXITCODE) { Fail "could not stash local changes in $InstallDir; commit or move them aside, then rerun" local_changes_blocked }
Write-Warn "local changes stashed as hermes-install-autostash-$stamp"
}
# checkout's branch guess only sees remote refs the refspec maps, so a narrow checkout
@@ -861,7 +881,7 @@ function Stage-Repository {
} else {
Invoke-Logged "Checking out $Branch" { git -C $InstallDir checkout $Branch }
}
- if ($LASTEXITCODE) { Fail "git checkout failed" }
+ if ($LASTEXITCODE) { Fail "git checkout failed" git_checkout_failed }
# --no-stat: across a large gap (v2026.7.1 -> today is ~27k lines) the
# diffstat arrives as one burst. Hermes-Setup.exe forwards every line
# to its window as a separate event; the burst overflows the Windows
@@ -876,22 +896,22 @@ function Stage-Repository {
# does, after parking the old tip. Mirrors scripts/install.sh.
# Keep commits absent from origin in the updater's rescue namespace.
$droppedText = (Invoke-Native { git -C $InstallDir rev-list --count "origin/$Branch..HEAD" 2>$null })
- if ($LASTEXITCODE) { Fail "cannot count commits before reset" }
+ if ($LASTEXITCODE) { Fail "cannot count commits before reset" git_reset_failed }
[long]$dropped = 0
- if (-not [long]::TryParse("$droppedText".Trim(), [ref]$dropped)) { Fail "cannot count commits before reset" }
+ if (-not [long]::TryParse("$droppedText".Trim(), [ref]$dropped)) { Fail "cannot count commits before reset" git_reset_failed }
if ($dropped -gt 0) {
Invoke-Native { git -C $InstallDir merge-base HEAD "origin/$Branch" 2>$null } | Out-Null
$rescueKind = if ($LASTEXITCODE -eq 0) { 'diverged' } else { 'orphan' }
$prior = (Invoke-Native { git -C $InstallDir rev-parse --short=12 HEAD 2>$null })
- if ($LASTEXITCODE -or -not $prior) { Fail "cannot identify commits before reset" }
+ if ($LASTEXITCODE -or -not $prior) { Fail "cannot identify commits before reset" git_reset_failed }
$rescue = "refs/hermes-update-backups/$rescueKind-$Branch-$stamp-$prior"
Invoke-Native { git -C $InstallDir update-ref $rescue HEAD 2>$null }
- if ($LASTEXITCODE) { Fail "cannot back up $dropped local commit(s); refusing to reset" }
+ if ($LASTEXITCODE) { Fail "cannot back up $dropped local commit(s); refusing to reset" git_reset_failed }
Write-Warn "$dropped commit(s) not on origin/$Branch backed up to $rescue"
Log "List them with: git -C `"$InstallDir`" log origin/$Branch..$rescue"
}
Invoke-Logged "Resetting to origin/$Branch" { git -C $InstallDir reset --hard "origin/$Branch" }
- if ($LASTEXITCODE) { Fail "git reset failed" }
+ if ($LASTEXITCODE) { Fail "git reset failed" git_reset_failed }
Write-Warn "not fast-forwardable; reset to origin/$Branch"
}
} else {
@@ -940,7 +960,7 @@ function Stage-Repository {
}
}
}
- if (-not $cloned) { Fail "git clone failed; no checkout published" }
+ if (-not $cloned) { Fail "git clone failed; no checkout published" git_clone_failed }
Move-Item -LiteralPath $tree -Destination $InstallDir
Disable-TreelessGraphWrites $InstallDir
Write-Ok "Hermes Agent cloned"
@@ -953,9 +973,9 @@ function Stage-Repository {
# records both, and a commit off that branch would make the next plain
# rerun "update" onto a different line.
Invoke-Native { git -C $InstallDir merge-base --is-ancestor $Commit "origin/$Branch" 2>$null }
- if ($LASTEXITCODE) { Fail "commit $Commit is not on branch $Branch" }
+ if ($LASTEXITCODE) { Fail "commit $Commit is not on branch $Branch" commit_not_on_branch }
Invoke-Logged "Pinning $Commit" { git -C $InstallDir checkout $Commit }
- if ($LASTEXITCODE) { Fail "could not pin commit $Commit" }
+ if ($LASTEXITCODE) { Fail "could not pin commit $Commit" git_checkout_failed }
}
}
@@ -987,10 +1007,10 @@ function Get-BootstrapPython {
$bootPy = (Invoke-Native -Utf8Output { & $uv python find --managed-python --no-project $pyRequest 2>$null }) -join "`n"
if ($LASTEXITCODE -or -not $bootPy) {
Invoke-Logged "Downloading Python $pyVersion" { & $uv python install --no-bin --no-registry $pyRequest }
- if ($LASTEXITCODE) { Fail "bootstrap Python installation failed" }
+ if ($LASTEXITCODE) { Fail "bootstrap Python installation failed" python_install_failed }
$bootPy = (Invoke-Native -Utf8Output { & $uv python find --managed-python --no-project $pyRequest }) -join "`n"
}
- if ($LASTEXITCODE -or -not $bootPy) { Fail "bootstrap Python lookup failed" }
+ if ($LASTEXITCODE -or -not $bootPy) { Fail "bootstrap Python lookup failed" python_install_failed }
$script:BootstrapPython = $bootPy.Trim()
return $script:BootstrapPython
}
@@ -1006,7 +1026,7 @@ function Invoke-BootstrapPm {
if ($SkipBrowser) { $pmArgs += @('--without', 'agent-browser') }
if ($SkipComputerUse) { $pmArgs += @('--without', 'cua-driver') }
Invoke-Logged "Installing dependencies (hash-verified via uv.lock)" { & $bootPy -m pm.cli @pmArgs }
- if ($LASTEXITCODE) { Fail "dependency install failed" }
+ if ($LASTEXITCODE) { Fail "dependency install failed" deps_install_failed }
} finally {
Pop-Location
}
@@ -1034,7 +1054,7 @@ function Invoke-SourceCompletion([bool]$Desktop) {
} finally {
Pop-Location
}
- if ($code) { Fail "app products or command publication failed (exit $code)" }
+ if ($code) { Fail "app products or command publication failed (exit $code)" products_build_failed }
Write-Ok "app products and hermes command ready"
}
@@ -1052,7 +1072,7 @@ function Publish-UserCommand {
} finally {
Pop-Location
}
- if ($code) { Fail "launcher staging failed" }
+ if ($code) { Fail "launcher staging failed" products_build_failed }
Set-LauncherUserPath $binDir
Write-Ok "hermes command installed at $binDir"
}
@@ -1134,7 +1154,9 @@ function Invoke-InstalledHermes([string[]]$CommandArgs) {
$runtimeCommand = @(Get-HermesRuntimeCommand -InstallRoot $InstallDir)
$runtimeArgs = @($runtimeCommand | Select-Object -Skip 1) + $CommandArgs
Invoke-Native { & $runtimeCommand[0] @runtimeArgs }
- if ($LASTEXITCODE) { Fail "hermes $($CommandArgs -join ' ') failed (exit $LASTEXITCODE)" }
+ if ($LASTEXITCODE) {
+ Fail "hermes $($CommandArgs -join ' ') failed (exit $LASTEXITCODE)" $(if ($CommandArgs[0] -eq 'setup') { 'setup_failed' } else { 'gateway_failed' })
+ }
}
function Stage-Setup {
@@ -1174,7 +1196,7 @@ function Confirm-DesktopArtifact {
if (Test-Path $cand) { $desktopExe = $cand; break }
}
if (-not $desktopExe) {
- Fail "desktop build produced no Hermes.exe under $desktopDir\release\*-unpacked"
+ Fail "desktop build produced no Hermes.exe under $desktopDir\release\*-unpacked" products_build_failed
}
Write-Ok "Desktop ready: $desktopExe"
@@ -1203,7 +1225,7 @@ function Confirm-DesktopArtifact {
function Stage-Complete {
$commit = $Commit
if (-not $commit) {
- if (-not (Ensure-Git)) { Fail "no pinned Git artifact for this Windows architecture" }
+ if (-not (Ensure-Git)) { Fail "no pinned Git artifact for this Windows architecture" unsupported_platform }
$commit = Invoke-Native { git -C $InstallDir rev-parse HEAD 2>$null }
}
if ($commit) {
@@ -1361,13 +1383,19 @@ if ($Stage) {
# No -Stage: run the whole ladder — the same authoritative list the
# manifest prints, so -IncludeDesktop inserts desktop here too.
+$script:InstallStarted = [DateTimeOffset]::UtcNow.ToUnixTimeSeconds()
+$script:InstallStage = "prerequisites"
try {
Write-Banner
foreach ($s in $Stages) {
+ $script:InstallStage = $s.name
+ $script:FailureClass = ""
Invoke-StageByName $s.name
}
+ Write-InstallReceipt "success" "none" "none"
Write-PathReloadHint
} catch {
+ Write-InstallReceipt "failed" $script:InstallStage $(if ($script:FailureClass) { $script:FailureClass } else { "other" })
Write-Err "$_"
if ($script:RunAsFile) { exit 1 }
# Under iex: report failure without closing the user's window.
diff --git a/scripts/install.sh b/scripts/install.sh
index a576ee5e27e..b76300be230 100755
--- a/scripts/install.sh
+++ b/scripts/install.sh
@@ -33,6 +33,9 @@ INCLUDE_DESKTOP=false
VERBOSE=false
SKIP_BROWSER=false
SKIP_COMPUTER_USE=false
+INSTALL_LADDER=false
+INSTALL_STARTED=0
+FAILURE_CLASS=""
while [ $# -gt 0 ]; do
case "$1" in
@@ -95,7 +98,25 @@ log() { printf '%s→%s %s\n' "$C_CYAN" "$C_NC" "$1"; }
log_success() { printf '%s✓%s %s\n' "$C_GREEN" "$C_NC" "$1"; }
log_warn() { printf '%s⚠%s %s\n' "$C_YELLOW" "$C_NC" "$1"; }
log_error() { printf '%s✗%s %s\n' "$C_RED" "$C_NC" "$1" >&2; }
-fail() { STAGE_REASON="$1"; log_error "$1"; exit 1; }
+# $2: closed failure class for the local install receipt (write_install_receipt).
+fail() { STAGE_REASON="$1"; FAILURE_CLASS="${2:-other}"; log_error "$1"; exit 1; }
+
+# One local receipt per full-ladder run, under the profile's shared-metrics dir.
+# Only closed tokens and two timestamps (never STAGE_REASON, paths or URLs); the
+# installer never sends anything. Hermes reports it as hermes.install.run on a
+# later start only while shared metrics collection is on, and deletes it
+# unreported when collection is off. Best effort: never fails the install.
+write_install_receipt() {
+ # $1 outcome, $2 failed stage, $3 failure class
+ {
+ local dir="$HERMES_HOME/telemetry/shared_metrics/pending_installs" id
+ id="$(od -An -N16 -tx1 /dev/urandom 2>/dev/null | tr -d ' \n')"
+ [ "${#id}" -eq 32 ] || id="$(printf '%08x%08x%08x' "$RANDOM$RANDOM" "$$" "$(date +%s)")"
+ mkdir -p "$dir" && printf '{"id":"%s","installer":"install_sh","outcome":"%s","failed_stage":"%s","failure_class":"%s","started_at":%s,"finished_at":%s}\n' \
+ "$id" "$1" "$2" "$3" "${INSTALL_STARTED:-0}" "$(date +%s)" > "$dir/.$id.tmp" \
+ && mv -f "$dir/.$id.tmp" "$dir/$id.json"
+ } >/dev/null 2>&1 || :
+}
print_banner() {
printf '\n%s%s' "$C_MAGENTA" "$C_BOLD"
@@ -267,10 +288,10 @@ ensure_uv() {
# its own packaged toolchain.
local _target
if ! _target="$(uv_bootstrap_target)"; then
- fail "no pinned uv build for this platform ($(uname -s) $(uname -m)); Hermes does not support this host"
+ fail "no pinned uv build for this platform ($(uname -s) $(uname -m)); Hermes does not support this host" unsupported_platform
fi
if ! uv_bootstrap_pin "$_target"; then
- fail "no pinned uv artifact for $_target; Hermes does not support this host"
+ fail "no pinned uv artifact for $_target; Hermes does not support this host" unsupported_platform
fi
local _store="${HERMES_RUNTIME_DIR:-$HERMES_HOME/tools}"
local _entry="$_store/uv-$UV_PIN_VERSION-$_target"
@@ -289,13 +310,13 @@ ensure_uv() {
local _curl_status=$?
case "$_curl_status" in
5|6|7|18|22|28|52|55|56) ;;
- *) rm -rf "$_tmp"; fail "failed to download pinned uv from $UV_PIN_URL (curl $_curl_status)" ;;
+ *) rm -rf "$_tmp"; fail "failed to download pinned uv from $UV_PIN_URL (curl $_curl_status)" download_failed ;;
esac
if [ -n "${UV_PIN_MIRROR:-}" ] && curl -LsSf "$UV_PIN_MIRROR" -o "$_tmp/uv.tar.gz"; then
_fetched_from="$UV_PIN_MIRROR"
else
rm -rf "$_tmp"
- fail "failed to download pinned uv from $UV_PIN_URL or ${UV_PIN_MIRROR:-no mirror}"
+ fail "failed to download pinned uv from $UV_PIN_URL or ${UV_PIN_MIRROR:-no mirror}" download_failed
fi
fi
local _digest
@@ -306,17 +327,17 @@ ensure_uv() {
fi
if [ "$_digest" != "$UV_PIN_SHA256" ]; then
rm -rf "$_tmp"
- fail "uv download digest mismatch from $_fetched_from (expected $UV_PIN_SHA256, got $_digest)"
+ fail "uv download digest mismatch from $_fetched_from (expected $UV_PIN_SHA256, got $_digest)" download_digest_mismatch
fi
if ! tar -xzf "$_tmp/uv.tar.gz" -C "$_tmp"; then
rm -rf "$_tmp"
- fail "failed to extract pinned uv archive"
+ fail "failed to extract pinned uv archive" uv_unusable
fi
local _unpacked
_unpacked="$(find "$_tmp" -mindepth 1 -maxdepth 2 -name uv -type f | head -n1)"
if [ -z "$_unpacked" ]; then
rm -rf "$_tmp"
- fail "uv binary not found in the downloaded archive"
+ fail "uv binary not found in the downloaded archive" uv_unusable
fi
mkdir -p "$_entry"
mv "$_unpacked" "$UV_CMD"
@@ -327,7 +348,7 @@ ensure_uv() {
fi
# Bootstrap keeps the installer private; only UV_CMD invokes it.
if ! "$UV_CMD" --version >/dev/null 2>&1; then
- fail "pinned uv staged but does not run on this host"
+ fail "pinned uv staged but does not run on this host" uv_unusable
fi
log_success "uv ready ($("$UV_CMD" --version 2>/dev/null))"
}
@@ -337,12 +358,12 @@ check_platform() {
# install the phone cannot run (no Android wheels in the lock). The
# signed APT package is the only supported shape there.
if [ -n "${TERMUX_VERSION:-}" ] || case "${PREFIX:-}" in *com.termux/files/usr*) true ;; *) false ;; esac; then
- fail "Termux is installed from its APT repository, not install.sh: pkg install hermes-agent (setup: https://hermes-agent.nousresearch.com/docs/getting-started/termux)"
+ fail "Termux is installed from its APT repository, not install.sh: pkg install hermes-agent (setup: https://hermes-agent.nousresearch.com/docs/getting-started/termux)" unsupported_platform
fi
case "$(uname -s 2>/dev/null)" in
Linux*) : ;;
Darwin*) : ;;
- *) fail "unsupported platform: $(uname -s). On Windows use install.ps1." ;;
+ *) fail "unsupported platform: $(uname -s). On Windows use install.ps1." unsupported_platform ;;
esac
}
@@ -378,6 +399,11 @@ stage_result() {
if [ "$JSON" = true ]; then
json_frame "$ok" "$STAGE" "${STAGE_SKIPPED:-false}" "$reason"
fi
+ if [ "$ok" = false ] && [ "${INSTALL_LADDER:-false}" = true ]; then
+ # 130/143: Ctrl-C or SIGTERM while a stage ran, not a stage defect.
+ case "$code" in 130|143) [ -n "${FAILURE_CLASS:-}" ] || FAILURE_CLASS=interrupted ;; esac
+ write_install_receipt failed "${STAGE//-/_}" "${FAILURE_CLASS:-other}"
+ fi
}
# The single authoritative stage list: emit_manifest prints it AND the
@@ -428,8 +454,8 @@ emit_manifest() {
}
stage_prerequisites() {
- command -v git >/dev/null 2>&1 || fail "git is required. Install it with your system package manager."
- command -v curl >/dev/null 2>&1 || fail "curl is required. Install it with your system package manager."
+ command -v git >/dev/null 2>&1 || fail "git is required. Install it with your system package manager." git_missing
+ command -v curl >/dev/null 2>&1 || fail "curl is required. Install it with your system package manager." curl_missing
# PM's Node on musl is the unofficial-builds musl archive, which links the
# system libstdc++; without it every node/npm stage fails verification.
local _target
@@ -439,7 +465,7 @@ stage_prerequisites() {
for _libdir in /lib /usr/lib /usr/local/lib; do
compgen -G "$_libdir/libstdc++.so.6*" >/dev/null && { _stdcxx=yes; break; }
done
- [ -n "$_stdcxx" ] || fail "musl host: the Node.js runtime needs the system libstdc++. Install it (Alpine: apk add libstdc++, Void: xbps-install libstdc++) and re-run."
+ [ -n "$_stdcxx" ] || fail "musl host: the Node.js runtime needs the system libstdc++. Install it (Alpine: apk add libstdc++, Void: xbps-install libstdc++) and re-run." libstdcxx_missing
fi
# glibc Node links libatomic.so.1, absent on minimal Debian/RHEL hosts. PM
# installs the distro package with `sudo -n` under its install lock, so
@@ -462,14 +488,14 @@ stage_repository() {
local broken
broken="${INSTALL_DIR}.broken-$(date -u +%Y%m%d-%H%M%S)"
log_warn "$INSTALL_DIR has no commits (interrupted clone); moving it aside to $broken"
- mv "$INSTALL_DIR" "$broken" || fail "cannot move $INSTALL_DIR aside"
+ mv "$INSTALL_DIR" "$broken" || fail "cannot move $INSTALL_DIR aside" filesystem_error
fi
if [ -d "$INSTALL_DIR/.git" ]; then
log "Updating $INSTALL_DIR ($BRANCH)"
# An explicit HERMES_REPO_URL names the source for reruns too, not
# just the first clone.
if [ -n "${HERMES_REPO_URL:-}" ]; then
- git -C "$INSTALL_DIR" remote set-url origin "$REPO_URL" || fail "cannot point origin at $REPO_URL"
+ git -C "$INSTALL_DIR" remote set-url origin "$REPO_URL" || fail "cannot point origin at $REPO_URL" git_fetch_failed
fi
# Explicit refspec: a tag-pinned --single-branch checkout from an older
# installer maps only the tag, so a by-name fetch writes FETCH_HEAD and
@@ -506,7 +532,7 @@ stage_repository() {
fi
fi
run_logged "Fetching origin/$BRANCH" git -C "$INSTALL_DIR" fetch origin "+refs/heads/$BRANCH:refs/remotes/origin/$BRANCH" \
- || fail "git fetch failed"
+ || fail "git fetch failed" git_fetch_failed
local stamp
stamp="$(date -u +%Y%m%d-%H%M%S)"
# Park local work BEFORE switching branches: checkout refuses a dirty
@@ -519,21 +545,21 @@ stage_repository() {
# the stash below (#4735).
if [ -n "$(git -C "$INSTALL_DIR" ls-files --unmerged)" ]; then
log_warn "clearing unmerged index entries from a previous conflict"
- git -C "$INSTALL_DIR" reset -q || fail "cannot clear the unmerged index in $INSTALL_DIR"
+ git -C "$INSTALL_DIR" reset -q || fail "cannot clear the unmerged index in $INSTALL_DIR" local_changes_blocked
fi
run_logged "Stashing local changes" \
git -C "$INSTALL_DIR" stash push --include-untracked -m "hermes-install-autostash-$stamp" \
- || fail "could not stash local changes in $INSTALL_DIR; commit or move them aside, then rerun"
+ || fail "could not stash local changes in $INSTALL_DIR; commit or move them aside, then rerun" local_changes_blocked
log_warn "local changes stashed as hermes-install-autostash-$stamp"
fi
# checkout's branch guess only sees remote refs the refspec maps, so a
# narrow checkout (detached at its tag, no local branch) gets the branch
# created at the fetched tip.
if git -C "$INSTALL_DIR" show-ref --verify --quiet "refs/heads/$BRANCH"; then
- run_logged "Checking out $BRANCH" git -C "$INSTALL_DIR" checkout "$BRANCH" || fail "git checkout failed"
+ run_logged "Checking out $BRANCH" git -C "$INSTALL_DIR" checkout "$BRANCH" || fail "git checkout failed" git_checkout_failed
else
run_logged "Checking out $BRANCH" git -C "$INSTALL_DIR" checkout -b "$BRANCH" "origin/$BRANCH" \
- || fail "git checkout failed"
+ || fail "git checkout failed" git_checkout_failed
fi
if ! run_logged --may-fail "Fast-forwarding to origin/$BRANCH" \
git -C "$INSTALL_DIR" merge --ff-only "origin/$BRANCH"; then
@@ -546,21 +572,21 @@ stage_repository() {
# namespace as `hermes update` so its pruning and recovery work.
local dropped rescue_kind rescue_ref prior
dropped="$(git -C "$INSTALL_DIR" rev-list --count "origin/$BRANCH..HEAD")" \
- || fail "cannot count commits before reset"
+ || fail "cannot count commits before reset" git_reset_failed
if [ "$dropped" -gt 0 ]; then
rescue_kind="diverged"
git -C "$INSTALL_DIR" merge-base HEAD "origin/$BRANCH" >/dev/null 2>&1 \
|| rescue_kind="orphan"
prior="$(git -C "$INSTALL_DIR" rev-parse --short=12 HEAD)" \
- || fail "cannot identify commits before reset"
+ || fail "cannot identify commits before reset" git_reset_failed
rescue_ref="refs/hermes-update-backups/$rescue_kind-$BRANCH-$stamp-$prior"
git -C "$INSTALL_DIR" update-ref "$rescue_ref" HEAD \
- || fail "cannot back up $dropped local commit(s); refusing to reset"
+ || fail "cannot back up $dropped local commit(s); refusing to reset" git_reset_failed
log_warn "$dropped commit(s) not on origin/$BRANCH backed up to $rescue_ref"
log "List them with: git -C \"$INSTALL_DIR\" log origin/$BRANCH..$rescue_ref"
fi
run_logged "Resetting to origin/$BRANCH" git -C "$INSTALL_DIR" reset --hard "origin/$BRANCH" \
- || fail "git reset failed"
+ || fail "git reset failed" git_reset_failed
log_warn "not fast-forwardable; reset to origin/$BRANCH"
fi
else
@@ -569,9 +595,9 @@ stage_repository() {
# the empty dir over) or we refuse: whatever lives there is not ours.
if [ -e "$INSTALL_DIR" ] || [ -L "$INSTALL_DIR" ]; then
if [ -d "$INSTALL_DIR" ] && [ ! -L "$INSTALL_DIR" ] && [ -z "$(ls -A "$INSTALL_DIR")" ]; then
- rmdir "$INSTALL_DIR" || fail "cannot replace empty $INSTALL_DIR"
+ rmdir "$INSTALL_DIR" || fail "cannot replace empty $INSTALL_DIR" filesystem_error
else
- fail "$INSTALL_DIR exists and is not a Hermes git checkout. Move it aside, or install elsewhere with --dir <path>."
+ fail "$INSTALL_DIR exists and is not a Hermes git checkout. Move it aside, or install elsewhere with --dir <path>." dir_not_checkout
fi
fi
mkdir -p "$(dirname "$INSTALL_DIR")"
@@ -579,7 +605,7 @@ stage_repository() {
# Phase lines ("Receiving objects: 42%") feed the status line; git
# prints none to a pipe unless asked.
if quiet_output; then progress=(--progress); fi
- staged="$(mktemp -d "$(dirname "$INSTALL_DIR")/.hermes-clone-XXXXXX")" || fail "cannot stage clone"
+ staged="$(mktemp -d "$(dirname "$INSTALL_DIR")/.hermes-clone-XXXXXX")" || fail "cannot stage clone" filesystem_error
for attempt in 1 2 3; do
# Blobless: every commit, tree and release tag (runtime identity is
# the nearest reachable release; --commit pins and branch switches
@@ -614,11 +640,11 @@ stage_repository() {
fi
if [ "$cloned" = false ]; then
rm -rf "$staged"
- fail "git clone failed; no checkout published"
+ fail "git clone failed; no checkout published" git_clone_failed
fi
if ! mv "$staged/tree" "$INSTALL_DIR"; then
rm -rf "$staged"
- fail "cannot publish cloned checkout"
+ fail "cannot publish cloned checkout" filesystem_error
fi
rmdir "$staged"
# A treeless checkout must never write a commit-graph: over a graph with
@@ -638,9 +664,9 @@ stage_repository() {
# marker records both, and a commit off that branch would make the
# next plain rerun "update" onto a different line.
git -C "$INSTALL_DIR" merge-base --is-ancestor "$INSTALL_COMMIT" "origin/$BRANCH" 2>/dev/null \
- || fail "commit $INSTALL_COMMIT is not on branch $BRANCH"
+ || fail "commit $INSTALL_COMMIT is not on branch $BRANCH" commit_not_on_branch
run_logged "Pinning $INSTALL_COMMIT" git -C "$INSTALL_DIR" checkout "$INSTALL_COMMIT" \
- || fail "could not pin commit $INSTALL_COMMIT"
+ || fail "could not pin commit $INSTALL_COMMIT" git_checkout_failed
fi
}
@@ -671,11 +697,11 @@ bootstrap_python() {
if ! boot_py="$(UV_SYSTEM_PYTHON=1 UV_NO_PROJECT=1 "$UV_CMD" python find --managed-python "$_py" 2>/dev/null)" \
&& ! boot_py="$("$UV_CMD" python find --system --no-project "$_py" 2>/dev/null)"; then
run_logged "Downloading Python $_py" "$UV_CMD" python install --no-bin --no-registry "$_py" \
- || fail "bootstrap Python installation failed"
- boot_py="$(UV_SYSTEM_PYTHON=1 UV_NO_PROJECT=1 "$UV_CMD" python find --managed-python "$_py")" || fail "bootstrap Python lookup failed"
+ || fail "bootstrap Python installation failed" python_install_failed
+ boot_py="$(UV_SYSTEM_PYTHON=1 UV_NO_PROJECT=1 "$UV_CMD" python find --managed-python "$_py")" || fail "bootstrap Python lookup failed" python_install_failed
fi
boot_py="${boot_py%$'\r'}"
- [ -x "$boot_py" ] && "$boot_py" --version >/dev/null 2>&1 || fail "bootstrap Python is not executable: $boot_py"
+ [ -x "$boot_py" ] && "$boot_py" --version >/dev/null 2>&1 || fail "bootstrap Python is not executable: $boot_py" python_install_failed
}
# uv exits before PM can replace its tool entry. pm.cli then prepares and
@@ -693,7 +719,7 @@ bootstrap_pm() {
if [ "$(id -u)" -ne 0 ] && command -v sudo >/dev/null 2>&1; then sudo -n -v 2>/dev/null || :; fi
(cd "$INSTALL_DIR" && run_logged "Installing dependencies (hash-verified via uv.lock)" \
"$boot_py" -m pm.cli "${pm_args[@]}") \
- || fail "pm install failed"
+ || fail "pm install failed" deps_install_failed
log_success "dependencies installed"
}
@@ -730,7 +756,7 @@ append_shell_path() {
return 0
fi
mkdir -p "$(dirname "$rc")"
- printf '\n# Hermes Agent command\n%s\n' "$line" >> "$rc" || fail "cannot update PATH in $rc"
+ printf '\n# Hermes Agent command\n%s\n' "$line" >> "$rc" || fail "cannot update PATH in $rc" filesystem_error
log_success "added ~/.local/bin to PATH in $rc"
}
@@ -777,7 +803,7 @@ stage_products() {
fi
(cd "$INSTALL_DIR" && run_logged "Building the hermes command and apps" \
"$boot_py" -I -B -X utf8 hermes_cli/source_completion.py "${args[@]}") \
- || fail "app products or command publication failed"
+ || fail "app products or command publication failed" products_build_failed
wire_shell_path
log_success "app products and hermes command ready"
}
@@ -815,7 +841,7 @@ stage_setup() {
log "setup skipped (no terminal); run 'hermes setup' after install"
return 0
fi
- "$INSTALL_DIR/.hermes/bin/hermes" setup </dev/tty || fail "setup failed"
+ "$INSTALL_DIR/.hermes/bin/hermes" setup </dev/tty || fail "setup failed" setup_failed
}
stage_gateway() {
@@ -825,7 +851,7 @@ stage_gateway() {
return 0
fi
# Setup installs the service when it handles the gateway; ask only if it did not.
- "$INSTALL_DIR/.hermes/bin/hermes" gateway install --if-missing </dev/tty || fail "gateway installation failed"
+ "$INSTALL_DIR/.hermes/bin/hermes" gateway install --if-missing </dev/tty || fail "gateway installation failed" gateway_failed
}
stage_complete() {
@@ -862,6 +888,7 @@ run_stage() (
set -e
STAGE="$1"
STAGE_REASON=""
+ FAILURE_CLASS=""
STAGE_SKIPPED=false
trap 'stage_result "$?"' EXIT
if [ "$NON_INTERACTIVE" = true ] && { [ "$STAGE" = setup ] || [ "$STAGE" = gateway ]; }; then
@@ -896,6 +923,10 @@ if [ "${BASH_SOURCE[0]:-$0}" = "$0" ]; then
if [ -n "$STAGE" ] && [ "$JSON" = true ]; then
trap 'stage_result "$?"' EXIT
+ elif [ -z "$STAGE" ]; then
+ INSTALL_LADDER=true
+ INSTALL_STARTED="$(date +%s)"
+ trap '[ "$?" -eq 0 ] || write_install_receipt failed prerequisites "${FAILURE_CLASS:-other}"' EXIT
fi
check_platform
trap - EXIT
@@ -913,5 +944,6 @@ if [ "${BASH_SOURCE[0]:-$0}" = "$0" ]; then
rc=$?
[ "$rc" -eq 0 ] || exit "$rc"
done
+ write_install_receipt success none none
print_path_reload_hint
fi
diff --git a/tests/hermes_cli/test_shared_metrics_install_run.py b/tests/hermes_cli/test_shared_metrics_install_run.py
new file mode 100644
index 00000000000..156b2025bee
--- /dev/null
+++ b/tests/hermes_cli/test_shared_metrics_install_run.py
@@ -0,0 +1,155 @@
+"""hermes.install.run: the installers' local receipt, counted by a later start only while collection is on."""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+import shutil
+import subprocess
+import sys
+import time
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+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_install_run as install_run
+from hermes_cli.observability import shared_metrics_process as process_metrics
+
+ROOT = Path(__file__).resolve().parents[2]
+INSTALL_SH = ROOT / "scripts" / "install.sh"
+INSTALL_PS1 = ROOT / "scripts" / "install.ps1"
+SCHEMA = ROOT / "hermes_cli" / "observability" / "schemas" / "hermes.shared_metrics.v4.schema.json"
+
+
+def marks(tmp_path, monkeypatch):
+ captured: list[tuple[str, dict]] = []
+ policy = {"on": True}
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
+ monkeypatch.setattr(
+ "hermes_cli.config.read_raw_config_readonly",
+ lambda: {"telemetry": {"shared_metrics": {"enabled": policy["on"]}}},
+ )
+ monkeypatch.setattr(relay_shared_metrics, "enabled", lambda: policy["on"])
+ store = {"saves": True}
+
+ def saved(rows):
+ if store["saves"]:
+ captured.extend(rows)
+ return len(rows) if store["saves"] else 0
+
+ monkeypatch.setattr(relay_shared_metrics, "record_process_marks_saved", saved, raising=False)
+ yield SimpleNamespace(rows=captured, policy=policy, home=tmp_path / "home", store=store)
+
+
+def _receipt(**overrides) -> dict:
+ now = int(time.time())
+ receipt = {"id": "ab" * 16, "installer": "install_sh", "outcome": "failed", "failed_stage": "repository",
+ "failure_class": "git_clone_failed", "started_at": now - 200, "finished_at": now}
+ return {**receipt, **overrides}
+
+
+def _park(home: Path, receipt: dict, name: str | None = None) -> Path:
+ directory = install_run.pending_installs_dir(home)
+ directory.mkdir(parents=True, exist_ok=True)
+ path = directory / f"{name or receipt.get('id', 'x')}.json"
+ path.write_text(json.dumps(receipt), encoding="utf-8")
+ return path
+
+
+def test_schema_and_installers_match_the_contract_exactly():
+ schema = json.loads(SCHEMA.read_text(encoding="utf-8"))
+ by_name = {d["properties"]["name"]["const"]: d for d in schema["$defs"].values() if "properties" in d}
+ dims = by_name[contract.INSTALL_RUN_METRIC]["properties"]["dimensions"]
+ assert {field: set(spec["enum"]) for field, spec in dims["properties"].items()} == {
+ field: set(values) for field, values in contract._COUNTER_DIMENSION_VALUES[contract.INSTALL_RUN_METRIC].items()}
+ assert set(dims["required"]) == set(dims["properties"])
+ assert {"$ref": "#/$defs/install_run_counter"} in schema["properties"]["metrics"]["items"]["oneOf"]
+
+ sh, ps1 = INSTALL_SH.read_text(encoding="utf-8"), INSTALL_PS1.read_text(encoding="utf-8")
+ # Every fail()/Fail call site passes a class from the contract, and every class is used somewhere.
+ sh_sites = re.findall(r'(?<![-\w])fail "(?:[^"\\$]|\\.|\$\([^)]*\)|\$)*" ?([a-z_]*)', sh)
+ ps1_sites = re.findall(r'(?<![-\w])Fail "(?:[^"`$]|`.|\$\([^)]*\)|\$)*" ?([a-z_$(]*)', ps1)
+ assert sh_sites and ps1_sites
+ assert "" not in sh_sites, "an install.sh fail() call site passes no failure class"
+ assert "" not in ps1_sites, "an install.ps1 Fail call site passes no failure class"
+ used = {c for c in sh_sites + ps1_sites if not c.startswith("$")} | {"setup_failed", "gateway_failed"}
+ assert used | {"interrupted", "none", "other"} == contract.INSTALL_RUN_FAILURE_CLASSES
+ stage_names = re.search(r"stage_names\(\) \{\n\s+printf '%s\\n' ([a-z -]+)\n", sh).group(1).split()
+ assert {s.replace("-", "_") for s in stage_names} == contract.INSTALL_RUN_STAGES
+ ps1_stages = re.findall(r'@\{ name = "([a-z-]+)"', ps1)
+ assert {s.replace("-", "_") for s in ps1_stages} == contract.INSTALL_RUN_STAGES
+
+
+def test_receipt_is_reported_once_out_of_contract_ones_dropped(marks):
+ good = _park(marks.home, _receipt())
+ success = _park(marks.home, _receipt(id="cd" * 16, installer="install_ps1", outcome="success",
+ failed_stage="none", failure_class="none"))
+ bad = [
+ _park(marks.home, _receipt(id="01" * 16, failure_class="git clone of https://host/x failed")),
+ _park(marks.home, _receipt(id="02" * 16, failed_stage="/home/someone")),
+ _park(marks.home, {**_receipt(id="03" * 16), "reason": "free text"}),
+ _park(marks.home, _receipt(id="04" * 16, outcome="success")), # success naming a failed stage
+ ]
+ marks.store["saves"] = False # a busy store keeps every in-contract receipt for the next start
+ install_run.report_pending_installs(marks.home)
+ assert good.exists() and success.exists() and not any(p.exists() for p in bad)
+ assert marks.rows == []
+
+ marks.store["saves"] = True
+ install_run.report_pending_installs(marks.home)
+ _park(marks.home, _receipt()) # the same receipt left behind by a failed delete
+ install_run.report_pending_installs(marks.home)
+ assert sorted(marks.rows, key=lambda r: r[1]["outcome"]) == [
+ (contract.INSTALL_RUN_MARK, {"duration_bucket": "2m_to_5m", "failed_stage": "repository",
+ "failure_class": "git_clone_failed", "installer": "install_sh", "outcome": "failed"}),
+ (contract.INSTALL_RUN_MARK, {"duration_bucket": "2m_to_5m", "failed_stage": "none",
+ "failure_class": "none", "installer": "install_ps1", "outcome": "success"}),
+ ]
+ assert list(install_run.pending_installs_dir(marks.home).iterdir()) == []
+ for mark, data in marks.rows:
+ assert contract.counter_dimensions_are_valid(contract._DECISION_MARK_METRICS[mark], data)
+
+
+def test_start_with_collection_off_purges_receipts_unreported(marks, monkeypatch):
+ receipt = _park(marks.home, _receipt())
+ monkeypatch.setattr(process_metrics, "_STATE", {})
+ marks.policy["on"] = False
+ process_metrics.begin_process("cli")
+ assert not receipt.parent.exists()
+ marks.policy["on"] = True
+ install_run.report_pending_installs(marks.home)
+ assert marks.rows == []
+
+
[email protected](sys.platform == "win32", reason="runs the real install.sh")
+def test_real_install_sh_ladder_leaves_only_closed_tokens(tmp_path):
+ """The real ladder with git missing from PATH fails in prerequisites and parks one closed receipt."""
+ tools = tmp_path / "bin"
+ tools.mkdir()
+ for name in ("bash", "uname", "date", "od", "tr", "mkdir", "mv", "curl", "id", "cat", "dirname"):
+ found = shutil.which(name)
+ if found:
+ (tools / name).symlink_to(found)
+ home = tmp_path / "hermes home"
+ result = subprocess.run(
+ [str(tools / "bash"), str(INSTALL_SH), "--non-interactive", "--hermes-home", str(home),
+ "--dir", str(tmp_path / "checkout")],
+ env={"HOME": str(tmp_path), "PATH": str(tools), "HERMES_REPO_URL": "https://example.invalid/x.git"},
+ capture_output=True, text=True, encoding="utf-8", timeout=60,
+ )
+ assert result.returncode == 1, result.stdout + result.stderr
+ assert "git is required" in result.stderr
+ receipts = list(install_run.pending_installs_dir(home).glob("*.json"))
+ assert len(receipts) == 1
+ text = receipts[0].read_text(encoding="utf-8")
+ assert "example.invalid" not in text and str(tmp_path) not in text and "required" not in text
+ receipt = json.loads(text)
+ assert install_run.install_run_fields(receipt) == {
+ "duration_bucket": "lt_30s", "failed_stage": "prerequisites", "failure_class": "git_missing",
+ "installer": "install_sh", "outcome": "failed",
+ }
diff --git a/website/docs/developer-guide/relay-shared-metrics.md b/website/docs/developer-guide/relay-shared-metrics.md
index 22635676786..caee729267b 100644
--- a/website/docs/developer-guide/relay-shared-metrics.md
+++ b/website/docs/developer-guide/relay-shared-metrics.md
@@ -508,6 +508,13 @@ they failed. Rows recorded before the change keep their old field set and still
| `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. 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 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`. |
<!-- ---- end iuf c1 ---- -->
+<!-- ---- iuf c2 ---- -->
+#### Fresh installs
+
+| Metric | Dimensions | Question it answers |
+|---|---|---|
+| `hermes.install.run` | installer (`install_sh`, `install_ps1`, `other`), outcome (`success`, `failed`), failed_stage (`prerequisites`, `repository`, `venv`, `python_deps`, `config`, `products`, `setup`, `gateway`, `complete`, `other`; `none` on success), failure_class (`unsupported_platform`, `download_failed`, `download_digest_mismatch`, `uv_unusable`, `git_missing`, `curl_missing`, `libstdcxx_missing`, `git_extract_failed`, `dir_not_checkout`, `git_clone_failed`, `git_fetch_failed`, `local_changes_blocked`, `git_checkout_failed`, `git_reset_failed`, `commit_not_on_branch`, `filesystem_error`, `python_install_failed`, `deps_install_failed`, `products_build_failed`, `setup_failed`, `gateway_failed`, `interrupted`, `other`; `none` on success), duration bucket (`lt_30s` … `gte_15m`) | How often a fresh `install.sh` / `install.ps1` run succeeds, and at which stage and for which closed reason it fails. The installer runs before the consent question and never sends anything: a full run (not a single `--stage` / `-Stage` call, so the Desktop bootstrap installer's per-stage calls are not counted) leaves one small local file under `$HERMES_HOME/telemetry/shared_metrics/pending_installs/` holding only these tokens, a random id and the start/finish times (never the error text, paths, URLs or host names). The next Hermes start in that profile counts it once, and only when collection is on at that moment; a start with collection off deletes the files unreported. So a failed install is counted only once a later install or Hermes start in the same profile succeeds with collection on; a failed install that is never followed by one is never counted. |
+<!-- ---- end iuf c2 ---- -->
Local state is written under: