Skip to content

The agent that grows with you

feat(desktop): bundle, publish, and update the desktop app as MSIX

ethernet47f4ab3a1787
diff --git a/.github/workflows/deploy-site.yml b/.github/workflows/deploy-site.yml
index 26e11ee9fb3..df0a42d51db 100644
--- a/.github/workflows/deploy-site.yml
+++ b/.github/workflows/deploy-site.yml
@@ -63,7 +63,7 @@ jobs:
client-id: ${{ vars.APP_CLIENT_ID }}
private-key: ${{ secrets.APP_PRIVATE_KEY }}
- - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
+ - uses: actions/[email protected] # immutable release. safe to pin.
with:
node-version: 26
cache: npm
diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml
index f245708486f..c0db414b5d2 100644
--- a/.github/workflows/docker.yml
+++ b/.github/workflows/docker.yml
@@ -94,6 +94,9 @@ jobs:
- name: Checkout code
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ - name: Write install stamp
+ run: python3 scripts/write_install_stamp.py --output install-stamp.json --distribution docker --update-mechanism external --source ci
+
# Retry once on transient Docker Hub / buildkit pull failures
# (connection reset, auth token timeout, rate limiting). The action
# generates a unique builder name per invocation so the retry doesn't
@@ -119,8 +122,6 @@ jobs:
load: true
platforms: ${{ matrix.platform }}
tags: ${{ env.IMAGE_NAME }}:test
- build-args: |
- HERMES_GIT_SHA=${{ github.sha }}
cache-from: ${{ matrix.cache-from }}
cache-to: ${{ (github.event_name != 'pull_request') && matrix.cache-to || '' }}
@@ -206,6 +207,9 @@ jobs:
- name: Checkout trusted source
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ - name: Write install stamp
+ run: python3 scripts/write_install_stamp.py --output install-stamp.json --distribution docker --update-mechanism external --source ci
+
# Retry once on transient Docker Hub / buildkit pull failures.
# See build job for rationale; same pattern.
- name: Set up Docker Buildx
@@ -234,8 +238,6 @@ jobs:
platforms: ${{ matrix.platform }}
labels: |
org.opencontainers.image.revision=${{ github.sha }}
- build-args: |
- HERMES_GIT_SHA=${{ github.sha }}
outputs: type=image,name=${{ env.IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=true
cache-from: ${{ matrix.cache-from }}
cache-to: ${{ matrix.cache-to }}
diff --git a/.github/workflows/docs-site-checks.yml b/.github/workflows/docs-site-checks.yml
index 1e82698218e..f33af0fc1a2 100644
--- a/.github/workflows/docs-site-checks.yml
+++ b/.github/workflows/docs-site-checks.yml
@@ -13,7 +13,7 @@ jobs:
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
+ - uses: actions/[email protected] # immutable release. safe to pin.
with:
node-version: 26
cache: npm
diff --git a/.github/workflows/e2e-desktop.yml b/.github/workflows/e2e-desktop.yml
index 8692f05d7a4..9c974a56ecd 100644
--- a/.github/workflows/e2e-desktop.yml
+++ b/.github/workflows/e2e-desktop.yml
@@ -40,7 +40,7 @@ jobs:
xdg-utils libatspi2.0-0 libdrm2 libgbm1 libasound2t64
# ── Node ───────────────────────────────────────────────────────────
- - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
+ - uses: actions/[email protected] # immutable release. safe to pin.
with:
node-version: 26
cache: npm
diff --git a/.github/workflows/js-autofix.yml b/.github/workflows/js-autofix.yml
index bd4ee6d1c92..dd341ba5d66 100644
--- a/.github/workflows/js-autofix.yml
+++ b/.github/workflows/js-autofix.yml
@@ -65,7 +65,7 @@ jobs:
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
+ - uses: actions/[email protected] # immutable release. safe to pin.
with:
node-version: 26
cache: npm
diff --git a/.github/workflows/js-tests.yml b/.github/workflows/js-tests.yml
index 956908293c2..c2b707e210d 100644
--- a/.github/workflows/js-tests.yml
+++ b/.github/workflows/js-tests.yml
@@ -18,7 +18,7 @@ jobs:
timeout-minutes: 30
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
+ - uses: actions/[email protected] # immutable release. safe to pin.
with:
node-version: 26
cache: npm
diff --git a/.github/workflows/nightly-release.yml b/.github/workflows/nightly-release.yml
new file mode 100644
index 00000000000..81b1d34942d
--- /dev/null
+++ b/.github/workflows/nightly-release.yml
@@ -0,0 +1,85 @@
+name: Nightly Release
+
+# Publishes the nightly prerelease channel: a dated prerelease versioned
+# NEXT-MINOR over the newest stable tag
+# (v<stable.minor+1>.0-nightly.<YYYYMMDDHHMMSS>), so a nightly always
+# outversions every stable build of the current line and loses to the
+# next stable minor — which is exactly how the electron-updater channel
+# switch works in both directions (see hermes_cli/update_channel.py).
+# Second-precision suffix: manual dispatches can publish several
+# nightlies per day; the scheduled run publishes at most one because
+# release.py skips when HEAD has no new commits since the last nightly.
+#
+# ALL of it lives in scripts/release.py --nightly: the tag math, the
+# skip gate, the draft release, and the dispatch of the desktop build.
+# This workflow only supplies a schedule and credentials, which is why
+# `release.py --nightly --publish` by hand does exactly what the cron
+# does — same tag, same draft, same build, same auto-publish.
+#
+# The desktop build uploads the installers to the Cloudflare R2 release
+# bucket and publishes the draft when the whole matrix is green. A failed
+# matrix leaves a draft: inspectable, re-runnable, and unreachable by
+# users. The prune job deletes both the GitHub releases+tags and the R2
+# nightly objects older than 14 days.
+#
+# schedule: is the ONE sanctioned time trigger in this repo (nightly
+# exemption). Everything else stays event-driven.
+
+on:
+ schedule:
+ - cron: '0 8 * * *' # daily, 0300 EST / 0800 UTC, middle of the night when most stuff will be moving less
+ workflow_dispatch: {}
+
+permissions:
+ contents: write # tag push + release create/delete for prune
+ actions: write # release.py dispatches the desktop build
+
+concurrency:
+ group: nightly-release
+ cancel-in-progress: false
+
+jobs:
+ tag:
+ name: Tag, draft, and start the nightly build
+ runs-on: ubuntu-24.04
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ # The changelog walks commits since the previous nightly tag
+ fetch-depth: 0
+ # the tag math reads the full tag list
+ fetch-tags: true
+
+ - name: Tag and draft
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ git config user.name "github-actions[bot]"
+ git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
+ python3 scripts/release.py --nightly --publish --remote origin
+
+ prune:
+ name: Prune nightlies older than 14 days
+ runs-on: ubuntu-24.04
+ needs: tag
+ environment: release-signing
+ # Prune even when there was nothing to tag today. The desktop build
+ # runs in its own workflow run now, so this no longer waits on it —
+ # the window is 14 days, far wider than any build.
+ if: always() && needs.tag.result != 'cancelled'
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ fetch-depth: 0
+ fetch-tags: true
+ - name: Prune
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: python3 scripts/release.py --prune-nightlies --publish --remote origin
+ - name: Prune R2 nightly objects
+ env:
+ CLOUDFLARE_R2_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_R2_ACCOUNT_ID }}
+ CLOUDFLARE_R2_ACCESS_KEY_ID: ${{ secrets.CLOUDFLARE_R2_ACCESS_KEY_ID }}
+ CLOUDFLARE_R2_SECRET_ACCESS_KEY: ${{ secrets.CLOUDFLARE_R2_SECRET_ACCESS_KEY }}
+ CLOUDFLARE_R2_BUCKET: ${{ vars.CLOUDFLARE_R2_BUCKET }}
+ run: node scripts/r2-release.mjs prune-nightlies --keep-days 14
diff --git a/.github/workflows/pm-bundle.yml b/.github/workflows/pm-bundle.yml
new file mode 100644
index 00000000000..841aba748a9
--- /dev/null
+++ b/.github/workflows/pm-bundle.yml
@@ -0,0 +1,124 @@
+name: PM Bundle
+
+# Stages the self-contained agent payload for each (os, arch) target with
+# `hermes pm bundle`: repo snapshot + tool store + facts + a relocatable
+# venv built on the staged python-build-standalone interpreter. Each
+# payload is smoke-tested on its native runner — the staged interpreter
+# boots hermes_cli out of the payload with no network and no PYTHONPATH —
+# as a pre-merge check for the pm tooling itself.
+#
+# Staging is native per target (no cross-target wheel tables anywhere):
+# the runner IS the target. pm's arch guard fails the job if any staged
+# mismatches, before anything ships.
+
+on:
+ workflow_dispatch:
+ inputs:
+ ref:
+ description: 'Git ref to bundle (default: the triggering ref)'
+ required: false
+ type: string
+ pull_request:
+ paths:
+ - 'pm/**'
+ - 'uv.lock'
+ - 'pyproject.toml'
+ - '.github/workflows/pm-bundle.yml'
+
+permissions:
+ contents: read
+
+concurrency:
+ group: pm-bundle-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ bundle:
+ name: bundle ${{ matrix.target.label }}
+ runs-on: ${{ matrix.target.runner }}
+ timeout-minutes: 45
+ strategy:
+ fail-fast: false
+ matrix:
+ target:
+ - label: linux-x64
+ runner: ubuntu-24.04
+ - label: linux-arm64
+ runner: ubuntu-24.04-arm
+ - label: darwin-arm64
+ runner: macos-15
+ - label: darwin-x64
+ runner: macos-15-intel
+ - label: win32-x64
+ runner: windows-2025
+ - label: win32-arm64
+ runner: windows-11-arm
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ ref: ${{ inputs.ref || github.ref }}
+ fetch-tags: true
+
+ # The host uv only bootstraps a python to run pm itself; every
+ # payload tool (uv included) is staged by pm from pm/lock.json.
+ - uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # 9.0.0
+ with:
+ enable-cache: false
+
+ # One cache for the pm store: keyed on the lockfile, so a pin bump
+ # rotates it. pm verifies every restored entry against the lock
+ # (hash-named fetches, verify() on entries) — the cache is an
+ # optimization, never a proof.
+ - name: Cache pm store
+ uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
+ with:
+ path: build/agent-payload/tools
+ key: pm-store-${{ matrix.target.label }}-${{ hashFiles('pm/lock.json', 'uv.lock') }}
+
+ # win32-arm64 builds cryptography from sdist (no win_arm64 wheel);
+ # its Rust core links OpenSSL statically from vcpkg.
+ - name: Cache vcpkg OpenSSL (arm64)
+ if: matrix.target.label == 'win32-arm64'
+ uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
+ with:
+ path: C:\vcpkg\installed\arm64-windows-static-md
+ key: vcpkg-openssl-arm64-windows-static-md-${{ runner.os }}
+
+ - name: Install OpenSSL (arm64)
+ if: matrix.target.label == 'win32-arm64'
+ shell: bash
+ run: |
+ if [ ! -f "/c/vcpkg/installed/arm64-windows-static-md/lib/libcrypto.lib" ]; then
+ "$VCPKG_INSTALLATION_ROOT/vcpkg" install openssl:arm64-windows-static-md
+ fi
+ {
+ printf 'OPENSSL_DIR=C:\\vcpkg\\installed\\arm64-windows-static-md\n'
+ printf 'OPENSSL_STATIC=1\n'
+ } >> "$GITHUB_ENV"
+
+ - name: Stage the payload
+ shell: bash
+ env:
+ # Windows runners default to cp1252; pm prints UTF-8 (✓/✗).
+ PYTHONUTF8: '1'
+ # ring/obstore's C sources need clang, not MSVC, on windows-arm64.
+ # Scoped to the cargo target triple so every other sdist keeps MSVC.
+ CC_aarch64_pc_windows_msvc: ${{ matrix.target.label == 'win32-arm64' && 'clang' || '' }}
+ run: |
+ # The bootstrap interpreter tracks the payload interpreter's
+ # minor version — one authority (pm/lock.json), no drift.
+ PYVER=$(python3 -c "import json; v=json.load(open('pm/lock.json'))['packages']['python']['version']; print('.'.join(v.split('+')[0].split('.')[:2]))" 2>/dev/null || python -c "import json; v=json.load(open('pm/lock.json'))['packages']['python']['version']; print('.'.join(v.split('+')[0].split('.')[:2]))")
+ # Archive what actions/checkout actually checked out. On
+ # pull_request events github.sha names a merge commit that a
+ # force-push invalidates mid-run ("not a tree object").
+ uv run --no-project --python "$PYVER" python -m pm.cli bundle \
+ --out build/agent-payload \
+ --ref HEAD
+
+ # The payload must boot with nothing from this checkout: the staged
+ # venv's interpreter, cwd at the staged REPO (the desktop spawn
+ # convention — sys.path[0] from cwd survives relocation where the
+ # editable install's absolute path would not), no PYTHONPATH.
+ - name: Smoke test the payload
+ shell: bash
+ run: bash scripts/smoke-payload.sh build/agent-payload
diff --git a/agent/monitoring/otlp_exporter.py b/agent/monitoring/otlp_exporter.py
index 17c85cb8b6a..36e9d30c08c 100644
--- a/agent/monitoring/otlp_exporter.py
+++ b/agent/monitoring/otlp_exporter.py
@@ -34,28 +34,22 @@ class OTLPUnavailable(RuntimeError):
"""Raised when the optional OpenTelemetry SDK isn't installed."""
-def _require_sdk(*, auto_install: bool = True, prompt: bool = True):
+def _require_sdk(*, auto_install: bool = True):
"""Import the OTel SDK, lazily installing it on first use if needed.
- Routes through tools.lazy_deps (feature 'export.otlp') so a missing SDK
+ Routes through pm.ensure_import('otlp') so a missing SDK
triggers the standard venv install flow — same as every other optional
- backend — gated by security.allow_lazy_installs and TTY-prompted. Falls back
- to OTLPUnavailable (with a manual install hint) when the SDK can't be made
+ backend — gated by security.allow_lazy_installs. Falls back to
+ OTLPUnavailable (with a manual install hint) when the SDK can't be made
importable (lazy installs disabled, install failed, or auto_install=False).
-
- ``auto_install``: attempt the lazy install when missing (default True).
- ``prompt``: ask before installing when interactive (default True); pass
- False from non-interactive contexts like the continuous streamer.
"""
if auto_install:
try:
- from tools.lazy_deps import ensure as _lazy_ensure
- _lazy_ensure("export.otlp", prompt=prompt)
- except ImportError:
- pass # lazy_deps unavailable — fall through to the import attempt
+ from pm import ensure_import as _lazy_ensure
+ _lazy_ensure("otlp")
except Exception:
- # FeatureUnavailable (lazy installs disabled / declined / failed) —
- # fall through; the import below raises OTLPUnavailable with the hint.
+ # Any lazy-install failure — fall through; the import below
+ # raises OTLPUnavailable with the hint.
pass
try:
from opentelemetry.sdk.trace import TracerProvider
@@ -240,7 +234,7 @@ def start_streaming(
``event_filter`` scopes the exporter to its plane, e.g. gateway-health
export, so enabling one plane cannot silently export unrelated events.
- Non-interactive context (startup): attempts a lazy install with prompt=False
+ Non-interactive context (startup): attempts a lazy install
so a configured-but-missing SDK is installed once (gated by
security.allow_lazy_installs), then streams. If it still can't load, logs and
no-ops — never blocks or raises into startup.
@@ -248,7 +242,7 @@ def start_streaming(
if not is_enabled(config):
return None
try:
- _require_sdk(prompt=False)
+ _require_sdk()
except OTLPUnavailable:
logger.warning("monitoring.export.otlp.enabled but the OTel SDK could not "
"be installed/imported; install 'hermes-agent[otlp]'")
diff --git a/apps/desktop/BUILDING.md b/apps/desktop/BUILDING.md
new file mode 100644
index 00000000000..52a260e72e4
--- /dev/null
+++ b/apps/desktop/BUILDING.md
@@ -0,0 +1,123 @@
+# Building the Desktop Installers
+
+This document tells you how the bundled desktop installers are built, and how
+to build and test one on your machine. For the app architecture, read
+`AGENTS.md` in this directory.
+
+## What a bundle is
+
+A bundled installer contains the full Hermes runtime. The user installs one
+file and gets everything. Nothing downloads at first launch.
+
+The installer contains:
+
+- The Electron app (the chat surface).
+- The agent source tree at the release tag, without `.git`.
+- `uv` and a CPython interpreter for the target architecture.
+- A ready `site-packages` tree, built from the lockfile.
+- A Node runtime and the prebuilt JS surfaces (ui-tui, dashboard SPA).
+- An install stamp (`install-stamp.json`) recording the tag, the commit, the
+ distribution, the update mechanism, and where the managed runtime dir
+ lives.
+
+The app runs the backend directly from its own resources. This is the
+"bundled" install axis, built by `pm bundle` against the `pm/lock.json` pin
+table — every managed tool (uv, python, node, npm, ripgrep, git, chromium,
+cua-driver) is digest-pinned and staged at build time.
+
+## The installer for each platform
+
+| Platform | Artifact | Notes |
+|---|---|---|
+| Windows | MSIX `.msix` / `.msixbundle` | The shipping artifact. Signed with Azure Trusted Signing. Out-of-store installs update via the OS App Installer (.appinstaller source; the app checks + prompts, the OS applies). Store-submission builds (HERMES_DESKTOP_VARIANT=store) use the Partner Center identity and update via the Store. |
+| macOS | `.dmg` | Signed and notarized when the `APPLE_*` / `CSC_*` secrets are set. Updated via electron-updater against the `latest-mac.yml` feed. |
+| Linux | unpacked / AppImage | Unsigned. |
+
+NSIS is intentionally dead (D1 decision): Windows ships MSIX only.
+
+## How the build works
+
+One script drives the whole build:
+
+```
+node scripts/build-bundled-desktop.mjs --tag=vX.Y.Z
+```
+
+The script always runs every step:
+
+1. **Gate the toolchain.** The host `node` and `npm` must satisfy
+ `package.json` engines, and the toolchain pins resolve from
+ `pm/lock.json` (the "Resolve toolchain pins" CI step). The payload embeds
+ these exact pinned versions, so gate == embed.
+2. **Build the JS surfaces.** ui-tui (with hermes-ink) and the dashboard SPA.
+3. **Build the desktop app.** `npm run build` in `apps/desktop`: vite,
+ electron-main bundle, native deps, then payload staging.
+4. **Stage the agent payload** (`pm bundle`). This snapshots the repo at the
+ tag with `git archive`, copies the prebuilt JS surfaces in, installs the
+ pinned CPython and `site-packages`, stages the pinned managed tools, and
+ writes `manifest.json` plus the install stamp. Each staged binary must
+ prove the target architecture in its own version banner. A wrong-
+ architecture binary fails the build.
+5. **Package with electron-builder.** MSIX on Windows, DMG on macOS.
+
+Payload staging stays dormant unless `HERMES_DESKTOP_VARIANT=bundled` is
+set. The build script sets it. A normal `npm run dev` or `npm run pack`
+without the script does not stage payloads.
+
+## Code signing (Windows)
+
+Signing turns on when the `AZURE_SIGN_*` environment variables are set:
+
+```
+AZURE_SIGN_ENDPOINT https://cus.codesigning.azure.net
+AZURE_SIGN_ACCOUNT codesign2
+AZURE_SIGN_PROFILE hermesagent
+AZURE_SIGN_PUBLISHER CN=Nous Research Inc., ...
+AZURE_CLIENT_ID (the OIDC app id)
+```
+
+`electron-builder.config.cjs` reads these variables and composes the
+`win.sign` configuration itself. Do not pass the values as `-c` arguments:
+the publisher name contains spaces, and spaces do not survive the cmd.exe
+argument hop. Signing runs through `scripts/sign-msix.mjs`, a plain hook
+that signs ONLY the .msix package: Windows validates the package signature
+(AppxSignature.p7x over AppxBlockMap.xml), and inner binaries are covered
+by the block-map hashes — per-file Authenticode is neither required nor
+validated.
+
+On win32, `scripts/after-pack.mjs` runs `sanitize-pe-signatures.mjs` before
+the MSIX pack: python-build-standalone's `llvm-strip` can leave dangling PE
+certificate tables, and one dangling table fails the whole package with
+0x800700C1. This is a hard-fail step, not best-effort.
+
+## The MSIX manifest
+
+`assets/msix-manifest.xml` is the stock app-builder-lib template plus the
+`uap5`/`desktop4` namespaces needed by the CLI execution aliases, and the
+`uap3` fragment (declared on its own root) that registers the app as a
+Windows Copilot hardware key provider. The extensions file
+(`build/msix-extensions.xml`) is generated at config-require time by
+`writeMsixExtensions()` in `electron-builder.config.cjs`. Keep the manifest
+in sync with app-builder-lib when electron-builder bumps.
+
+## Code signing (macOS)
+
+The macOS build signs and notarizes with electron-builder's builtin
+notarization when the `APPLE_ID` / `APPLE_APP_SPECIFIC_PASSWORD` /
+`APPLE_TEAM_ID` secrets are present. The `sign-nested-chromium` path is dead
+(the browser ships in the payload; nested signing is handled by the
+electron-builder signing pass).
+
+## Local build
+
+```
+cd apps/desktop
+npm install
+npm run dist:win:msix # or dist:mac / dist:linux
+```
+
+For a fast dev loop without payload staging:
+
+```
+npm run dev # vite + electron against a dev backend
+```
diff --git a/apps/desktop/README.md b/apps/desktop/README.md
index 997cb72846c..12ef67797bd 100644
--- a/apps/desktop/README.md
+++ b/apps/desktop/README.md
@@ -78,7 +78,7 @@ npm run dev:fake-boot # exercise the startup overlay with deterministic delays
```bash
npm run dist:mac # DMG + zip
-npm run dist:win # NSIS + MSI
+npm run dist:win # MSIX
npm run dist:linux # AppImage + deb + rpm
npm run pack # unpacked app under release/ (no installer)
```
diff --git a/apps/desktop/assets/appx/Square150x150Logo.png b/apps/desktop/assets/appx/Square150x150Logo.png
new file mode 100644
index 00000000000..79d8af456b9
Binary files /dev/null and b/apps/desktop/assets/appx/Square150x150Logo.png differ
diff --git a/apps/desktop/assets/appx/Square44x44Logo.png b/apps/desktop/assets/appx/Square44x44Logo.png
new file mode 100644
index 00000000000..cc8d3b428be
Binary files /dev/null and b/apps/desktop/assets/appx/Square44x44Logo.png differ
diff --git a/apps/desktop/assets/appx/StoreLogo.png b/apps/desktop/assets/appx/StoreLogo.png
new file mode 100644
index 00000000000..a9c5137d7b2
Binary files /dev/null and b/apps/desktop/assets/appx/StoreLogo.png differ
diff --git a/apps/desktop/assets/appx/Wide310x150Logo.png b/apps/desktop/assets/appx/Wide310x150Logo.png
new file mode 100644
index 00000000000..8cbae317739
Binary files /dev/null and b/apps/desktop/assets/appx/Wide310x150Logo.png differ
diff --git a/apps/desktop/assets/msix-manifest.xml b/apps/desktop/assets/msix-manifest.xml
new file mode 100644
index 00000000000..01d3132eacf
--- /dev/null
+++ b/apps/desktop/assets/msix-manifest.xml
@@ -0,0 +1,57 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Custom MSIX manifest for Hermes desktop.
+
+ Forked from app-builder-lib's templates/msix/appxmanifest.xml. The PM
+ payload console-script aliases are uap5 extensions. The package root
+ must declare uap5 and list it in IgnorableNamespaces.
+
+ Keep this template in sync with app-builder-lib when electron-builder
+ changes. The only intended delta is the uap5 namespace declaration and
+ IgnorableNamespaces entry.
+-->
+<!--suppress XmlUnusedNamespaceDeclaration -->
+<Package
+ xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
+ xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
+ xmlns:uap5="http://schemas.microsoft.com/appx/manifest/uap/windows10/5"
+ xmlns:uap10="http://schemas.microsoft.com/appx/manifest/uap/windows10/10"
+ xmlns:desktop="http://schemas.microsoft.com/appx/manifest/desktop/windows10"
+ xmlns:desktop4="http://schemas.microsoft.com/appx/manifest/desktop/windows10/4"
+ xmlns:desktop6="http://schemas.microsoft.com/appx/manifest/desktop/windows10/6"
+ xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
+ IgnorableNamespaces="uap5 uap10 desktop4 desktop6">
+ <!-- use single quotes to avoid double quotes escaping in the publisher value -->
+ <Identity Name="${identityName}"
+ ProcessorArchitecture="${arch}"
+ Publisher='${publisher}'
+ Version="${version}" />
+ <Properties>
+ <DisplayName>${displayName}</DisplayName>
+ <PublisherDisplayName>${publisherDisplayName}</PublisherDisplayName>
+ <Description>${description}</Description>
+ <Logo>${logo}</Logo>
+ ${packageIntegrity}
+ </Properties>
+ <Resources>
+ ${resourceLanguages}
+ </Resources>
+ <Dependencies>
+ <TargetDeviceFamily Name="Windows.Desktop" MinVersion="${minVersion}" MaxVersionTested="${maxVersionTested}" />
+ </Dependencies>
+ ${capabilities}
+ <Applications>
+ <Application Id="${applicationId}" Executable="${executable}" EntryPoint="Windows.FullTrustApplication">
+ <uap:VisualElements
+ BackgroundColor="${backgroundColor}"
+ DisplayName="${displayName}"
+ Square150x150Logo="${square150x150Logo}"
+ Square44x44Logo="${square44x44Logo}"
+ Description="${description}">
+ ${defaultTile}
+ ${lockScreen}
+ ${splashScreen}
+ </uap:VisualElements>
+ ${extensions}
+ </Application>
+ </Applications>
+</Package>
diff --git a/apps/desktop/electron/active-runtime-state.ts b/apps/desktop/electron/active-runtime-state.ts
index 6d922a46277..8b42be2dfa3 100644
--- a/apps/desktop/electron/active-runtime-state.ts
+++ b/apps/desktop/electron/active-runtime-state.ts
@@ -7,6 +7,10 @@ export interface ActiveRuntimeState {
hasValidMarker: boolean
shouldUseActiveRuntime: boolean
usabilityReason: 'usable' | 'unusable'
+ /** The canonical-root install stamp (written by the bootstrap), when the
+ * active runtime was desktop-installed. Populated by the caller
+ * (main.ts activeRuntimeState); undefined when never set. */
+ canonicalInstallStamp?: { source?: unknown; commit?: unknown; branch?: unknown } | null
}
export function hasValidBootstrapMarker(
diff --git a/apps/desktop/electron/app-updater.test.ts b/apps/desktop/electron/app-updater.test.ts
new file mode 100644
index 00000000000..c0cb2d4016f
--- /dev/null
+++ b/apps/desktop/electron/app-updater.test.ts
@@ -0,0 +1,97 @@
+import assert from 'node:assert/strict'
+
+import { test } from 'vitest'
+
+import {
+ checkAppInstallerUpdate,
+ PLACEHOLDER_FEED_BASE_URL,
+ triggerAppInstallerUpdate,
+ win32AppInstallerFeedPath
+} from './app-updater'
+
+// ── feed hosting + paths ────────────────────────────────────────────
+
+test('the feed base URL placeholder is a documented dead end', () => {
+ // Overridden by `updates.desktop_feed_base_url` (read inline in main.ts);
+ // the placeholder itself must never resolve to a real host.
+ assert.equal(PLACEHOLDER_FEED_BASE_URL, 'https://updates.invalid/hermes-desktop')
+})
+
+test('win32 App Installer feed paths are per-channel and per-variant', () => {
+ assert.equal(win32AppInstallerFeedPath('stable', false), 'win32/stable/')
+ assert.equal(win32AppInstallerFeedPath('nightly', false), 'win32/nightly/')
+ assert.equal(win32AppInstallerFeedPath('stable', true), 'win32/light/stable/')
+ assert.equal(win32AppInstallerFeedPath('nightly', true), 'win32/light/nightly/')
+})
+
+// ── win32 arm (OS App Installer checker + trigger) ─────────────────
+
+function fakePayloadRunner(stdout: string, code = 0) {
+ const calls: string[] = []
+ return {
+ runner: {
+ python: 'C:\\payload\\tools\\cpython\\python.exe',
+ script: 'C:\\payload\\scripts\\check-appinstaller-update.py',
+ run: async (python: string, script: string) => {
+ calls.push(`${python} ${script}`)
+ return { code, stdout }
+ }
+ } as any,
+ calls
+ }
+}
+
+test('win32 check reports available when the OS says a newer package exists', async () => {
+ const { runner } = fakePayloadRunner(JSON.stringify({ available: true, availability: 'Available' }))
+ const result = await checkAppInstallerUpdate(runner)
+
+ assert.equal(result.available, true)
+ assert.equal(result.availability, 'Available')
+})
+
+test('win32 check reports not-available cleanly', async () => {
+ const { runner } = fakePayloadRunner(JSON.stringify({ available: false, availability: 'NoApplicableUpdate' }))
+ const result = await checkAppInstallerUpdate(runner)
+
+ assert.equal(result.available, false)
+})
+
+test('win32 check surfaces an unknown verdict (missing winrt) without crashing', async () => {
+ const { runner } = fakePayloadRunner(JSON.stringify({ available: null, error: 'winrt import failed' }), 1)
+ const result = await checkAppInstallerUpdate(runner)
+
+ assert.equal(result.available, null)
+ assert.match(result.error || '', /winrt import failed/)
+})
+
+test('win32 trigger opens ms-appinstaller with the channel .appinstaller after teardown', async () => {
+ const calls: string[] = []
+ const shell = {
+ openExternal: async (url: string) => void calls.push(`open:${url}`)
+ }
+
+ const result = await triggerAppInstallerUpdate(
+ 'https://updates.example.com/',
+ 'stable',
+ false,
+ shell as any,
+ () => void calls.push('teardown')
+ )
+
+ assert.equal(result.ok, true)
+ assert.deepEqual(calls, [
+ 'teardown',
+ 'open:ms-appinstaller:?source=https%3A%2F%2Fupdates.example.com%2Fwin32%2Fstable%2Fstable.appinstaller'
+ ])
+})
+
+test('win32 trigger light+nightly targets the light nightly feed dir', async () => {
+ const calls: string[] = []
+ const shell = {
+ openExternal: async (url: string) => void calls.push(url)
+ }
+
+ await triggerAppInstallerUpdate('https://updates.example.com', 'nightly', true, shell as any)
+
+ assert.equal(calls[0], 'ms-appinstaller:?source=https%3A%2F%2Fupdates.example.com%2Fwin32%2Flight%2Fnightly%2Fnightly.appinstaller')
+})
diff --git a/apps/desktop/electron/app-updater.ts b/apps/desktop/electron/app-updater.ts
new file mode 100644
index 00000000000..39e06655056
--- /dev/null
+++ b/apps/desktop/electron/app-updater.ts
@@ -0,0 +1,137 @@
+// app-updater.ts — the win32 update arm for bundled desktop installs.
+//
+// win32 — the OS App Installer owns the apply. The package was installed
+// from an .appinstaller, which registered the feed URI as the
+// package's update source; the OS checks it and swaps the package
+// wholesale. The app's only job is the checker: ask the OS whether
+// an update is available (via the bundled payload python's winrt),
+// show its own prompt, run graceful teardown, then trigger
+// ms-appinstaller: and quit. Installations that Windows manages
+// for us — Microsoft Store deployments (process.windowsStore) and
+// stamps whose updateMechanism is 'external' — get NO in-app
+// updater at all: the store/steward owns the update loop.
+//
+// Source installs never reach this module. The callers gate on the install
+// stamp first and fall through to the git-based update path.
+//
+// NOTE: the darwin electron-updater arm (and its gate/channel/feed helpers —
+// shouldUseAppUpdater, selectUpdaterArm, resolveUpdaterChannel,
+// resolveFeedBaseUrl, feedSelection, describeFeedCheck) was ripped out in
+// wt/darwin-updater: main.ts reimplemented the gate/channel/feed inline, so
+// the module surface was test-only. To add macOS in-app updates back, restore
+// the arm from git history (this file @ the parent of that commit) together
+// with the `electron-updater` dependency and its test block — see the
+// add-back plan in the wt/darwin-updater commit message.
+//
+// The win32 helpers are pure so vitest covers them; the impure pieces
+// (electron shell, payload python) are injected.
+
+// ─── feed hosting ───────────────────────────────────────────────────────────
+
+/**
+ * PLACEHOLDER — the default base URL of the desktop release feeds.
+ *
+ * W3 (R2 hosting) supplies the real value; until it lands, this default is
+ * a documented dead end that config overrides (`updates.desktop_feed_base_url`
+ * in config.yaml — read inline by main.ts). Layout under the base:
+ *
+ * <base>/win32/<channel>/ — App Installer feed dir (.appinstaller
+ * + .msixbundle) for out-of-store MSIX.
+ *
+ * `<channel>` is 'stable' or 'nightly'.
+ */
+export const PLACEHOLDER_FEED_BASE_URL = 'https://updates.invalid/hermes-desktop'
+
+/**
+ * The App Installer feed dir for a channel. The .appinstaller for a channel
+ * lives under this dir; the OS re-reads it on launch (HoursBetweenUpdateChecks)
+ * and swaps the bundle when a newer version is there. The light variant feeds
+ * from its own subtree so the two variants can never serve each other's
+ * packages.
+ */
+export function win32AppInstallerFeedPath(
+ channel: 'stable' | 'nightly',
+ light: boolean
+): string {
+ const variant = light ? 'light/' : ''
+ return `win32/${variant}${channel}/`
+}
+
+// ─── win32 arm (OS App Installer checker + trigger) ────────────────────────
+
+/** The result of an App Installer update check. */
+export interface AppInstallerCheck {
+ /** null when the check could not run (no winrt, not packaged, error). */
+ available: boolean | null
+ /** Human-readable availability string from the OS, when reported. */
+ availability?: string
+ error?: string
+}
+
+/**
+ * The payload-python invocation the win32 arm needs. Injectable so vitest
+ * covers the arm without a payload.
+ */
+export interface PayloadPythonRunner {
+ /** Absolute path to the bundled payload python (tools/<entry>/python.exe). */
+ python: string
+ /** The checker script's absolute path. */
+ script: string
+ /** Run the script; resolve with {code, stdout}. */
+ run: (python: string, script: string) => Promise<{ code: number; stdout: string }>
+}
+
+/**
+ * win32 arm: ask the OS whether an App Installer update is available, via
+ * the bundled payload python's winrt (PackageManager.CheckPackageUpdateAvailabilityAsync).
+ * The OS compares the package's registered .appinstaller source against the
+ * installed version; it does NOT download anything.
+ */
+export async function checkAppInstallerUpdate(
+ runner: PayloadPythonRunner
+): Promise<AppInstallerCheck> {
+ const { code, stdout } = await runner.run(runner.python, runner.script)
+ const text = stdout.trim()
+ let parsed: { available?: boolean | null; availability?: string; error?: string; reason?: string } | null = null
+ try {
+ parsed = text ? JSON.parse(text) : null
+ } catch {
+ parsed = null
+ }
+
+ if (parsed && typeof parsed.available === 'boolean') {
+ return { available: parsed.available, availability: parsed.availability, error: parsed.error }
+ }
+ if (parsed && parsed.available === null) {
+ return { available: null, error: parsed.error || 'checker returned unknown' }
+ }
+ if (code !== 0) {
+ return { available: null, error: parsed?.error || `checker exited ${code}` }
+ }
+ return { available: null, error: 'checker returned no availability' }
+}
+
+/**
+ * win32 arm: trigger the OS App Installer to apply the update and quit.
+ * `ms-appinstaller:?source=<feed .appinstaller URL>` makes the OS re-read the
+ * package's update source and install the newer bundle; the app then exits so
+ * the package swap is not contested. `beforeInstall` runs first (backend
+ * teardown while the process is still alive).
+ */
+export async function triggerAppInstallerUpdate(
+ feedBaseUrl: string,
+ channel: 'stable' | 'nightly',
+ light: boolean,
+ shell: { openExternal: (url: string) => Promise<void> },
+ beforeInstall?: () => void | Promise<void>
+): Promise<{ ok: true }> {
+ if (beforeInstall) {
+ await beforeInstall()
+ }
+
+ const appinstallerUrl =
+ `${feedBaseUrl.replace(/\/+$/, '')}/${win32AppInstallerFeedPath(channel, light)}${channel}.appinstaller`
+ await shell.openExternal(`ms-appinstaller:?source=${encodeURIComponent(appinstallerUrl)}`)
+
+ return { ok: true }
+}
diff --git a/apps/desktop/electron/deep-link-route.test.ts b/apps/desktop/electron/deep-link-route.test.ts
new file mode 100644
index 00000000000..31f5a93525b
--- /dev/null
+++ b/apps/desktop/electron/deep-link-route.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from 'vitest'
+
+import { routeDeepLink } from './deep-link-route'
+
+describe('routeDeepLink', () => {
+ it('summons quick entry for the Copilot key press', () => {
+ expect(routeDeepLink('copilot-key', 'start')).toBe('quick-entry')
+ })
+
+ it('ignores the Copilot key release so a tap does not undo the summon', () => {
+ expect(routeDeepLink('copilot-key', 'stop')).toBe('ignore')
+ })
+
+ it('ignores unknown copilot-key paths instead of leaking them to the renderer', () => {
+ expect(routeDeepLink('copilot-key', '')).toBe('ignore')
+ expect(routeDeepLink('copilot-key', 'toggle')).toBe('ignore')
+ })
+
+ it('routes every other deep link to the renderer', () => {
+ expect(routeDeepLink('blueprint', 'morning-brief')).toBe('renderer')
+ expect(routeDeepLink('', '')).toBe('renderer')
+ })
+})
diff --git a/apps/desktop/electron/deep-link-route.ts b/apps/desktop/electron/deep-link-route.ts
new file mode 100644
index 00000000000..9cd83791eb4
--- /dev/null
+++ b/apps/desktop/electron/deep-link-route.ts
@@ -0,0 +1,26 @@
+/**
+ * Where a hermes:// deep link is handled. Pure — main.ts routes on the
+ * result, tests assert the contract.
+ *
+ * 'quick-entry' — summon the ephemeral quick-entry popup in the main
+ * process. Used by the Windows Copilot hardware key: the MSIX manifest
+ * fragment (generated by electron-builder.config.cjs) registers the app
+ * as a copilotkeyprovider whose press activates
+ * <scheme>://copilot-key/start.
+ * A hardware key wants the lightweight composer, not the full window.
+ * 'ignore' — activation noise that must not reach the renderer. The
+ * Copilot key's press-and-hold RELEASE fires copilot-key/stop; a tap
+ * fires start+stop nearly together, so acting on stop would undo the
+ * summon. Unknown copilot-key paths land here too.
+ * 'renderer' — everything else: focus the main window and deliver the
+ * payload to the renderer's deep-link listener (blueprint links etc.).
+ */
+export type DeepLinkRoute = 'ignore' | 'quick-entry' | 'renderer'
+
+export function routeDeepLink(kind: string, name: string): DeepLinkRoute {
+ if (kind === 'copilot-key') {
+ return name === 'start' ? 'quick-entry' : 'ignore'
+ }
+
+ return 'renderer'
+}
diff --git a/apps/desktop/electron/desktop-electron-pin.test.ts b/apps/desktop/electron/desktop-electron-pin.test.ts
index 1428003d3ec..8a27b26d6d6 100644
--- a/apps/desktop/electron/desktop-electron-pin.test.ts
+++ b/apps/desktop/electron/desktop-electron-pin.test.ts
@@ -19,12 +19,14 @@
*
* 1. the Electron dependency is an *exact* version (Electron Builder needs the
* installed binary to match ``electronVersion`` / ``electronDist``), and
- * 2. the dependency, ``build.electronVersion``, and the resolved lockfile entry
- * all agree — so ``npm ci`` installs exactly what the build packages.
+ * 2. the dependency, electron-builder.config.cjs ``electronVersion``, and the
+ * resolved lockfile entry all agree — so ``npm ci`` installs exactly what
+ * the build packages.
*/
import assert from 'node:assert/strict'
import fs from 'node:fs'
+import { createRequire } from 'node:module'
import path from 'node:path'
import { test } from 'vitest'
@@ -67,18 +69,18 @@ test('electron dependency is exactly pinned', () => {
)
})
-test('electron dependency matches build.electronVersion', () => {
- const pkg = desktopPkg()
- const spec = electronSpec(pkg)
- const build = (pkg.build ?? {}) as Record<string, unknown>
- const builderVersion = build.electronVersion as string | undefined
- assert.ok(builderVersion, 'build.electronVersion is missing')
+test('electron dependency matches electron-builder.config.cjs', () => {
+ const spec = electronSpec(desktopPkg())
+ const require = createRequire(import.meta.url)
+ const config = require('../electron-builder.config.cjs') as { electronVersion?: string }
+ const builderVersion = config.electronVersion
+ assert.ok(builderVersion, 'electron-builder.config.cjs electronVersion is missing')
assert.equal(
spec,
builderVersion,
- `electron dependency ("${spec}") must equal build.electronVersion ` +
- `("${builderVersion}"); otherwise electron-builder packages a different ` +
- 'version than npm installs into electronDist.'
+ `electron dependency ("${spec}") must equal electron-builder.config.cjs ` +
+ `electronVersion ("${builderVersion}"); otherwise electron-builder packages ` +
+ 'a different version than npm installs.'
)
})
diff --git a/apps/desktop/electron/desktop-uninstall.test.ts b/apps/desktop/electron/desktop-uninstall.test.ts
index 6d296ee1db9..23ece67cd5a 100644
--- a/apps/desktop/electron/desktop-uninstall.test.ts
+++ b/apps/desktop/electron/desktop-uninstall.test.ts
@@ -14,31 +14,67 @@ import assert from 'node:assert/strict'
import { test } from 'vitest'
import {
+ allowedUninstallModes,
buildPosixCleanupScript,
buildWindowsCleanupScript,
+ installKindAllowsCodeRemoval,
modeRemovesAgent,
modeRemovesUserData,
+ nativeRemovalInstructions,
+ resolveInstallKind,
resolveRemovableAppPath,
shouldRemoveAppBundle,
- UNINSTALL_MODES,
uninstallArgsForMode
} from './desktop-uninstall'
// --- uninstallArgsForMode ---
-test('uninstallArgsForMode maps each mode to the module-runner argv', () => {
- assert.deepEqual(uninstallArgsForMode('gui'), ['-m', 'hermes_cli.uninstall', '--mode', 'gui'])
- assert.deepEqual(uninstallArgsForMode('lite'), ['-m', 'hermes_cli.uninstall', '--mode', 'lite'])
- assert.deepEqual(uninstallArgsForMode('full'), ['-m', 'hermes_cli.uninstall', '--mode', 'full'])
-})
-
test('uninstallArgsForMode throws on an unknown mode (no silent full wipe)', () => {
assert.throws(() => uninstallArgsForMode('nuke'), /Unknown uninstall mode/)
assert.throws(() => uninstallArgsForMode(''), /Unknown uninstall mode/)
})
-test('UNINSTALL_MODES lists exactly the three supported modes', () => {
- assert.deepEqual([...UNINSTALL_MODES].sort(), ['full', 'gui', 'lite'])
+// --- resolveInstallKind / allowedUninstallModes / nativeRemovalInstructions ---
+
+test('resolveInstallKind reads the stamp: distribution nix wins, payload kind means bundled', () => {
+ assert.equal(resolveInstallKind({ distribution: 'nix' }), 'nix')
+ assert.equal(resolveInstallKind({ source: 'nix' }), 'nix')
+ // distribution beats payload: a nix stamp never becomes 'bundled'.
+ assert.equal(resolveInstallKind({ distribution: 'nix', payload: 'bundled' }), 'nix')
+ assert.equal(resolveInstallKind({ distribution: 'desktop-app', payload: 'bundled' }), 'bundled')
+ assert.equal(resolveInstallKind({ payload: 'bundled' }), 'bundled')
+ // light artifacts have no agent code either — same managed flow.
+ assert.equal(resolveInstallKind({ payload: 'light' }), 'bundled')
+ // bootstrap / no stamp facts at all → the classic source/installer flow.
+ assert.equal(resolveInstallKind({ payload: 'bootstrap' }), 'standard')
+ assert.equal(resolveInstallKind({}), 'standard')
+ assert.equal(resolveInstallKind(), 'standard')
+})
+
+test('only standard installs may remove code; managed kinds get data-only', () => {
+ assert.equal(installKindAllowsCodeRemoval('standard'), true)
+ assert.equal(installKindAllowsCodeRemoval('nix'), false)
+ assert.equal(installKindAllowsCodeRemoval('bundled'), false)
+
+ assert.deepEqual(allowedUninstallModes('standard'), ['gui', 'lite', 'full'])
+ assert.deepEqual(allowedUninstallModes('nix'), ['data'])
+ assert.deepEqual(allowedUninstallModes('bundled'), ['data'])
+})
+
+test('nativeRemovalInstructions names the steward per kind and OS', () => {
+ assert.match(nativeRemovalInstructions('nix', 'linux'), /installed by Nix/)
+ assert.match(nativeRemovalInstructions('nix', 'darwin'), /flake or profile/)
+ assert.match(nativeRemovalInstructions('bundled', 'win32'), /Installed apps/)
+ assert.match(nativeRemovalInstructions('bundled', 'darwin'), /Trash/)
+ assert.match(
+ nativeRemovalInstructions('bundled', 'linux', '/home/x/Apps/Hermes.AppImage'),
+ /\/home\/x\/Apps\/Hermes\.AppImage/
+ )
+ assert.match(
+ nativeRemovalInstructions('bundled', 'linux', '/opt/hermes/linux-unpacked'),
+ /app directory at \/opt\/hermes\/linux-unpacked/
+ )
+ assert.match(nativeRemovalInstructions('bundled', 'linux'), /wherever you saved it/)
})
// --- modeRemovesAgent / modeRemovesUserData ---
@@ -47,10 +83,12 @@ test('mode predicates classify what each mode removes', () => {
assert.equal(modeRemovesAgent('gui'), false)
assert.equal(modeRemovesAgent('lite'), true)
assert.equal(modeRemovesAgent('full'), true)
+ assert.equal(modeRemovesAgent('data'), false)
assert.equal(modeRemovesUserData('gui'), false)
assert.equal(modeRemovesUserData('lite'), false)
assert.equal(modeRemovesUserData('full'), true)
+ assert.equal(modeRemovesUserData('data'), true)
})
// --- resolveRemovableAppPath ---
diff --git a/apps/desktop/electron/desktop-uninstall.ts b/apps/desktop/electron/desktop-uninstall.ts
index 3d644865382..20d70a822b1 100644
--- a/apps/desktop/electron/desktop-uninstall.ts
+++ b/apps/desktop/electron/desktop-uninstall.ts
@@ -28,7 +28,102 @@
import path from 'node:path'
-const UNINSTALL_MODES = ['gui', 'lite', 'full']
+import type { ArtifactKind } from './install-stamp'
+
+const UNINSTALL_MODES = ['gui', 'lite', 'full', 'data']
+
+// How this desktop app got onto the machine, read from the install stamp
+// (install-stamp.json) that every packager writes:
+// 'nix' — a Nix build (stamp distribution 'nix'). The store is
+// immutable and the install is owned by Nix tooling, so the
+// app must not remove any code, its own bundle included.
+// 'bundled' — an embedded artifact (agent payload in resources; the
+// stamp has payload:true). There is no agent venv under
+// HERMES_HOME, and the OS owns app removal (Apps & Features
+// / Trash / delete the AppImage).
+// 'standard' — everything else: the git-clone install the desktop
+// installer bootstraps, or a `hermes desktop` source build.
+// The classic script flow (venv python + rm the bundle) works.
+//
+// Only 'standard' installs may remove code. 'nix' and 'bundled' installs
+// may only remove user data (mode 'data') — the app itself is removed the
+// native way, per nativeRemovalInstructions().
+const INSTALL_KINDS = ['nix', 'bundled', 'standard']
+
+/**
+ * Classify the install from the stamp. Pure so it can be unit-tested:
+ * callers pass the stamp fields (`distribution`, `source`, `payload`).
+ * `distribution` is authoritative; `source` is the schema-1 fallback.
+ * The 'bundled' and 'light' artifact kinds both classify as the managed
+ * 'bundled' flow — neither has agent code the app may remove, and the OS
+ * owns app removal.
+ */
+function resolveInstallKind({
+ distribution,
+ source,
+ payload = 'bootstrap'
+}: { distribution?: string | null; source?: string | null; payload?: ArtifactKind } = {}) {
+ if (distribution === 'nix' || source === 'nix') {
+ return 'nix'
+ }
+
+ if (payload === 'bundled' || payload === 'light') {
+ return 'bundled'
+ }
+
+ return 'standard'
+}
+
+/** True when this install kind lets the app remove code (agent / bundle). */
+function installKindAllowsCodeRemoval(kind) {
+ return kind === 'standard'
+}
+
+/**
+ * The modes the uninstall UI may offer for an install kind. Every kind can
+ * remove user data. Only 'standard' may also remove code — there the 'full'
+ * mode already covers data, so 'data' alone is not offered. Managed installs
+ * (nix, bundled) get exactly one destructive action — remove user data —
+ * with app removal handed to the steward via nativeRemovalInstructions().
+ */
+function allowedUninstallModes(kind) {
+ return installKindAllowsCodeRemoval(kind) ? ['gui', 'lite', 'full'] : ['data']
+}
+
+/**
+ * Human instructions for removing the app itself the native way. Used when
+ * the install kind forbids code removal: Windows owns the bundled app
+ * through Apps & Features, macOS through the Trash, a Linux AppImage is a
+ * single file the user placed somewhere, and a Nix install belongs to the
+ * flake / profile that made it. `appPath` is the resolveRemovableAppPath()
+ * result (the AppImage path on Linux), used only to name the exact file.
+ */
+function nativeRemovalInstructions(kind, platform, appPath = null) {
+ if (kind === 'nix') {
+ return (
+ 'This Hermes desktop app was installed by Nix. Uninstall it the same way you installed it: ' +
+ 'remove hermes-agent from your flake or profile, then rebuild.'
+ )
+ }
+
+ if (platform === 'win32') {
+ return 'To uninstall, go to Windows Settings → Apps → Installed apps.'
+ }
+
+ if (platform === 'darwin') {
+ return 'Quit the app and drag Hermes.app from Applications to the Trash.'
+ }
+
+ if (appPath && /\.appimage$/i.test(String(appPath))) {
+ return `Delete the AppImage file at ${appPath}.`
+ }
+
+ if (appPath) {
+ return `Delete the app directory at ${appPath}.`
+ }
+
+ return 'Delete the Hermes AppImage (or app directory) from wherever you saved it.'
+}
/**
* Map an uninstall mode to the `python -m hermes_cli.uninstall` argv (after the
@@ -37,7 +132,7 @@ const UNINSTALL_MODES = ['gui', 'lite', 'full']
* lite/full delete — see the Finding-3 note in buildWindowsCleanupScript.
* Throws on an unknown mode so a typo can't silently become a full wipe.
*/
-function uninstallArgsForMode(mode) {
+function uninstallArgsForMode(mode: string) {
if (!UNINSTALL_MODES.includes(mode)) {
throw new Error(`Unknown uninstall mode: ${mode}`)
}
@@ -45,14 +140,14 @@ function uninstallArgsForMode(mode) {
return ['-m', 'hermes_cli.uninstall', '--mode', mode]
}
-/** True when `mode` removes the agent (lite/full), false for gui-only. */
-function modeRemovesAgent(mode) {
+/** True when `mode` removes the agent code (lite/full), false otherwise. */
+function modeRemovesAgent(mode: string) {
return mode === 'lite' || mode === 'full'
}
-/** True when `mode` removes user data (full only). */
-function modeRemovesUserData(mode) {
- return mode === 'full'
+/** True when `mode` removes user data (full and data). */
+function modeRemovesUserData(mode: string) {
+ return mode === 'full' || mode === 'data'
}
/**
@@ -257,10 +352,15 @@ function buildWindowsCleanupScript({
}
export {
+ allowedUninstallModes,
buildPosixCleanupScript,
buildWindowsCleanupScript,
+ INSTALL_KINDS,
+ installKindAllowsCodeRemoval,
modeRemovesAgent,
modeRemovesUserData,
+ nativeRemovalInstructions,
+ resolveInstallKind,
resolveRemovableAppPath,
shouldRemoveAppBundle,
UNINSTALL_MODES,
diff --git a/apps/desktop/electron/external-open.test.ts b/apps/desktop/electron/external-open.test.ts
new file mode 100644
index 00000000000..646ec2d365c
--- /dev/null
+++ b/apps/desktop/electron/external-open.test.ts
@@ -0,0 +1,136 @@
+/**
+ * Tests for electron/external-open.ts — the single route every external URL
+ * open funnels through. All I/O is injected, so the "open failed → notify"
+ * behavior is asserted without loading electron. Run with the electron test
+ * script that runs electron/*.test.ts (same pattern as native-oauth-login).
+ */
+
+import assert from 'node:assert/strict'
+import type { ChildProcess } from 'node:child_process'
+import { EventEmitter } from 'node:events'
+
+import { test } from 'vitest'
+
+import { type ExternalOpenDeps, openExternalUrl } from './external-open'
+
+function makeDeps(overrides: Partial<ExternalOpenDeps> = {}) {
+ const calls = {
+ opened: [] as string[],
+ fileOpened: [] as string[],
+ notified: [] as Array<[string, string]>,
+ logged: [] as string[]
+ }
+
+ const deps: ExternalOpenDeps = {
+ isWsl: false,
+ spawn: () => {
+ throw new Error('not used')
+ },
+ openExternal: async url => {
+ calls.opened.push(url)
+ },
+ openFile: async raw => {
+ calls.fileOpened.push(raw)
+ },
+ notifyFailure: (url, message) => calls.notified.push([url, message]),
+ log: line => calls.logged.push(line),
+ ...overrides
+ }
+
+ return { deps, calls }
+}
+
+test('resolves ok and opens when openExternal succeeds', async () => {
+ const { deps, calls } = makeDeps()
+
+ const result = await openExternalUrl('https://example.com/x', deps)
+
+ assert.deepEqual(result, { ok: true })
+ assert.deepEqual(calls.opened, ['https://example.com/x'])
+ assert.equal(calls.notified.length, 0)
+})
+
+test('notifies and resolves failed when openExternal rejects', async () => {
+ const { deps, calls } = makeDeps({
+ openExternal: async () => {
+ throw new Error('no method available for opening')
+ }
+ })
+
+ const result = await openExternalUrl('https://example.com', deps)
+
+ assert.deepEqual(result, {
+ ok: false,
+ reason: 'failed',
+ message: 'no method available for opening'
+ })
+ assert.deepEqual(calls.notified, [['https://example.com/', 'no method available for opening']])
+ assert.ok(calls.logged.some(line => line.includes('openExternal failed')))
+})
+
+test('resolves invalid for a URL the route does not open, with no notify', async () => {
+ const { deps, calls } = makeDeps()
+
+ for (const url of ['', 'not a url', 'ftp://x.com']) {
+ const result = await openExternalUrl(url, deps)
+ assert.equal(result.ok, false)
+
+ if (result.ok === false) {
+ assert.equal(result.reason, 'invalid')
+ }
+ }
+
+ assert.equal(calls.opened.length, 0)
+ assert.equal(calls.notified.length, 0)
+})
+
+test('dispatches file:// URLs to openFile', async () => {
+ const { deps, calls } = makeDeps()
+
+ const result = await openExternalUrl('file:///C:/x.html', deps)
+
+ assert.deepEqual(result, { ok: true })
+ assert.deepEqual(calls.fileOpened, ['file:///C:/x.html'])
+})
+
+test('wsl: spawns cmd.exe and resolves ok on the happy path', async () => {
+ const spawned: string[] = []
+ const proc = new EventEmitter() as unknown as ChildProcess
+
+ const { deps } = makeDeps({
+ isWsl: true,
+ spawn: (cmd, args) => {
+ spawned.push(cmd, ...args)
+
+ return proc
+ }
+ })
+
+ const result = await openExternalUrl('https://example.com', deps)
+
+ assert.deepEqual(result, { ok: true })
+ assert.equal(spawned[0], 'cmd.exe')
+ assert.ok(spawned.some(arg => arg === 'https://example.com/'))
+})
+
+test('wsl: falls back to openExternal and notifies when cmd.exe fails to spawn', async () => {
+ const proc = new EventEmitter() as unknown as ChildProcess
+ const { deps, calls } = makeDeps({ isWsl: true, spawn: () => proc })
+
+ deps.openExternal = async url => {
+ calls.opened.push(url)
+ throw new Error('xdg-open missing')
+ }
+
+ const result = await openExternalUrl('https://example.com', deps)
+ assert.deepEqual(result, { ok: true })
+
+ // openExternalUrl's fire-and-forget WSL path resolves before the spawn
+ // error can arrive; drive the error to exercise the fallback.
+ ;(proc as unknown as EventEmitter).emit('error', new Error('ENOENT'))
+
+ await new Promise(resolve => setTimeout(resolve, 20))
+
+ assert.deepEqual(calls.opened, ['https://example.com/'])
+ assert.deepEqual(calls.notified, [['https://example.com/', 'xdg-open missing']])
+})
diff --git a/apps/desktop/electron/external-open.ts b/apps/desktop/electron/external-open.ts
new file mode 100644
index 00000000000..89475f4ea53
--- /dev/null
+++ b/apps/desktop/electron/external-open.ts
@@ -0,0 +1,126 @@
+/**
+ * external-open.ts
+ *
+ * The single route every external URL open in the desktop app flows through.
+ * Electron-free: every side effect (shell.openExternal, spawn, the file
+ * opener, the failure channel) is injected, so the "open failed → notify"
+ * behavior is unit-tested without loading electron — the same shape as
+ * native-oauth-login.ts and connection-config.ts. main.ts wires the real deps.
+ *
+ * A URL is opened exactly once. An open failure is logged and reported
+ * through notifyFailure (the renderer shows a fallback modal with the URL);
+ * the caller reads the result to decide whether an open-failure must also
+ * abort its own flow (the native-OAuth path fails fast, link paths don't).
+ */
+
+import type { ChildProcess, SpawnOptions } from 'node:child_process'
+
+export type ExternalOpenResult =
+ | { ok: true }
+ | { ok: false; reason: 'invalid' }
+ | { ok: false; reason: 'failed'; message: string }
+
+export interface ExternalOpenDeps {
+ isWsl: boolean
+ spawn: (cmd: string, args: readonly string[], opts: SpawnOptions) => ChildProcess
+ openExternal: (url: string) => Promise<void>
+ openFile: (rawUrl: string) => Promise<void>
+ notifyFailure: (url: string, message: string) => void
+ log: (line: string) => void
+}
+
+const SUPPORTED_WEB = ['http:', 'https:', 'mailto:']
+
+export function externalOpenErrorMessage(error: unknown): string {
+ return error instanceof Error ? error.message : String(error)
+}
+
+/**
+ * Open a URL in the system browser. Resolves `invalid` for a URL the route
+ * does not open (empty, malformed, unsupported scheme). NEVER rejects: an open
+ * failure is logged + reported through notifyFailure and resolves `failed`,
+ * so fire-and-forget callers can `void` the result safely.
+ */
+export async function openExternalUrl(
+ rawUrl: string,
+ deps: ExternalOpenDeps
+): Promise<ExternalOpenResult> {
+ const raw = String(rawUrl || '').trim()
+
+ if (!raw) {
+ return { ok: false, reason: 'invalid' }
+ }
+
+ let parsed: URL
+
+ try {
+ parsed = new URL(raw)
+ } catch {
+ return { ok: false, reason: 'invalid' }
+ }
+
+ if (parsed.protocol === 'file:') {
+ try {
+ await deps.openFile(raw)
+ } catch {
+ // main's openFile handles its own fallback; never surfaced here
+ }
+
+ return { ok: true }
+ }
+
+ if (!SUPPORTED_WEB.includes(parsed.protocol)) {
+ return { ok: false, reason: 'invalid' }
+ }
+
+ const url = parsed.toString()
+
+ if (deps.isWsl) {
+ return openViaWsl(url, deps)
+ }
+
+ try {
+ await deps.openExternal(url)
+
+ return { ok: true }
+ } catch (error) {
+ return failOpen(deps, url, error)
+ }
+}
+
+async function openViaWsl(url: string, deps: ExternalOpenDeps): Promise<ExternalOpenResult> {
+ deps.log(`[link] opening via WSL→Windows: ${url}`)
+
+ const proc = deps.spawn('cmd.exe', ['/c', 'start', '""', url], {
+ detached: true,
+ stdio: 'ignore',
+ windowsHide: true
+ })
+
+ // 'error' only fires when the process could not be spawned. In that case
+ // fall back to xdg-open; if that also fails, surface it. The handler runs
+ // asynchronously after this function has already resolved.
+ proc.on('error', error => {
+ deps.log(`[link] cmd.exe start failed: ${error.message}; falling back to xdg-open`)
+
+ deps.openExternal(url).catch(openError => {
+ failOpen(deps, url, openError)
+ })
+ })
+
+ try {
+ proc.unref()
+ } catch {
+ // unref can throw on an already-closed handle in some node versions
+ }
+
+ return { ok: true }
+}
+
+function failOpen(deps: ExternalOpenDeps, url: string, error: unknown): ExternalOpenResult {
+ const message = externalOpenErrorMessage(error)
+ deps.log(`[link] openExternal failed: ${message}`)
+ deps.notifyFailure(url, message)
+
+ return { ok: false, reason: 'failed', message }
+}
diff --git a/apps/desktop/electron/first-run-setup-gate.test.ts b/apps/desktop/electron/first-run-setup-gate.test.ts
index f8b53525f0f..94cd05bdc70 100644
--- a/apps/desktop/electron/first-run-setup-gate.test.ts
+++ b/apps/desktop/electron/first-run-setup-gate.test.ts
@@ -131,3 +131,44 @@ test('remote apply without a waiter has no first-run side effects', async () =>
assert.equal(hidden, 0)
assert.equal(gate.isLocalBootstrapConfirmed(), true)
})
+
+const bundledDamagedBackend = {
+ activeRoot: '/tmp/hermes-home/hermes-agent',
+ kind: 'bundled-unusable',
+ platform: 'win32',
+ local: 'bundled-damaged'
+} as const
+
+test('the gate prompts on bundled-unusable (a damaged bundled payload)', async () => {
+ const prompts = []
+ const gate = createFirstRunSetupGate({ promptChoice: backend => prompts.push(backend), stuckAfterMs: 0 })
+
+ const pending = gate.wait(bundledDamagedBackend)
+
+ assert.equal(await settledState(pending), 'pending')
+ assert.equal(prompts.length, 1)
+ assert.equal(gate.hasWaiter(), true)
+})
+
+test('continueLocal settles bundled-unusable without any install side effect', async () => {
+ const gate = createFirstRunSetupGate({ stuckAfterMs: 0 })
+ const pending = gate.wait(bundledDamagedBackend)
+
+ gate.continueLocal()
+
+ assert.equal(await pending, 'continue-local')
+ assert.equal(gate.hasWaiter(), false)
+ assert.equal(gate.isLocalBootstrapConfirmed(), true)
+})
+
+test('remote apply on bundled-unusable settles for a remote re-resolution', async () => {
+ let hidden = 0
+ const gate = createFirstRunSetupGate({ hideChoice: () => hidden++, stuckAfterMs: 0 })
+ const pending = gate.wait(bundledDamagedBackend)
+
+ const resumedWaiter = gate.abandonForRemoteApply()
+
+ assert.equal(resumedWaiter, true)
+ assert.equal(hidden, 1)
+ assert.equal(await pending, 'remote-applied')
+})
diff --git a/apps/desktop/electron/first-run-setup-gate.ts b/apps/desktop/electron/first-run-setup-gate.ts
index 2d83cbeafe6..a9402dfde78 100644
--- a/apps/desktop/electron/first-run-setup-gate.ts
+++ b/apps/desktop/electron/first-run-setup-gate.ts
@@ -2,6 +2,8 @@ interface FirstRunSetupBackend {
activeRoot?: string
kind?: string
platform?: string
+ /** What the local setup card represents: 'none' = installer offer, the rest = use existing. */
+ local?: 'none' | 'installed' | 'bundled' | 'bundled-damaged'
}
interface FirstRunSetupGateOptions {
@@ -57,8 +59,15 @@ export function createFirstRunSetupGate({
}
}
+ // Both sentinels need a user decision: 'bootstrap-needed' offers install-or-
+ // connect; 'bundled-unusable' (a bundled install whose payload is damaged)
+ // offers connect-or-reinstall — never install.
const shouldGate = (backend?: FirstRunSetupBackend | null) =>
- Boolean(backend && backend.kind === 'bootstrap-needed' && !localBootstrapConfirmed)
+ Boolean(
+ backend &&
+ (backend.kind === 'bootstrap-needed' || backend.kind === 'bundled-unusable') &&
+ !localBootstrapConfirmed
+ )
const wait = async (backend?: FirstRunSetupBackend | null) => {
if (!shouldGate(backend)) {
diff --git a/apps/desktop/electron/first-run-setup-main-process.test.ts b/apps/desktop/electron/first-run-setup-main-process.test.ts
index 1dc1b920ef6..6f724ed7c33 100644
--- a/apps/desktop/electron/first-run-setup-main-process.test.ts
+++ b/apps/desktop/electron/first-run-setup-main-process.test.ts
@@ -117,3 +117,108 @@ test('a primary apply without an active first-run gate tears down before reconne
assert.deepEqual(teardownPrimaryBackend.mock.calls, [[{ soft: true }]])
assert.deepEqual(order, ['clear-failure', 'teardown', 'notify'])
})
+
+const bundledDamagedBackend = {
+ activeRoot: '/tmp/hermes-home/hermes-agent',
+ kind: 'bundled-unusable',
+ platform: 'win32',
+ local: 'bundled-damaged'
+}
+
+test('a bundled-unusable continueLocal never reaches an installer — the local step refuses instead', async () => {
+ const gate = createFirstRunSetupGate({ stuckAfterMs: 0 })
+
+ const runBootstrap = vi.fn()
+
+ // Production ordering (electron/main.ts ensureRuntime): the
+ // bundled-unusable branch throws the reinstall error BEFORE any
+ // runBootstrap call. Model that contract — the installer must never fire
+ // for a bundled install, damaged or not.
+ const ensureLocalRuntime = vi.fn(async (backend: any) => {
+ assert.equal(backend.kind, 'bundled-unusable')
+ assert.equal(backend.local, 'bundled-damaged')
+
+ throw new Error('This app bundles its own Hermes runtime, but the runtime files are missing or damaged. Reinstall Hermes Desktop to restore it.')
+ })
+
+ const pendingConnection = runPrimaryBackendStartup({
+ connectRemote: vi.fn(),
+ ensureLocalRuntime,
+ prepareLocalBackend: vi.fn(async () => bundledDamagedBackend),
+ resolveRemote: vi.fn(async () => null),
+ waitForDecision: gate.wait,
+ waitForLocalStart: vi.fn(async () => {})
+ })
+
+ await vi.waitFor(() => assert.equal(gate.hasWaiter(), true))
+
+ gate.continueLocal()
+
+ await assert.rejects(pendingConnection, /Reinstall Hermes Desktop to restore it/)
+ assert.equal(ensureLocalRuntime.mock.calls.length, 1)
+ assert.equal(runBootstrap.mock.calls.length, 0)
+})
+
+test('a bundled-unusable remote apply connects without ensuring or bootstrapping locally', async () => {
+ const gate = createFirstRunSetupGate({ stuckAfterMs: 0 })
+
+ const candidateRemote = {
+ authMode: 'token',
+ baseUrl: 'https://gateway.example.com/hermes',
+ source: 'settings',
+ token: 'secret',
+ wsUrl: 'wss://gateway.example.com/hermes/api/ws?token=secret'
+ }
+
+ let savedRemote: typeof candidateRemote | null = null
+
+ const resolveRemote = vi.fn(async () => savedRemote)
+ const connectRemote = vi.fn(async remote => ({ ...remote, mode: 'remote' as const }))
+ const ensureLocalRuntime = vi.fn()
+ const teardownPrimaryBackend = vi.fn(async () => {})
+ const cancelSshBootstrap = vi.fn(async () => {})
+ const teardownSsh = vi.fn(async () => {})
+ const clearLocalBootstrapFailure = vi.fn()
+ const notifyConnectionApplied = vi.fn()
+
+ const pendingConnection = runPrimaryBackendStartup({
+ connectRemote,
+ ensureLocalRuntime,
+ prepareLocalBackend: vi.fn(async () => bundledDamagedBackend),
+ resolveRemote,
+ waitForDecision: gate.wait,
+ waitForLocalStart: vi.fn(async () => {})
+ })
+
+ await vi.waitFor(() => assert.equal(gate.hasWaiter(), true))
+
+ // Remote is the escape hatch on a damaged bundle: persist + re-home, same
+ // production ordering as the bootstrap-needed path.
+ savedRemote = candidateRemote
+
+ await applyConnectionChange({
+ cancelAndWait: cancelSshBootstrap,
+ isPrimary: true,
+ rehomePrimary: () =>
+ rehomePrimaryConnection({
+ clearLocalBootstrapFailure,
+ mode: 'remote',
+ notifyConnectionApplied,
+ resumeFirstRunRemote: gate.abandonForRemoteApply,
+ teardownPrimaryBackend
+ }),
+ scope: '',
+ sendApplied: notifyConnectionApplied,
+ stopPool: vi.fn(),
+ teardownPrimary: teardownPrimaryBackend,
+ teardownSsh
+ })
+
+ assert.deepEqual(await pendingConnection, {
+ kind: 'remote',
+ connection: { ...candidateRemote, mode: 'remote' }
+ })
+ assert.deepEqual(resolveRemote.mock.calls, [[], []])
+ assert.deepEqual(connectRemote.mock.calls, [[candidateRemote]])
+ assert.equal(ensureLocalRuntime.mock.calls.length, 0)
+})
diff --git a/apps/desktop/electron/install-stamp.test.ts b/apps/desktop/electron/install-stamp.test.ts
new file mode 100644
index 00000000000..3f437781c1c
--- /dev/null
+++ b/apps/desktop/electron/install-stamp.test.ts
@@ -0,0 +1,57 @@
+// installShape() — the ONE split every desktop lifecycle decision gates on.
+//
+// The stamp is a constant of the artifact; the shape is derived from it
+// and never from filesystem probes. These tests pin the derivation table
+// and the probe-independence (a stamp object is enough — no fs access).
+
+import { describe, expect, test } from 'vitest'
+
+import { installShape, type InstallStamp } from './install-stamp'
+
+function stamp(overrides: Partial<InstallStamp>): InstallStamp {
+ return {
+ schemaVersion: 2,
+ commit: 'a'.repeat(40),
+ commitDate: 1755000000,
+ branch: 'main',
+ builtAt: '2026-08-14T00:00:00Z',
+ dirty: false,
+ source: 'ci',
+ distribution: 'desktop-app',
+ updateMechanism: 'electron-updater',
+ baseVersion: '0.21.0',
+ displayVersion: '0.21.0',
+ distance: 0,
+ payload: 'bootstrap',
+ tag: null,
+ ...overrides
+ }
+}
+
+describe('installShape', () => {
+ test('a bundled stamp is the bundled shape', () => {
+ expect(installShape(stamp({ payload: 'bundled', tag: 'v0.21.0' }))).toBe('bundled')
+ })
+
+ test('a bootstrap stamp is a checkout — its runtime is a local install', () => {
+ expect(installShape(stamp({ payload: 'bootstrap' }))).toBe('checkout')
+ })
+
+ test('a light stamp is not bundled (no runtime to run at all)', () => {
+ // Light artifacts never resolve a local backend; what matters here is
+ // that they can never be told to run venv machinery as "bundled".
+ expect(installShape(stamp({ payload: 'light' }))).toBe('checkout')
+ })
+
+ test('a dev run (null stamp) is a checkout', () => {
+ expect(installShape(null)).toBe('checkout')
+ })
+
+ test('the shape comes from the stamp alone — no probe can change it', () => {
+ // Same stamp, any filesystem state: the answer is a pure function of
+ // the constant. (The probes live INSIDE the chosen shape as integrity
+ // checks; see resolveHermesBackend.)
+ const bundled = stamp({ payload: 'bundled' })
+ expect(installShape(bundled)).toBe(installShape(bundled))
+ })
+})
diff --git a/apps/desktop/electron/install-stamp.ts b/apps/desktop/electron/install-stamp.ts
new file mode 100644
index 00000000000..40d5df7f123
--- /dev/null
+++ b/apps/desktop/electron/install-stamp.ts
@@ -0,0 +1,70 @@
+// install-stamp.ts — the typed build-time install stamp.
+//
+// scripts/write_install_stamp.py writes build/install-stamp.json during
+// `npm run build`.
+// bundle-electron-main.mjs bakes that file into the
+// production bundle by defining the __HERMES_INSTALL_STAMP__ global as
+// the stamp. The stamp is a constant of the artifact.
+// It cannot be missing, stale, or edited after signing.
+//
+// Dev bundles and test runs define nothing; the typeof guard makes the
+// stamp null there (a dev run has no artifact to be truthful about).
+
+/**
+ * The desktop artifact kind — which runtime story this artifact tells:
+ * - 'bootstrap': no runtime in the artifact; first launch bootstraps a
+ * local install (the default; also what non-desktop stamps carry).
+ * - 'bundled': the agent runtime ships inside the artifact resources.
+ * - 'light': no runtime at all; remote connections only.
+ * Selected at build time by HERMES_DESKTOP_VARIANT (unset = bootstrap).
+ */
+export type ArtifactKind = 'bootstrap' | 'bundled' | 'light'
+
+/** Mirrors the dict scripts/write_install_stamp.py::build_stamp returns. */
+export interface InstallStamp {
+ schemaVersion: number
+ commit: string | null
+ commitDate: number | null
+ branch: string | null
+ builtAt: string | null
+ dirty: boolean
+ /** Build provenance: where the stamp's facts came from. */
+ source: 'build' | 'ci' | 'docker' | 'fallback' | 'git' | 'local' | 'nix' | 'unknown' | null
+ /** The steward of a sealed tree ('desktop-app' | 'docker' | 'nix'), when packaged. */
+ distribution: string | null
+ /** Who applies the next update. Required in every stamp. */
+ updateMechanism: 'self' | 'electron-updater' | 'external'
+ baseVersion: string | null
+ displayVersion: string | null
+ distance: number | null
+ payload: ArtifactKind
+ /** The pinned release tag. Always set for 'bundled' and 'light', never for 'bootstrap'. */
+ tag: string | null
+}
+
+declare const __HERMES_INSTALL_STAMP__: InstallStamp | undefined
+
+/** The baked stamp of this artifact, or null on dev bundles. */
+export const INSTALL_STAMP: Readonly<InstallStamp> | null =
+ typeof __HERMES_INSTALL_STAMP__ === 'undefined' ? null : Object.freeze(__HERMES_INSTALL_STAMP__)
+
+/**
+ * The install shape this process runs as — THE single split every
+ * lifecycle decision gates on (mirror of Python's runtime_tree()):
+ * - 'bundled': the runtime ships inside the artifact. Venv machinery,
+ * installers, repair-reinstall escalation and update checkouts must
+ * never run; drift means rebuild, updates mean the steward.
+ * - 'checkout': a git tree with venv machinery, provisioner-on-demand
+ * and `hermes update`.
+ *
+ * Derived from the stamp CONSTANT, never from filesystem probes: a
+ * payload/venv/marker probe answers "is this artifact intact?", not
+ * "which shape am I?" — those probes remain only as integrity checks
+ * inside an already-chosen shape (a bundled stamp with a damaged
+ * payload throws; it must not quietly become a checkout). Dev runs
+ * (null stamp) and bootstrap artifacts are 'checkout': their runtime
+ * is a local install the app bootstraps and maintains.
+ */
+export function installShape(stamp: Readonly<InstallStamp> | null = INSTALL_STAMP): 'bundled' | 'checkout' {
+ return stamp?.payload === 'bundled' ? 'bundled' : 'checkout'
+}
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index fda19468746..0485be5ca2f 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -269,7 +269,11 @@ import { serializeJsonBody, setJsonRequestHeaders } from './oauth-net-request'
import { LEGACY_OAUTH_PARTITION, resolveOauthPartition } from './oauth-partition'
import { createParentStartMarkerResolver, parentWatchdogEnv } from './parent-process-identity'
import { adoptPayloadVenv, installIdForRoot, isBundledInstall, resolvePayload, type PayloadInfo } from './payload-backend'
-import { checkAppInstallerUpdate, PLACEHOLDER_FEED_BASE_URL, triggerAppInstallerUpdate } from './app-updater'
+import { PLACEHOLDER_FEED_BASE_URL } from './app-updater'
+import { AppInstallerStrategy } from './updater/app-installer'
+import { ExternalStrategy } from './updater/external'
+import { resolveUpdaterMechanism } from './updater'
+import { writePendingRelaunch, consumePendingRelaunch } from './updater/relaunch'
import { registerPetOverlayIpc } from './pet-overlay-ipc'
import {
buildRegistryProfileRoutes,
@@ -2856,49 +2860,21 @@ async function resolveHealedBranch(updateRoot, branch) {
}
async function checkUpdates() {
- // A bundled install has no checkout to pull — the OS App Installer owns
- // the update loop for out-of-store MSIX installs. Ask the OS whether a
- // newer package is available on the registered .appinstaller source.
+ // A bundled install has no checkout to pull — resolve the updater
+ // mechanism once and delegate. Out-of-store MSIX asks the OS whether a
+ // newer package is on the registered .appinstaller source; Store installs
+ // report unsupported (the steward owns their update loop).
const bundledPayload = resolvePayload(process.resourcesPath, { fileExists, directoryExists, isWindows: IS_WINDOWS })
if (bundledPayload) {
- if (IS_WINDOWS && !isWindowsStore()) {
- try {
- const check = await checkAppInstallerUpdate({
- python: bundledPayload.storePython,
- // The checker ships inside the payload's repo snapshot (git archive
- // of the committed tree): <payload>/<repo>/apps/desktop/scripts/.
- script: path.join(bundledPayload.repoDir, 'apps', 'desktop', 'scripts', 'check-appinstaller-update.py'),
- run: runPayloadPython
- })
-
- return {
- supported: true,
- mechanism: 'app-installer',
- channel: resolveUpdaterChannelFromStamp(),
- currentVersion: app.getVersion(),
- latestVersion: null,
- updateAvailable: check.available === true,
- // null = unknown (checker unavailable) — surface honestly.
- error: check.available === null ? (check.error || 'update check unavailable') : undefined,
- fetchedAt: Date.now()
- }
- } catch (error) {
- return {
- supported: true,
- mechanism: 'app-installer',
- error: 'check-failed',
- message: error?.message || String(error),
- fetchedAt: Date.now()
- }
- }
- }
+ const strategy = resolveBundledUpdateStrategy(bundledPayload)
- return {
- supported: false,
- reason: 'bundled-not-appinstaller',
- message: 'bundled install: updates are applied by the installer (Microsoft Store or App Installer).',
+ return strategy.check().catch(error => ({
+ supported: true,
+ mechanism: strategy.mechanism,
+ error: 'check-failed',
+ message: error?.message || String(error),
fetchedAt: Date.now()
- }
+ }))
}
const updateRoot = resolveUpdateRoot()
@@ -3150,6 +3126,42 @@ let updateInFlight = false
// ── bundled / App Installer helpers ─────────────────────────────────────────
+/**
+ * Resolve the updater strategy for a BUNDLED install (payload present).
+ * Dispatch mirrors the pre-strategy ladder exactly: win32 out-of-store →
+ * App Installer arm; Store / other → external (unsupported). The checkout
+ * ladder below appliesUpdates' bundled branch stays in main.ts (it delegates
+ * through the same mechanism resolution via the wire's `mechanism` field).
+ */
+function resolveBundledUpdateStrategy(bundledPayload) {
+ const mechanism = resolveUpdaterMechanism({
+ isBundled: true,
+ isWindows: IS_WINDOWS,
+ isWindowsStore: isWindowsStore()
+ })
+
+ if (mechanism === 'app-installer') {
+ return new AppInstallerStrategy({
+ python: bundledPayload.storePython,
+ // The checker ships inside the payload's repo snapshot (git archive of
+ // the committed tree): <payload>/<repo>/apps/desktop/scripts/.
+ script: path.join(bundledPayload.repoDir, 'apps', 'desktop', 'scripts', 'check-appinstaller-update.py'),
+ run: runPayloadPython,
+ channel: resolveUpdaterChannelFromStamp(),
+ light: isLightVariant(),
+ feedBaseUrl: resolveDesktopFeedBaseUrl(),
+ shell: { openExternal: url => shell.openExternal(url) },
+ teardownBundledBackend,
+ emitUpdateProgress,
+ appVersion: app.getVersion(),
+ quit: () => app.quit(),
+ registerPendingRelaunch: fromVersion => writePendingRelaunch(HERMES_HOME, fromVersion)
+ })
+ }
+
+ return new ExternalStrategy()
+}
+
/** True when this process is a Microsoft Store deployment. */
function isWindowsStore(): boolean {
return Boolean((process as any).windowsStore)
@@ -3753,47 +3765,15 @@ async function applyUpdates(opts: { stopSafeBlockers?: boolean } = {}) {
// A bundled install ships its whole runtime as a sealed payload — there
// is no checkout to pull or venv to sync. New app release IS the update.
if (resolvePayload(process.resourcesPath, { fileExists, directoryExists, isWindows: IS_WINDOWS })) {
- // Out-of-store MSIX installs are App Installer owned: the OS registered
- // the .appinstaller URI as the update source at install, so "apply"
- // means run the graceful teardown (backend children holding install-dir
- // locks must die first — the same teardown the old in-app updater ran
- // between download and install), then hand the process to the OS App
- // Installer and quit.
- if (IS_WINDOWS && !isWindowsStore()) {
- const feedBaseUrl = resolveDesktopFeedBaseUrl()
-
- if (feedBaseUrl) {
- emitUpdateProgress({
- stage: 'restart',
- message: 'Applying the Hermes update — the window will close and the App Installer will finish.',
- percent: 100
- })
-
- await triggerAppInstallerUpdate(
- feedBaseUrl,
- resolveUpdaterChannelFromStamp(),
- isLightVariant(),
- { openExternal: url => shell.openExternal(url) },
- teardownBundledBackend
- )
-
- // The OS App Installer now owns the swap. Quit so no process holds
- // files in the install dir while Windows replaces the package.
- app.quit()
-
- return { ok: true, manual: false, bundled: true }
- }
- }
-
- // No App Installer source (a non-MSIX bundled install, or no feed
- // configured): the manual card remains the fallback.
- emitUpdateProgress({
- stage: 'manual',
- message: 'bundled install: update by installing the new app release',
- percent: null
- })
+ // Delegate to the bundled strategy: out-of-store MSIX runs the graceful
+ // teardown, hands the swap to the OS App Installer, registers the
+ // one-shot relaunch marker, and quits; anything else gets the manual
+ // card (reinstall the app release).
+ const strategy = resolveBundledUpdateStrategy(
+ resolvePayload(process.resourcesPath, { fileExists, directoryExists, isWindows: IS_WINDOWS })
+ )
- return { ok: true, manual: true, bundled: true }
+ return strategy.apply(opts)
}
updateInFlight = true
@@ -17782,6 +17762,17 @@ app.on('open-url', (event, url) => {
})
app.whenReady().then(() => {
+ // Post-update relaunch detection (App Installer arm): when the previous
+ // version wrote the one-shot pending-relaunch marker before quitting into
+ // an OS package swap, consume it here — the renderer toasts "Hermes
+ // updated to vX.Y.Z" once its bridge is up. Same-version markers (update
+ // never landed) are deleted silently.
+ const relaunchInfo = consumePendingRelaunch(HERMES_HOME, app.getVersion())
+
+ if (relaunchInfo.wasUpdateRelaunch) {
+ rememberLog(`[updates] post-update relaunch detected (from ${relaunchInfo.fromVersion})`)
+ }
+
// Warm the login-shell PATH resolution immediately so it usually completes
// before the backend start path awaits the same single-flight promise.
void ensureLoginShellPath()
diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.ts
index 7e5526c00ea..949832691c8 100644
--- a/apps/desktop/electron/preload.ts
+++ b/apps/desktop/electron/preload.ts
@@ -269,6 +269,12 @@ contextBridge.exposeInMainWorld('hermesDesktop', {
setDisableF12: blocked => ipcRenderer.send('hermes:devtools:disable-f12', blocked),
setPreviewShortcutActive: active => ipcRenderer.send('hermes:previewShortcutActive', Boolean(active)),
openExternal: url => ipcRenderer.invoke('hermes:openExternal', url),
+ onExternalOpenFailed: callback => {
+ const listener = (_event, payload) => callback(payload)
+ ipcRenderer.on('hermes:external-open-failed', listener)
+
+ return () => ipcRenderer.removeListener('hermes:external-open-failed', listener)
+ },
openPreviewInBrowser: url => ipcRenderer.invoke('hermes:openPreviewInBrowser', url),
reachPreviewUrl: url => ipcRenderer.invoke('hermes:preview:reach', url),
setActiveConnectionRoute: route => ipcRenderer.send('hermes:connection:active-route', route),
@@ -301,6 +307,7 @@ contextBridge.exposeInMainWorld('hermesDesktop', {
// Fire-and-forget: persists a renderer error-boundary catch (with component
// stack) to desktop.log so crashes survive the window (#79428).
reportRendererError: report => ipcRenderer.send('hermes:logs:renderer-error', report),
+ logLine: line => ipcRenderer.send('hermes:logs:renderer-line', line),
readDir: dirPath => ipcRenderer.invoke('hermes:fs:readDir', dirPath),
gitRoot: startPath => ipcRenderer.invoke('hermes:fs:gitRoot', startPath),
revealPath: targetPath => ipcRenderer.invoke('hermes:fs:reveal', targetPath),
diff --git a/apps/desktop/electron/product-identity.test.ts b/apps/desktop/electron/product-identity.test.ts
new file mode 100644
index 00000000000..678782cd193
--- /dev/null
+++ b/apps/desktop/electron/product-identity.test.ts
@@ -0,0 +1,107 @@
+// product-identity.cjs is the single derivation of the desktop product
+// identity; electron/product-identity.ts re-exports it. These tests hold
+// the identity contract: the TS accessor resolves to the .cjs object, and
+// the two variants disagree on every OS-visible marker (side-by-side
+// installs must not collide).
+import assert from 'node:assert/strict'
+import { createRequire } from 'node:module'
+
+import { afterEach, beforeEach, test, vi } from 'vitest'
+
+const require = createRequire(import.meta.url)
+
+beforeEach(() => {
+ vi.resetModules()
+})
+
+afterEach(() => {
+ delete process.env.HERMES_DESKTOP_VARIANT
+ delete process.env.HERMES_PAYLOAD_TAG
+ vi.resetModules()
+})
+
+async function identityForVariant(variant: string | undefined) {
+ if (variant === undefined) {
+ delete process.env.HERMES_DESKTOP_VARIANT
+ } else {
+ process.env.HERMES_DESKTOP_VARIANT = variant
+ }
+
+ delete require.cache[require.resolve('../product-identity.cjs')]
+ vi.resetModules()
+
+ return (await import('./product-identity')).PRODUCT_IDENTITY
+}
+
+test('light identity is fully distinct from the full identity', async () => {
+ const full = await identityForVariant(undefined)
+ const light = await identityForVariant('light')
+
+ assert.equal(light.light, true)
+
+ // Enumerate the OS-visible identity markers explicitly rather than looping
+ // Object.keys: `store` is a build-mode flag, legitimately equal (false)
+ // across variants, so a keys-loop would fail for the wrong reason. Only the
+ // markers Windows/electron keys on must differ for side-by-side installs.
+ for (const prop of ['displayName', 'appId', 'appNamePascal', 'msixAppIdWithOrg', 'channel'] as const) {
+ assert.notEqual(light[prop], full[prop], `${prop} must differ between light and full`)
+ }
+})
+
+test('a nightly payload tag moves BOTH variants onto their nightly feed channel', async () => {
+ process.env.HERMES_PAYLOAD_TAG = 'v0.28.0-nightly.20260818'
+ const full = await identityForVariant(undefined)
+ assert.equal(full.channel, 'nightly')
+
+ process.env.HERMES_PAYLOAD_TAG = 'v0.28.0-nightly.20260818'
+ const light = await identityForVariant('light')
+ assert.equal(light.channel, 'light-nightly')
+})
+
+test('stable tags and tagless dev builds publish to the stable channels', async () => {
+ process.env.HERMES_PAYLOAD_TAG = 'v0.28.0'
+ assert.equal((await identityForVariant(undefined)).channel, 'latest')
+
+ delete process.env.HERMES_PAYLOAD_TAG
+ assert.equal((await identityForVariant('light')).channel, 'light')
+})
+
+test('bundled variant keeps the Hermes display name and a distinct appId', async () => {
+ const full = await identityForVariant(undefined)
+ const bundled = await identityForVariant('bundled')
+
+ assert.equal(bundled.light, false)
+ assert.equal(bundled.displayName, full.displayName)
+ assert.equal(bundled.appNamePascal, 'HermesBundled')
+ assert.notEqual(bundled.appId, full.appId)
+ assert.equal(bundled.channel, 'latest')
+})
+
+test('store inherits the bundled app identity (shared userData) but swaps the MSIX packaging identity', async () => {
+ const bundled = await identityForVariant('bundled')
+ const store = await identityForVariant('store')
+
+ // Same Electron app: displayName/appNamePascal (-> shared userData dir),
+ // appId, and the out-of-store org-prefixed name are all inherited.
+ assert.equal(store.store, true)
+ assert.equal(store.light, false)
+ assert.equal(store.displayName, bundled.displayName)
+ assert.equal(store.appNamePascal, bundled.appNamePascal)
+ assert.equal(store.appId, bundled.appId)
+ assert.equal(store.msixAppIdWithOrg, bundled.msixAppIdWithOrg)
+ // The store build never publishes to a feed.
+ assert.equal(store.channel, null)
+})
+
+test('store carries the Partner Center MSIX identity and no other variant does', async () => {
+ const store = await identityForVariant('store')
+ assert.deepEqual(store.storeMsix, {
+ identityName: 'NousResearchInc.HermesAgent',
+ publisher: 'CN=EE6D86E4-606F-4E38-B940-AD7248C9D519',
+ publisherDisplayName: 'Nous Research Inc.'
+ })
+
+ for (const v of [undefined, 'bundled', 'light'] as const) {
+ assert.equal((await identityForVariant(v)).storeMsix, undefined, `variant ${v} must carry no storeMsix`)
+ }
+})
diff --git a/apps/desktop/electron/product-identity.ts b/apps/desktop/electron/product-identity.ts
new file mode 100644
index 00000000000..a722c6e88d5
--- /dev/null
+++ b/apps/desktop/electron/product-identity.ts
@@ -0,0 +1,19 @@
+// product-identity.ts — the typed build-time product identity.
+//
+// product-identity.cjs is the single derivation of every name-shaped
+// value a variant owns (product name, appId, channel). Dev bundles and
+// test runs import the .cjs itself so the derivation exists in exactly
+// one place.
+
+import devIdentity from '../product-identity.cjs'
+
+/** Mirrors product-identity.cjs (see product-identity.d.cts). */
+export type ProductIdentity = typeof devIdentity
+
+declare const __HERMES_PRODUCT_IDENTITY__: ProductIdentity
+
+/** The baked identity of this artifact (dev bundles derive it live). */
+export const PRODUCT_IDENTITY: Readonly<ProductIdentity> =
+ typeof __HERMES_PRODUCT_IDENTITY__ === 'undefined'
+ ? Object.freeze(devIdentity)
+ : Object.freeze(__HERMES_PRODUCT_IDENTITY__)
diff --git a/apps/desktop/electron/updater/app-installer-strategy.test.ts b/apps/desktop/electron/updater/app-installer-strategy.test.ts
new file mode 100644
index 00000000000..023325a30de
--- /dev/null
+++ b/apps/desktop/electron/updater/app-installer-strategy.test.ts
@@ -0,0 +1,70 @@
+// updater/app-installer-strategy.test.ts — the apply-flow contract: the
+// one-shot relaunch marker is written BEFORE the OS hand-off, teardown runs
+// before the trigger, and quit is unconditional (no relaunch question).
+
+import { describe, expect, it } from 'vitest'
+
+import { AppInstallerStrategy } from './app-installer'
+import type { AppInstallerStrategyDeps } from './app-installer'
+
+function makeDeps(over: Partial<AppInstallerStrategyDeps> = {}) {
+ const calls: string[] = []
+ const deps: AppInstallerStrategyDeps = {
+ python: 'python.exe',
+ script: 'check.py',
+ run: async () => ({ code: 0, stdout: '{"available": true}' }),
+ channel: 'stable',
+ light: false,
+ feedBaseUrl: 'https://updates.example/hermes-desktop',
+ shell: { openExternal: async () => { calls.push('openExternal') } },
+ teardownBundledBackend: async () => { calls.push('teardown') },
+ emitUpdateProgress: () => {},
+ appVersion: '0.18.2',
+ quit: () => { calls.push('quit') },
+ registerPendingRelaunch: () => { calls.push('relaunch-marker'); return true },
+ ...over
+ }
+ return { deps, calls }
+}
+
+describe('AppInstallerStrategy.apply', () => {
+ it('writes the relaunch marker before teardown, trigger, and quit — order is the contract', async () => {
+ const { deps, calls } = makeDeps()
+ const strategy = new AppInstallerStrategy(deps)
+ const result = await strategy.apply({})
+
+ expect(result).toEqual({ ok: true, manual: false, bundled: true, mechanism: 'app-installer' })
+ expect(calls).toEqual(['relaunch-marker', 'teardown', 'openExternal', 'quit'])
+ })
+
+ it('fails open: a marker-write failure never blocks the update', async () => {
+ const { deps, calls } = makeDeps({ registerPendingRelaunch: () => false })
+ const result = await new AppInstallerStrategy(deps).apply({})
+ expect(result.ok).toBe(true)
+ expect(calls).toContain('quit')
+ })
+
+ it('no feed URL → manual card, no teardown, no quit', async () => {
+ const { deps, calls } = makeDeps({ feedBaseUrl: '' })
+ const result = await new AppInstallerStrategy(deps).apply({})
+ expect(result).toEqual({ ok: true, manual: true, bundled: true, mechanism: 'app-installer' })
+ expect(calls).toEqual([])
+ })
+})
+
+describe('AppInstallerStrategy.check', () => {
+ it('threads the OS checker result onto the mechanism wire', async () => {
+ const { deps } = makeDeps({ run: async () => ({ code: 0, stdout: '{"available": true}' }) })
+ const status = await new AppInstallerStrategy(deps).check()
+ expect(status.mechanism).toBe('app-installer')
+ expect(status.updateAvailable).toBe(true)
+ expect(status.error).toBeUndefined()
+ })
+
+ it('unknown availability is an error on the wire, never "no update"', async () => {
+ const { deps } = makeDeps({ run: async () => ({ code: 1, stdout: '{"available": null, "error": "winrt missing"}' }) })
+ const status = await new AppInstallerStrategy(deps).check()
+ expect(status.updateAvailable).toBe(false)
+ expect(status.error).toBe('winrt missing')
+ })
+})
diff --git a/apps/desktop/electron/updater/app-installer.ts b/apps/desktop/electron/updater/app-installer.ts
new file mode 100644
index 00000000000..29ebaf957da
--- /dev/null
+++ b/apps/desktop/electron/updater/app-installer.ts
@@ -0,0 +1,149 @@
+// updater/app-installer.ts — the win32 out-of-store MSIX strategy.
+//
+// The OS App Installer owns the apply. The package was installed from an
+// .appinstaller, which registered the feed URI as the package's update source;
+// the OS checks it and swaps the package wholesale. The app's only jobs:
+// check() ask the OS whether an update is available (via the bundled
+// payload python's winrt), surfacing UNKNOWN honestly;
+// apply() run graceful teardown, trigger ms-appinstaller:, quit — and
+// a pending-relaunch marker so Hermes comes back by itself.
+//
+// Pure-injectable: the impure pieces (python runner, shell, quit, relaunch
+// marker) are injected, so vitest covers the arm without a payload.
+
+import {
+ checkAppInstallerUpdate,
+ type AppInstallerCheck,
+ type PayloadPythonRunner,
+ triggerAppInstallerUpdate,
+ win32AppInstallerFeedPath
+} from '../app-updater'
+import type { UpdaterApplyResultWire, UpdaterStatusWire } from './index'
+
+export interface AppInstallerStrategyDeps {
+ /** Absolute path to the bundled payload python (tools/<entry>/python.exe). */
+ python: string
+ /** The checker script's absolute path (payload repo snapshot). */
+ script: string
+ run: PayloadPythonRunner['run']
+ /** Channel + variant from the baked install stamp. */
+ channel: 'stable' | 'nightly'
+ light: boolean
+ /** The App Installer feed base URL; empty when nothing configured it. */
+ feedBaseUrl: string
+ shell: { openExternal: (url: string) => Promise<void> }
+ /** Graceful backend teardown before the package swap. */
+ teardownBundledBackend: () => void | Promise<void>
+ /** Progress emitter for the updates overlay. */
+ emitUpdateProgress: (payload: { stage: string; message: string; percent: number | null }) => void
+ /** App version label for the status wire. */
+ appVersion: string
+ /** Quit the app (after handing the swap to the OS). */
+ quit: () => void
+ /**
+ * Register a one-shot post-update relaunch (run-key entry or equivalent)
+ * before quitting, so Hermes reopens on the new version with no user
+ * action. The new version's first run detects + deletes the marker.
+ * Returns false when registration failed (relaunch stays manual).
+ */
+ registerPendingRelaunch: (targetVersion: string) => boolean
+}
+
+export interface CheckOutcome {
+ status: UpdaterStatusWire
+}
+
+/**
+ * Ask the OS whether an App Installer update is available. `available: null`
+ * (checker unavailable) is surfaced as an honest unknown on the wire —
+ * NEVER as "no update".
+ */
+export function appInstallerCheckToStatus(check: AppInstallerCheck, appVersion: string): UpdaterStatusWire {
+ return {
+ supported: true,
+ mechanism: 'app-installer',
+ currentVersion: appVersion,
+ updateAvailable: check.available === true,
+ // null = unknown (checker unavailable) — surface honestly, never "no update".
+ error: check.available === null ? check.error || 'update check unavailable' : undefined,
+ fetchedAt: Date.now()
+ }
+}
+
+export class AppInstallerStrategy {
+ readonly mechanism = 'app-installer' as const
+
+ constructor(private readonly deps: AppInstallerStrategyDeps) {}
+
+ async check(): Promise<UpdaterStatusWire> {
+ const { code, stdout } = await this.deps.run(this.deps.python, this.deps.script)
+ const check = parseCheckOutput(code, stdout)
+
+ return appInstallerCheckToStatus(check, this.deps.appVersion)
+ }
+
+ async apply(_opts: { stopSafeBlockers?: boolean }): Promise<UpdaterApplyResultWire> {
+ const feedBaseUrl = this.deps.feedBaseUrl
+
+ if (!feedBaseUrl) {
+ this.deps.emitUpdateProgress({
+ stage: 'manual',
+ message: 'bundled install: update by installing the new app release',
+ percent: null
+ })
+
+ return { ok: true, manual: true, bundled: true, mechanism: this.mechanism }
+ }
+
+ this.deps.emitUpdateProgress({
+ stage: 'restart',
+ message: 'Applying the Hermes update — the window will close and the App Installer will finish.',
+ percent: 100
+ })
+
+ // Unconditional relaunch: register the one-shot marker BEFORE the swap so
+ // Hermes comes back on the new version with no user action.
+ this.deps.registerPendingRelaunch(this.deps.appVersion)
+
+ await triggerAppInstallerUpdate(
+ feedBaseUrl,
+ this.deps.channel,
+ this.deps.light,
+ this.deps.shell,
+ this.deps.teardownBundledBackend
+ )
+
+ this.deps.quit()
+
+ return { ok: true, manual: false, bundled: true, mechanism: this.mechanism }
+ }
+}
+
+/** Parse the payload-python checker's output into an AppInstallerCheck. */
+export function parseCheckOutput(code: number, stdout: string): AppInstallerCheck {
+ const text = stdout.trim()
+ let parsed: { available?: boolean | null; availability?: string; error?: string; reason?: string } | null = null
+
+ try {
+ parsed = text ? JSON.parse(text) : null
+ } catch {
+ parsed = null
+ }
+
+ if (parsed && typeof parsed.available === 'boolean') {
+ return { available: parsed.available, availability: parsed.availability, error: parsed.error }
+ }
+
+ if (parsed && parsed.available === null) {
+ return { available: null, error: parsed.error || 'checker returned unknown' }
+ }
+
+ if (code !== 0) {
+ return { available: null, error: parsed?.error || `checker exited ${code}` }
+ }
+
+ return { available: null, error: 'checker returned no availability' }
+}
+
+export { win32AppInstallerFeedPath }
+export type { AppInstallerCheck, PayloadPythonRunner }
diff --git a/apps/desktop/electron/updater/checkout.ts b/apps/desktop/electron/updater/checkout.ts
new file mode 100644
index 00000000000..384d35028e5
--- /dev/null
+++ b/apps/desktop/electron/updater/checkout.ts
@@ -0,0 +1,51 @@
+// updater/checkout.ts — the git-checkout strategies (win + posix + manual).
+//
+// These wrap the existing bodies in main.ts rather than re-implementing
+// them: the checkout update flow is deeply entangled with the god-file's
+// closure helpers (resolveHealedBranch, venv-lock release, blocker scans,
+// hand-off marker claims). The strategy adapter delegates; the ladder's
+// TAIL (manual `hermes update` command card) lives here because it is pure
+// enough to test.
+
+import type { UpdaterApplyResultWire, UpdaterStatusWire } from './index'
+
+export interface CheckoutStrategyDeps {
+ /** The existing checkUpdates git-checkout body (unchanged). */
+ checkBody: () => Promise<UpdaterStatusWire>
+ /** The existing applyUpdates git-checkout body (unchanged). */
+ applyBody: (opts: { stopSafeBlockers?: boolean }) => Promise<UpdaterApplyResultWire>
+ isWindows: boolean
+}
+
+export class CheckoutStrategy {
+ readonly mechanism: 'windows-handoff' | 'posix-handoff'
+
+ constructor(private readonly deps: CheckoutStrategyDeps) {
+ this.mechanism = deps.isWindows ? 'windows-handoff' : 'posix-handoff'
+ }
+
+ async check(): Promise<UpdaterStatusWire> {
+ const status = await this.deps.checkBody()
+ status.mechanism = this.mechanism
+ return status
+ }
+
+ async apply(opts: { stopSafeBlockers?: boolean }): Promise<UpdaterApplyResultWire> {
+ const result = await this.deps.applyBody(opts)
+ result.mechanism = this.mechanism
+ return result
+ }
+}
+
+/**
+ * The manual command card for a checkout with no staged updater: the exact
+ * `hermes update` line to run, branch-pinned to the checkout's current branch
+ * for non-main (bare `hermes update` would silently switch the install
+ * off-branch). Extracted from applyUpdates so the wording contract is
+ * unit-testable.
+ */
+export function buildManualUpdateCommand(currentBranch: string | null | undefined): string {
+ return currentBranch && currentBranch !== 'HEAD' && currentBranch !== 'main'
+ ? `hermes update --branch ${currentBranch}`
+ : 'hermes update'
+}
diff --git a/apps/desktop/electron/updater/external.ts b/apps/desktop/electron/updater/external.ts
new file mode 100644
index 00000000000..f3842c28c69
--- /dev/null
+++ b/apps/desktop/electron/updater/external.ts
@@ -0,0 +1,30 @@
+// updater/external.ts — the steward-owned strategy.
+//
+// Store deployments (process.windowsStore) and stamps whose updateMechanism
+// is 'external': the steward (Microsoft Store / App Installer on-launch
+// re-check) owns the update loop. The app does not check, does not apply —
+// it only tells the user updates happen outside the app.
+
+import type { UpdaterApplyResultWire, UpdaterStatusWire } from './index'
+
+export const EXTERNAL_UNSUPPORTED_MESSAGE =
+ 'bundled install: updates are applied by the installer (Microsoft Store or App Installer).'
+
+export class ExternalStrategy {
+ readonly mechanism = 'external' as const
+ readonly supported = false
+
+ async check(): Promise<UpdaterStatusWire> {
+ return {
+ supported: false,
+ mechanism: 'external',
+ reason: 'bundled-not-appinstaller',
+ message: EXTERNAL_UNSUPPORTED_MESSAGE,
+ fetchedAt: Date.now()
+ }
+ }
+
+ async apply(): Promise<UpdaterApplyResultWire> {
+ return { ok: true, manual: true, bundled: true, mechanism: 'external' }
+ }
+}
diff --git a/apps/desktop/electron/updater/index.ts b/apps/desktop/electron/updater/index.ts
new file mode 100644
index 00000000000..2cbdbd7e4f7
--- /dev/null
+++ b/apps/desktop/electron/updater/index.ts
@@ -0,0 +1,90 @@
+// updater/index.ts — the desktop update strategy surface.
+//
+// Every install shape updates through a different owner:
+// app-installer out-of-store MSIX on win32 — the OS App Installer owns
+// the apply (the .appinstaller feed registered at install).
+// external Microsoft Store / steward-owned deployments — no in-app
+// updater at all.
+// windows-handoff git checkout on win32 — detached updater binary or the
+// repo hand-off script owns the swap.
+// posix-handoff git checkout on macOS/Linux — the repo posix hand-off
+// script owns the swap.
+// manual checkout with no staged updater — the user runs
+// `hermes update` themselves.
+//
+// The mechanism is resolved ONCE from runtime facts (payload presence,
+// platform, store flag) by resolveUpdaterMechanism — a pure function, unit
+// tested — and every strategy reports it on the wire so the renderer can
+// tailor copy per mechanism without probing the install shape itself.
+
+export type UpdaterMechanism =
+ | 'app-installer'
+ | 'external'
+ | 'windows-handoff'
+ | 'posix-handoff'
+ | 'manual'
+
+/** The facts the mechanism dispatch keys on. Pure data — injectable for tests. */
+export interface MechanismFacts {
+ /** A bundled payload ships inside this artifact (sealed runtime). */
+ isBundled: boolean
+ isWindows: boolean
+ /** This process is a Microsoft Store deployment. */
+ isWindowsStore: boolean
+}
+
+/**
+ * Resolve which mechanism owns updates for this install. Precedence mirrors
+ * the historical checkUpdates/applyUpdates ladder in main.ts exactly:
+ * payload-probe first, store-flag second, platform third. Behavior-preserving.
+ */
+export function resolveUpdaterMechanism(facts: MechanismFacts): UpdaterMechanism {
+ if (facts.isBundled) {
+ return facts.isWindows && !facts.isWindowsStore ? 'app-installer' : 'external'
+ }
+
+ return facts.isWindows ? 'windows-handoff' : 'posix-handoff'
+}
+
+/** The status shape main.ts already sends over `hermes:updates:check`. */
+export interface UpdaterStatusWire {
+ supported: boolean
+ mechanism?: UpdaterMechanism
+ updateAvailable?: boolean
+ branch?: string
+ currentBranch?: string
+ reason?: string
+ message?: string
+ error?: string
+ behind?: number | null
+ currentSha?: string
+ currentVersion?: string
+ channel?: 'stable' | 'nightly'
+ latestTag?: string | null
+ targetSha?: string
+ commits?: { sha: string; summary: string; author: string; at: number }[]
+ dirty?: boolean
+ hermesRoot?: string
+ fetchedAt?: number
+}
+
+/** The result shape main.ts already sends over `hermes:updates:apply`. */
+export interface UpdaterApplyResultWire {
+ ok: boolean
+ mechanism?: UpdaterMechanism
+ error?: string
+ message?: string
+ manual?: boolean
+ bundled?: boolean
+ command?: string
+ hermesRoot?: string
+ handedOff?: boolean
+ updater?: string
+ [key: string]: unknown
+}
+
+export interface UpdaterStrategy {
+ readonly mechanism: UpdaterMechanism
+ check(): Promise<UpdaterStatusWire>
+ apply(opts: { stopSafeBlockers?: boolean }): Promise<UpdaterApplyResultWire>
+}
diff --git a/apps/desktop/electron/updater/relaunch.ts b/apps/desktop/electron/updater/relaunch.ts
new file mode 100644
index 00000000000..2170254bfe9
--- /dev/null
+++ b/apps/desktop/electron/updater/relaunch.ts
@@ -0,0 +1,116 @@
+// updater/relaunch.ts — unconditional relaunch after an App Installer swap.
+//
+// Contract: clicking Update always ends in Hermes reopening on the new
+// version — no user action between quit and relaunch. Implementation: a
+// one-shot pending-relaunch marker written before we quit. The OS App
+// Installer swaps the package; on next launch (whenever it happens) Hermes
+// reads the marker, shows the "updated" toast, and deletes it.
+//
+// The marker is a JSON file under HERMES_HOME (not a run-key / scheduled
+// task): a registry entry can't be made one-shot safely from a dying process,
+// and a file survives the package swap (HERMES_HOME lives outside the
+// package). For the actual relaunch we rely on Windows restarting the app
+// when an MSIX package update completes while the app registered itself
+// for restart (RegisterApplicationRestart) — the marker's job is only to
+// tell the NEW version it was an update relaunch, so it can toast + clean up.
+//
+// If the OS does NOT relaunch (update applied later, on next launch), the
+// marker is still correct: the first launch after the swap detects it and
+// toasts. A stale marker (update cancelled/failed) self-deletes when its
+// expected-version no longer matches a later install... no — cancelled
+// updates mean the version never changed, so we stamp with "expected NEW
+// version unknown" instead: the marker only records that an update was
+// STARTED; the new version decides "was it really me?" by comparing versions
+// recorded at write time vs launch time.
+
+import * as fs from 'node:fs'
+import * as path from 'node:path'
+
+export interface PendingRelaunchMarker {
+ schemaVersion: 1
+ /** Version of the app that wrote the marker (pre-update). */
+ fromVersion: string
+ /** Wall-clock ms when the update was triggered. */
+ startedAt: number
+}
+
+const MARKER_FILENAME = 'pending-update-relaunch.json'
+
+function markerPath(hermesHome: string): string {
+ return path.join(hermesHome, MARKER_FILENAME)
+}
+
+/** Pure: the filename constant, for tests. */
+export const PENDING_RELAUNCH_FILENAME = MARKER_FILENAME
+
+/**
+ * Register the one-shot post-update relaunch marker. Best-effort — a failure
+ * to write never blocks the update; relaunch just stays manual.
+ */
+export function writePendingRelaunch(
+ hermesHome: string,
+ fromVersion: string,
+ writeFile: (file: string, contents: string) => void = (f, c) => fs.writeFileSync(f, c)
+): boolean {
+ try {
+ const marker: PendingRelaunchMarker = { schemaVersion: 1, fromVersion, startedAt: Date.now() }
+ writeFile(markerPath(hermesHome), JSON.stringify(marker))
+
+ return true
+ } catch {
+ return false
+ }
+}
+
+export interface ConsumedRelaunch {
+ /** True when this launch IS the post-update relaunch (new version). */
+ wasUpdateRelaunch: boolean
+ /** The version the update started from, when the marker was present. */
+ fromVersion?: string
+}
+
+export interface RelaunchFsDeps {
+ existsSync?: (file: string) => boolean
+ readFileSync?: (file: string) => string
+ unlinkSync?: (file: string) => void
+}
+
+/**
+ * First-run hook: detect + consume the pending-relaunch marker. Returns
+ * wasUpdateRelaunch=true only when the CURRENT version differs from the
+ * marker's fromVersion — the same version means the update never landed
+ * (cancelled/failed OS install), so the marker is deleted and no toast fires.
+ */
+export function consumePendingRelaunch(
+ hermesHome: string,
+ currentVersion: string,
+ deps: RelaunchFsDeps = {}
+): ConsumedRelaunch {
+ const existsSync = deps.existsSync ?? ((file: string) => fs.existsSync(file))
+ const readFileSync = deps.readFileSync ?? ((file: string) => fs.readFileSync(file, 'utf8'))
+ const unlinkSync = deps.unlinkSync ?? ((file: string) => fs.unlinkSync(file))
+
+ const file = markerPath(hermesHome)
+
+ if (!existsSync(file)) {
+ return { wasUpdateRelaunch: false }
+ }
+
+ let fromVersion: string | undefined
+
+ try {
+ const raw = JSON.parse(readFileSync(file)) as PendingRelaunchMarker
+ fromVersion = typeof raw.fromVersion === 'string' ? raw.fromVersion : undefined
+ } catch {
+ fromVersion = undefined
+ }
+
+ // Consume unconditionally — the marker is one-shot.
+ try {
+ unlinkSync(file)
+ } catch {
+ // Best-effort cleanup; a leftover marker is re-consumed harmlessly.
+ }
+
+ return { wasUpdateRelaunch: fromVersion !== undefined && fromVersion !== currentVersion, fromVersion }
+}
diff --git a/apps/desktop/electron/updater/updater.test.ts b/apps/desktop/electron/updater/updater.test.ts
new file mode 100644
index 00000000000..d94f31af89e
--- /dev/null
+++ b/apps/desktop/electron/updater/updater.test.ts
@@ -0,0 +1,149 @@
+// updater/updater.test.ts — resolution precedence + wire-shape contracts
+// for the strategy layer. Pure DI: no Electron, no payload.
+
+import { describe, expect, it } from 'vitest'
+
+import { resolveUpdaterMechanism } from './index'
+import { appInstallerCheckToStatus, parseCheckOutput } from './app-installer'
+import { buildManualUpdateCommand } from './checkout'
+import { writePendingRelaunch, consumePendingRelaunch, PENDING_RELAUNCH_FILENAME } from './relaunch'
+
+describe('resolveUpdaterMechanism — precedence', () => {
+ it('bundled win32 out-of-store → app-installer', () => {
+ expect(resolveUpdaterMechanism({ isBundled: true, isWindows: true, isWindowsStore: false })).toBe('app-installer')
+ })
+
+ it('bundled win32 Store → external (steward owns updates)', () => {
+ expect(resolveUpdaterMechanism({ isBundled: true, isWindows: true, isWindowsStore: true })).toBe('external')
+ })
+
+ it('bundled posix → external', () => {
+ expect(resolveUpdaterMechanism({ isBundled: true, isWindows: false, isWindowsStore: false })).toBe('external')
+ })
+
+ it('checkout win32 → windows-handoff', () => {
+ expect(resolveUpdaterMechanism({ isBundled: false, isWindows: true, isWindowsStore: false })).toBe('windows-handoff')
+ })
+
+ it('checkout posix → posix-handoff', () => {
+ expect(resolveUpdaterMechanism({ isBundled: false, isWindows: false, isWindowsStore: false })).toBe('posix-handoff')
+ })
+
+ it('store flag never downgrades a checkout (probe only fires for bundled)', () => {
+ // isWindowsStore on a checkout is meaningless; the resolver must not
+ // route a win32 checkout to external on a stray true.
+ expect(resolveUpdaterMechanism({ isBundled: false, isWindows: true, isWindowsStore: true })).toBe('windows-handoff')
+ })
+})
+
+describe('app-installer check → status wire', () => {
+ it('available true → updateAvailable, no error', () => {
+ const s = appInstallerCheckToStatus({ available: true }, '0.18.2')
+ expect(s.supported).toBe(true)
+ expect(s.mechanism).toBe('app-installer')
+ expect(s.updateAvailable).toBe(true)
+ expect(s.error).toBeUndefined()
+ })
+
+ it('available false → updateAvailable false, NO error (honest no-update)', () => {
+ const s = appInstallerCheckToStatus({ available: false }, '0.18.2')
+ expect(s.updateAvailable).toBe(false)
+ expect(s.error).toBeUndefined()
+ })
+
+ it('available null → updateAvailable false WITH error (honest unknown, never "no update")', () => {
+ const s = appInstallerCheckToStatus({ available: null, error: 'no winrt' }, '0.18.2')
+ expect(s.updateAvailable).toBe(false)
+ expect(s.error).toBe('no winrt')
+ })
+})
+
+describe('parseCheckOutput', () => {
+ it('parses boolean true/false availability', () => {
+ expect(parseCheckOutput(0, '{"available": true, "availability": "Available"}')).toEqual({
+ available: true,
+ availability: 'Available',
+ error: undefined
+ })
+ expect(parseCheckOutput(0, '{"available": false}')).toEqual({ available: false, availability: undefined, error: undefined })
+ })
+
+ it('available null surfaces the checker error', () => {
+ expect(parseCheckOutput(2, '{"available": null, "error": "winrt import failed"}')).toEqual({
+ available: null,
+ error: 'winrt import failed'
+ })
+ })
+
+ it('non-zero exit without parseable output names the exit code', () => {
+ expect(parseCheckOutput(1, 'boom')).toEqual({ available: null, error: 'checker exited 1' })
+ })
+
+ it('exit 0 with no availability is unknown, not no-update', () => {
+ expect(parseCheckOutput(0, '')).toEqual({ available: null, error: 'checker returned no availability' })
+ })
+})
+
+describe('buildManualUpdateCommand', () => {
+ it('bare command on main and detached HEAD', () => {
+ expect(buildManualUpdateCommand('main')).toBe('hermes update')
+ expect(buildManualUpdateCommand('HEAD')).toBe('hermes update')
+ expect(buildManualUpdateCommand(null)).toBe('hermes update')
+ })
+
+ it('branch-pinned for non-main checkouts', () => {
+ expect(buildManualUpdateCommand('ethie/pm')).toBe('hermes update --branch ethie/pm')
+ })
+})
+
+describe('pending relaunch marker', () => {
+ const KEY = PENDING_RELAUNCH_FILENAME
+
+ function fakeFs(files: Record<string, string>) {
+ const has = (f: string) => f.replace(/\\/g, '/').endsWith(`/${KEY}`) || f === KEY
+ return {
+ existsSync: (f: string) => has(f),
+ readFileSync: (f: string) => files[Object.keys(files).find(k => k.replace(/\\/g, '/') === f.replace(/\\/g, '/')) ?? f],
+ unlinkSync: (f: string) => {
+ const key = Object.keys(files).find(k => k.replace(/\\/g, '/') === f.replace(/\\/g, '/'))
+ if (key) delete files[key]
+ }
+ }
+ }
+
+ it('write then consume on a different version = update relaunch', () => {
+ const files: Record<string, string> = {}
+ expect(writePendingRelaunch('/home', '0.18.2', (f, c) => { files[f] = c as string })).toBe(true)
+ expect(JSON.parse(Object.values(files)[0]).fromVersion).toBe('0.18.2')
+
+ const r = consumePendingRelaunch('/home', '0.18.3', fakeFs(files))
+ expect(r.wasUpdateRelaunch).toBe(true)
+ expect(r.fromVersion).toBe('0.18.2')
+ // one-shot: consumed
+ expect(Object.keys(files)).toHaveLength(0)
+ })
+
+ it('same version = update never landed; marker consumed silently', () => {
+ const files: Record<string, string> = {}
+ writePendingRelaunch('/home', '0.18.2', (f, c) => { files[f] = c as string })
+
+ const r = consumePendingRelaunch('/home', '0.18.2', fakeFs(files))
+ expect(r.wasUpdateRelaunch).toBe(false)
+ expect(Object.keys(files)).toHaveLength(0)
+ })
+
+ it('no marker = normal launch', () => {
+ expect(consumePendingRelaunch('/home', '0.18.3', fakeFs({})).wasUpdateRelaunch).toBe(false)
+ })
+
+ it('corrupt marker is consumed and treated as unknown', () => {
+ const files: Record<string, string> = {}
+ writePendingRelaunch('/home', '0.18.2', (f, c) => { files[f] = c as string })
+ // corrupt the contents under the same key
+ for (const k of Object.keys(files)) files[k] = 'not json'
+
+ const r = consumePendingRelaunch('/home', '0.18.3', fakeFs(files))
+ expect(r.wasUpdateRelaunch).toBe(false)
+ expect(Object.keys(files)).toHaveLength(0)
+ })
+})
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 95837f12e32..d841bf103f7 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -34,12 +34,13 @@
"builder": "cross-env NODE_OPTIONS=--max-old-space-size=16384 node scripts/run-electron-builder.mjs",
"pack": "npm run build && npm run builder -- --dir --publish never",
"dist": "npm run build && npm run builder",
+ "payload": "node scripts/stage-payload.mjs",
+ "dist:bundled": "npm run payload && npm run dist",
"dist:mac": "npm run build && npm run builder -- --mac",
"dist:mac:dmg": "npm run build && npm run builder -- --mac dmg",
"dist:mac:zip": "npm run build && npm run builder -- --mac zip",
- "dist:win": "npm run build && npm run builder -- --win",
- "dist:win:msi": "npm run build && npm run builder -- --win msi",
- "dist:win:nsis": "npm run build && npm run builder -- --win nsis",
+ "dist:win": "npm run build && npm run builder -- --win msix",
+ "dist:win:msix": "npm run build && npm run builder -- --win msix",
"dist:linux": "npm run build && npm run builder -- --linux AppImage deb rpm",
"perf": "node scripts/perf/run.mjs",
"update:shim": "bash ../../scripts/desktop-update/repro.sh shim",
@@ -53,10 +54,10 @@
"test:desktop": "node scripts/test-desktop.mjs",
"test:desktop:all": "node scripts/test-desktop.mjs all",
"test:desktop:dmg": "node scripts/test-desktop.mjs dmg",
- "test:desktop:nsis": "node scripts/test-desktop.mjs nsis",
+ "test:desktop:msix": "node scripts/test-desktop.mjs msix",
"test:desktop:existing": "node scripts/test-desktop.mjs existing",
"test:desktop:fresh": "node scripts/test-desktop.mjs fresh",
- "typecheck": "tsc -p . --noEmit && tsc -p tsconfig.electron.json --noEmit && tsc -p tsconfig.e2e.json --noEmit",
+ "typecheck": "tsc -p . --noEmit && tsc -p tsconfig.electron.json --noEmit && tsc -p tsconfig.e2e.json --noEmit && tsc --ignoreConfig --allowJs --checkJs --noEmit --skipLibCheck --module nodenext --moduleResolution nodenext --target es2022 electron-builder.config.cjs",
"lint": "eslint src/ electron/",
"lint:fix": "eslint src/ electron/ --fix",
"fmt": "prettier --write 'src/**/*.{ts,tsx}' 'electron/**/*.ts' 'vite.config.ts'",
@@ -173,7 +174,7 @@
"concurrently": "10.0.4",
"cross-env": "10.1.0",
"electron": "40.10.2",
- "electron-builder": "26.15.3",
+ "electron-builder": "27.0.0-alpha.6",
"esbuild": "0.28.1",
"jsdom": "29.1.1",
"prettier": "3.9.5",
@@ -183,124 +184,5 @@
"vite": "8.2.0",
"vitest": "4.1.10",
"wait-on": "9.0.10"
- },
- "build": {
- "electronVersion": "40.10.2",
- "appId": "com.nousresearch.hermes",
- "productName": "Hermes",
- "executableName": "Hermes",
- "protocols": [
- {
- "name": "Hermes Protocol",
- "schemes": [
- "hermes"
- ]
- }
- ],
- "artifactName": "Hermes-${version}-${os}-${arch}.${ext}",
- "icon": "assets/icon",
- "directories": {
- "output": "release"
- },
- "files": [
- "dist/**",
- "assets/**",
- "public/**",
- "package.json"
- ],
- "beforeBuild": "scripts/before-build.mjs",
- "beforePack": "scripts/before-pack.mjs",
- "afterPack": "scripts/after-pack.mjs",
- "extraResources": [
- {
- "from": "build/install-stamp.json",
- "to": "install-stamp.json"
- },
- {
- "from": "assets/icon.ico",
- "to": "icon.ico"
- }
- ],
- "asar": true,
- "afterSign": "scripts/notarize.mjs",
- "asarUnpack": [
- "**/*.node",
- "**/prebuilds/**",
- "dist/**"
- ],
- "mac": {
- "category": "public.app-category.developer-tools",
- "entitlements": "electron/entitlements.mac.plist",
- "entitlementsInherit": "electron/entitlements.mac.inherit.plist",
- "extendInfo": {
- "CFBundleDisplayName": "Hermes",
- "CFBundleExecutable": "Hermes",
- "CFBundleName": "Hermes",
- "NSAudioCaptureUsageDescription": "Hermes uses audio capture for voice conversations.",
- "NSCameraUsageDescription": "Hermes uses the camera when a plugin or feature you enable requests it.",
- "NSMicrophoneUsageDescription": "Hermes uses the microphone for voice input and voice conversations.",
- "NSCalendarsUsageDescription": "Hermes needs access to Calendar to provide requested meeting and scheduling support.",
- "NSCalendarsFullAccessUsageDescription": "Hermes needs full access to Calendar to read and manage events when explicitly requested.",
- "NSRemindersUsageDescription": "Hermes needs access to Reminders to provide requested personal-assistant and scheduling support.",
- "NSRemindersFullAccessUsageDescription": "Hermes needs full access to Reminders to read and manage reminders when explicitly requested.",
- "NSScreenCaptureUsageDescription": "Hermes captures the screen when you ask the agent to screenshot or record it.",
- "NSLocalNetworkUsageDescription": "Hermes connects to devices on your local network when a plugin or feature you enable requests it.",
- "NSAppleMusicUsageDescription": "Hermes accesses your music library when a plugin or feature you enable requests it."
- },
- "gatekeeperAssess": false,
- "hardenedRuntime": true,
- "target": [
- "dmg",
- "zip"
- ]
- },
- "dmg": {
- "title": "Install Hermes",
- "backgroundColor": "#f5f5f7",
- "iconSize": 96,
- "window": {
- "width": 560,
- "height": 360
- },
- "contents": [
- {
- "x": 160,
- "y": 170,
- "type": "file"
- },
- {
- "x": 400,
- "y": 170,
- "type": "link",
- "path": "/Applications"
- }
- ]
- },
- "win": {
- "legalTrademarks": "Hermes",
- "target": [
- "nsis",
- "msi"
- ],
- "signAndEditExecutable": false
- },
- "linux": {
- "category": "Development",
- "maintainer": "Nous Research <[email protected]>",
- "synopsis": "Native desktop shell for Hermes Agent.",
- "target": [
- "AppImage",
- "deb",
- "rpm"
- ]
- },
- "nsis": {
- "oneClick": false,
- "allowToChangeInstallationDirectory": true,
- "perMachine": false,
- "shortcutName": "Hermes",
- "uninstallDisplayName": "Hermes",
- "warningsAsErrors": false
- }
}
}
diff --git a/apps/desktop/product-identity.cjs b/apps/desktop/product-identity.cjs
new file mode 100644
index 00000000000..1ffed574aea
--- /dev/null
+++ b/apps/desktop/product-identity.cjs
@@ -0,0 +1,71 @@
+// The desktop product identity — THE single source for every name-shaped
+// value a variant owns. HERMES_DESKTOP_VARIANT=light builds "Hermes
+// Light", the remote-only client; everything else is full "Hermes".
+//
+// Consumed at build time by electron-builder.config.cjs (packaging
+// identity). electron/product-identity.ts is the typed runtime accessor.
+// @ts-check
+/// <reference types="node" />
+'use strict'
+
+const variants = {
+ '': { display: 'Hermes', kebab: 'hermes', pascal: 'Hermes' },
+ light: {
+ display: 'Hermes Light',
+ kebab: 'hermes-light',
+ pascal: 'HermesLight'
+ },
+ bundled: {
+ display: 'Hermes',
+ kebab: 'hermes-bundled',
+ pascal: 'HermesBundled'
+ }
+}
+
+const variant = process.env.HERMES_DESKTOP_VARIANT || ''
+if (!['', 'light', 'bundled', 'store'].includes(variant)) {
+ throw new Error(`Unknown HERMES_DESKTOP_VARIANT ${variant}. expected one of (empty), light, bundled, store`)
+}
+
+// 'store' is a Store-submission packaging identity layered on the bundled
+// variant: same Electron app (displayName/appId/appNamePascal -> shared
+// userData + single-instance lock with the out-of-store install), different
+// MSIX package identity. The Store re-signs on submission.
+const store = variant === 'store'
+const light = variant === 'light'
+const name = variants[store ? 'bundled' : (variant || '')]
+
+// The electron-updater feed channel this build PUBLISHES to. A nightly
+// tag (vX.Y.0-nightly.YYYYMMDDHHMMSS) writes nightly.yml / light-nightly.yml;
+// stable tags write latest.yml / light.yml. Keyed on the payload tag so
+// the one release workflow serves both channels — a nightly build can
+// never overwrite the stable feed file, and vice versa.
+const nightly = /-nightly\.20\d{6}(?:\d{6})?$/.test(process.env.HERMES_PAYLOAD_TAG || '')
+
+/** @typedef {import("./product-identity.d.cts")} ProductIdentity */
+
+/** @type {ProductIdentity} */
+const identity = {
+ store,
+ light,
+ displayName: name.display,
+ appId: `com.nousresearch.${name.kebab}`,
+ // The store build never publishes to a release feed (the Store owns its
+ // updates); null means "no feed" for its publish config.
+ channel: store ? null : light ? (nightly ? 'light-nightly' : 'light') : (nightly ? 'nightly' : 'latest'),
+ appNamePascal: name.pascal,
+ msixAppIdWithOrg: `NousResearch.${name.pascal}`,
+ ...(store
+ ? {
+ storeMsix: {
+ // Partner Center publisher identity (the account's publisher ID) —
+ // validated + re-signed by the Store on submission.
+ identityName: 'NousResearchInc.HermesAgent',
+ publisher: 'CN=EE6D86E4-606F-4E38-B940-AD7248C9D519',
+ publisherDisplayName: 'Nous Research Inc.'
+ }
+ }
+ : {})
+}
+
+module.exports = identity
diff --git a/apps/desktop/product-identity.d.cts b/apps/desktop/product-identity.d.cts
new file mode 100644
index 00000000000..01b1b0d6dad
--- /dev/null
+++ b/apps/desktop/product-identity.d.cts
@@ -0,0 +1,27 @@
+interface ProductIdentity {
+ /** True when this artifact is Hermes Light (remote-only client). */
+ light: boolean
+ /** True for a Store-submission build (Windows Store packaging identity). */
+ store: boolean
+ /** Display name. e.g. "Hermes Light" */
+ displayName: string
+ /** OS-level app identity. e.g. "com.nousresearch.hermes-light" */
+ appId: string
+ /** app name in pascal case. e.g. "HermesLight" */
+ appNamePascal: string
+ /** OS-level app identity w/ org prefix. e.g. "NousResearch.HermesLight" */
+ msixAppIdWithOrg: string
+ /** electron-updater feed channel this build publishes to. Stable tags:
+ * "latest" | "light"; nightly tags: "nightly" | "light-nightly". Null
+ * for a store build (the Store owns its updates; no release feed). */
+ channel: string | null
+ /** Store-submission MSIX packaging identity. Present only when `store`. */
+ storeMsix?: {
+ identityName: string
+ publisher: string
+ publisherDisplayName: string
+ }
+}
+
+declare const identity: ProductIdentity
+export = identity
diff --git a/apps/desktop/scripts/after-pack.mjs b/apps/desktop/scripts/after-pack.mjs
index 30c83a08a64..5b1c7150d81 100644
--- a/apps/desktop/scripts/after-pack.mjs
+++ b/apps/desktop/scripts/after-pack.mjs
@@ -28,7 +28,39 @@ import { sanitizeTree } from './sanitize-pe-signatures.mjs'
import { stampExeIdentity } from './set-exe-identity.mjs'
export default async function afterPack(context) {
- if (context.electronPlatformName !== 'win32') {
+ const platform = context.electronPlatformName
+ if (platform === 'darwin') {
+ const payload = findPackedPayload(context.appOutDir, platform)
+ if (payload) {
+ const dropped = stripFetchCache(payload)
+ const n = relativizePayloadLinks(payload)
+ const entitlements = path.join(import.meta.dirname, '..', 'electron', 'entitlements.mac.inherit.plist')
+ const { identity, keychain } = await resolveSigningIdentity(context.packager)
+ const nested = signNestedChromium(payload, { entitlements, identity, keychain })
+ console.log(
+ `[after-pack] dropped ${dropped} fetch- cache dirs; relativized ${n} payload links; repaired ${nested.repaired} framework links; signed ${nested.signed} nested chromium targets` +
+ (identity ? ` as ${identity}` : ' (no Developer ID in the builder keychain)')
+ )
+ }
+ return
+ }
+ if (platform === 'linux') {
+ // Linux has no codesign, but the relocatable venv's bin/python* are
+ // ABSOLUTE symlinks onto the build runner's store interpreter, so they
+ // dangle once the unpacked tree moves (first-boot smoke, or a user
+ // installing to a different path). Rewrite them to RELATIVE symlinks
+ // (the target lives inside the payload) — a relative link survives
+ // relocation AND keeps the interpreter's real prefix resolution (a
+ // copied binary would fall back to the baked build prefix and lose its
+ // stdlib). Out-of-payload targets fail the build.
+ const payload = findPackedPayload(context.appOutDir, platform)
+ if (payload) {
+ const n = relativizePayloadLinks(payload)
+ console.log(`[after-pack] relativized ${n} payload links so the relocatable venv survives relocation`)
+ }
+ return
+ }
+ if (platform !== 'win32') {
return
}
@@ -36,6 +68,18 @@ export default async function afterPack(context) {
const exe = path.join(context.appOutDir, `${productName}.exe`)
const desktopRoot = path.resolve(import.meta.dirname, '..')
+ // Repair dangling PE certificate tables BEFORE electron-builder signs the
+ // tree. A stripped-but-still-declared signature makes signtool reject the
+ // file with 0x800700C1, and AppxSIP inspects every PE inside the MSIX, so
+ // one bad payload DLL fails the whole package. Unlike the stamp below this
+ // is NOT best-effort: shipping past it means shipping an unsignable bundle.
+ // this is a hack until https://github.com/astral-sh/python-build-standalone/pull/1217 is merged.
+ const { scanned, repaired } = sanitizeTree(context.appOutDir)
+ console.log(`[after-pack] ${scanned} PEs scanned, ${repaired.length} dangling certificate tables cleared`)
+ for (const file of repaired) {
+ console.log(` ${file}`)
+ }
+
try {
await stampExeIdentity(exe, desktopRoot)
} catch (err) {
diff --git a/apps/desktop/scripts/audit-bundle-arch.mjs b/apps/desktop/scripts/audit-bundle-arch.mjs
new file mode 100644
index 00000000000..747285352a7
--- /dev/null
+++ b/apps/desktop/scripts/audit-bundle-arch.mjs
@@ -0,0 +1,290 @@
+// audit-bundle-arch.mjs: prove every native binary inside a packed desktop
+// bundle was built for the target architecture.
+//
+// Why: wrong-arch binaries run FINE on the build runner (Windows-on-ARM and
+// Rosetta emulate x64 silently) and only fail — or quietly burn cycles in
+// emulation — on user machines. One x64 pip launcher shim inside an arm64
+// payload shipped exactly this way. The build must fail loudly instead.
+//
+// The scan walks every file, sniffs the magic bytes (PE / ELF / Mach-O,
+// including fat headers), and reports any binary whose architecture does
+// not match the target. Non-binaries are skipped by content, not by file
+// extension — a mis-extensioned .exe still gets caught.
+//
+// CLI:
+// node audit-bundle-arch.mjs --arch=arm64 --root=release
+//
+// --root is scanned for the unpacked app dirs electron-builder produces
+// (win-unpacked, win-arm64-unpacked, linux-unpacked, mac/, mac-arm64/, …).
+// Auditing the unpacked tree covers the exact bytes the installer embeds:
+// MSIX/DMG/AppImage add compression around it, not content.
+
+import fs from "node:fs"
+import path from "node:path"
+
+import { isMain } from "./utils.mjs"
+
+// ─── pure classification (unit-tested, no I/O) ─────────────────────────────
+
+const PE_MACHINES = {
+ 0x014c: "ia32",
+ 0x01c0: "arm",
+ 0x01c4: "arm",
+ 0x8664: "x64",
+ 0xaa64: "arm64",
+ 0xa641: "arm64ec", // ARM64EC: arm64-ABI code, runs only on arm64 Windows
+}
+
+const ELF_MACHINES = {
+ 0x03: "ia32",
+ 0x28: "arm",
+ 0x3e: "x64",
+ 0xb7: "arm64",
+}
+
+const MACHO_CPUTYPES = {
+ 0x01000007: "x64",
+ 0x0100000c: "arm64",
+ 0x00000007: "ia32",
+ 0x0000000c: "arm",
+}
+
+/**
+ * Classify a buffer holding the head of a file (>= 64 bytes is plenty for
+ * every format except PE, whose COFF header lives at an offset named at
+ * 0x3c — pass headerAt for that case; classifyFile below handles it).
+ *
+ * Returns null for non-binaries, or { format, arches } where arches lists
+ * every architecture the file carries (>1 only for Mach-O fat binaries).
+ */
+export function classifyHeader(buf) {
+ if (buf.length >= 0x40 && buf[0] === 0x4d && buf[1] === 0x5a) {
+ // PE: the real machine field needs a second read at e_lfanew; caller
+ // resolves it. Report the format and the offset to read.
+ return { format: "pe", peHeaderOffset: buf.readUInt32LE(0x3c) }
+ }
+ if (buf.length >= 20 && buf[0] === 0x7f && buf[1] === 0x45 && buf[2] === 0x4c && buf[3] === 0x46) {
+ const machine = buf.readUInt16LE(18)
+ return { format: "elf", arches: [ELF_MACHINES[machine] || `unknown(0x${machine.toString(16)})`] }
+ }
+ if (buf.length >= 8) {
+ const be = buf.readUInt32BE(0)
+ // Thin Mach-O, either endianness.
+ if (be === 0xfeedface || be === 0xfeedfacf) {
+ const cputype = buf.readUInt32BE(4)
+ return { format: "macho", arches: [MACHO_CPUTYPES[cputype] || `unknown(0x${cputype.toString(16)})`] }
+ }
+ if (be === 0xcefaedfe || be === 0xcffaedfe) {
+ const cputype = buf.readUInt32LE(4)
+ return { format: "macho", arches: [MACHO_CPUTYPES[cputype] || `unknown(0x${cputype.toString(16)})`] }
+ }
+ // Fat/universal: big-endian header, one arch entry per slice.
+ if (be === 0xcafebabe) {
+ const count = buf.readUInt32BE(4)
+ // A Java .class file shares the magic; its "count" here is the
+ // bytecode version (>= 45). Real fat binaries carry a few slices.
+ if (count > 0 && count < 30) {
+ const arches = []
+ for (let i = 0; i < count && 8 + i * 20 + 4 <= buf.length; i++) {
+ const cputype = buf.readUInt32BE(8 + i * 20)
+ arches.push(MACHO_CPUTYPES[cputype] || `unknown(0x${cputype.toString(16)})`)
+ }
+ return { format: "macho-fat", arches }
+ }
+ }
+ }
+ return null
+}
+
+/**
+ * Resolve a PE machine code (read at peHeaderOffset+4) to an arch name.
+ * Split from classifyHeader so the walker can do the second read lazily.
+ */
+export function peArch(machineCode) {
+ return PE_MACHINES[machineCode] || `unknown(0x${machineCode.toString(16)})`
+}
+
+/**
+ * Does a classified binary satisfy the target arch?
+ * - exact match, always
+ * - macOS fat binary: any slice matching is enough (universal ships both)
+ * - arm64 targets accept arm64ec PEs (arm64-ABI by definition)
+ * Everything else — including "unknown(...)" — is a mismatch: an
+ * unclassifiable machine code in a shipped binary deserves a loud failure,
+ * not a shrug.
+ */
+export function archMatches(arches, targetArch) {
+ return arches.some((a) => a === targetArch || (targetArch === "arm64" && a === "arm64ec"))
+}
+
+/**
+ * The unpacked-app directories electron-builder leaves under release/ for
+ * a target arch. Names differ per platform: Windows/Linux use
+ * <platform>[-<arch>]-unpacked with the HOST-default arch unsuffixed; mac
+ * uses mac[-<arch>]/. Match by shape, not an exhaustive list, so a rename
+ * in electron-builder fails the audit (no dirs found) instead of silently
+ * auditing nothing.
+ */
+export function findUnpackedDirs(entries) {
+ return entries.filter((name) => /-unpacked$/.test(name) || /^mac(-[a-z0-9]+)?$/.test(name))
+}
+
+// ─── impure walker + CLI ────────────────────────────────────────────────────
+
+function classifyFile(filePath) {
+ const fd = fs.openSync(filePath, "r")
+ try {
+ const head = Buffer.alloc(4096)
+ const n = fs.readSync(fd, head, 0, head.length, 0)
+ const sniffed = classifyHeader(head.subarray(0, n))
+ if (!sniffed) return null
+ if (sniffed.format !== "pe") return sniffed
+ // PE: read the 6 bytes at e_lfanew — "PE\0\0" + machine.
+ const peHead = Buffer.alloc(6)
+ const m = fs.readSync(fd, peHead, 0, 6, sniffed.peHeaderOffset)
+ if (m < 6 || peHead.readUInt32LE(0) !== 0x00004550) {
+ return null // MZ without a PE header: DOS-era stub or corrupt — not a shippable binary format we know.
+ }
+ return { format: "pe", arches: [peArch(peHead.readUInt16LE(4))] }
+ } finally {
+ fs.closeSync(fd)
+ }
+}
+
+function* walkFiles(dir) {
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
+ const full = path.join(dir, entry.name)
+ if (entry.isSymbolicLink()) continue // targets are scanned as files where they live
+ if (entry.isDirectory()) {
+ yield* walkFiles(full)
+ } else if (entry.isFile()) {
+ yield full
+ }
+ }
+}
+
+/**
+ * Paths allowed to carry foreign-arch binaries. pip and setuptools ship
+ * Windows launcher STUB TEMPLATES as package data (distlib t32/t64/w32/
+ * w64.exe, setuptools cli*.exe / gui*.exe). They are not executed from
+ * here; pip copies one to build a console-script shim at install time.
+ * They exist on every platform and are always x86 PEs — inside an arm64
+ * or linux payload they are inert bytes, not a wrong-arch bug.
+ *
+ * Anchored at agent-payload (not the tree root: mac nests the payload
+ * under Hermes.app/Contents/Resources/). The lib segment is `Lib` on
+ * Windows and `lib/python3.11` elsewhere; both separators appear in
+ * relative paths depending on the build host.
+ *
+ * PortableGit carries .NET AnyCPU/MSIL assemblies (Git Credential Manager:
+ * Avalonia.*, Atlassian.*, Microsoft.*, System.*, etc.) across mingw64/bin,
+ * mingw64/lib, and mingw64/libexec/git-core. Their PE machine field is 0x14c
+ * (ia32) because .NET assemblies are format-neutral — the CLR JITs them to
+ * the native arch at load time. It also ships usr/libexec/getprocaddr32.exe,
+ * a 32-bit MSYS2 helper. The staging script already PE-probes cmd/git.exe
+ * itself; the bundle audit does not need to re-audit PortableGit's internal
+ * MSYS2/.NET layout.
+ */
+const EXEMPT_PATTERNS = [
+ // pip / setuptools launcher STUB TEMPLATES. x86 PE templates pip copies
+ // when it writes a console-script shim. Present on every platform.
+ // Live under the payload python store entry AND the relocatable venv.
+ /agent-payload[/\\](tools[/\\]python-[^/\\]+[/\\](Lib|lib[/\\]python[\d.]+)|venv[/\\](Lib|lib[/\\]python[\d.]+))[/\\]site-packages[/\\](setuptools|pip[/\\]_vendor[/\\]distlib)[/\\]/i,
+ // PortableGit internals under the payload tool store.
+ /agent-payload[/\\]tools[/\\]git(-[^/\\]+)?[/\\](mingw64|clangarm64|usr|cmd)[/\\]/i,
+ // discord.py ships x64 and x86 opus; opus.py loads by bitness.
+ /agent-payload[/\\]venv[/\\](Lib|lib[/\\]python[\d.]+)[/\\]site-packages[/\\]discord[/\\]bin[/\\]libopus-0\.(x64|x86)\.dll$/i,
+ // pvporcupine ships one native lib per OS/arch in the same wheel.
+ // Only the matching sibling is loaded.
+ /agent-payload[/\\]venv[/\\](Lib|lib[/\\]python[\d.]+)[/\\]site-packages[/\\]pvporcupine[/\\]lib[/\\]/i,
+ // debugpy ships attach helpers for every OS/arch in one wheel.
+ /agent-payload[/\\]venv[/\\](Lib|lib[/\\]python[\d.]+)[/\\]site-packages[/\\]debugpy[/\\]_vendored[/\\]pydevd[/\\]/i,
+ // agent-browser ships no native win-arm64 build; on win32-arm64 the
+ // payload stages the x64 exe, which Windows runs under built-in
+ // emulation (its own postinstall falls back to x64 on arm64).
+ /agent-payload[/\\]tools[/\\]agent-browser-[^/\\]+[/\\]bin[/\\]agent-browser-win32-x64\.exe$/i,
+ // chromium / chromium-headless-shell are pm packages too: CfT publishes
+ // no native win-arm64 build, so on win32-arm64 the payload stages the
+ // win64 (x64) build and Windows runs it under emulation — the same
+ // choice the package code makes (PlaywrightBrowser._CFT maps win32-arm64
+ // to win64). Store entries are named by playwright revision only
+ // (chromium-<rev>, chromium_headless_shell-<rev>, dashes→underscores);
+ // the zips extract in place, so the x64 trees carry a -win64 segment.
+ // Scoping to that segment keeps linux/darwin chromium audited.
+ /agent-payload[/\\]tools[/\\]chromium(_headless_shell)?-[^/\\]+[/\\](chrome|chrome-headless-shell)-win64[/\\]/i,
+]
+
+export function isExemptPath(relPath) {
+ return EXEMPT_PATTERNS.some((p) => p.test(relPath))
+}
+
+export function auditTree(rootDir, targetArch) {
+ const mismatches = []
+ let binaries = 0
+ let exempted = 0
+ for (const file of walkFiles(rootDir)) {
+ let info
+ try {
+ info = classifyFile(file)
+ } catch {
+ continue // unreadable file: electron-builder would have failed on it already
+ }
+ if (!info) continue
+ binaries += 1
+ if (!archMatches(info.arches, targetArch)) {
+ const rel = path.relative(rootDir, file)
+ if (isExemptPath(rel)) {
+ exempted += 1
+ continue
+ }
+ mismatches.push({ file: rel, format: info.format, arches: info.arches })
+ }
+ }
+ return { binaries, exempted, mismatches }
+}
+
+function main() {
+ const args = Object.fromEntries(
+ process.argv.slice(2).map((a) => {
+ const [k, ...v] = a.replace(/^--/, "").split("=")
+ return [k, v.join("=")]
+ })
+ )
+ const targetArch = args.arch
+ const root = args.root
+ if (!targetArch || !root) {
+ console.error("usage: audit-bundle-arch.mjs --arch=<x64|arm64> --root=<release dir>")
+ process.exit(2)
+ }
+
+ const dirs = findUnpackedDirs(fs.readdirSync(root)).map((d) => path.join(root, d))
+ if (dirs.length === 0) {
+ console.error(`audit-bundle-arch: no unpacked app directory under ${root} — nothing was audited, failing`)
+ process.exit(1)
+ }
+
+ let failed = false
+ for (const dir of dirs) {
+ const { binaries, exempted, mismatches } = auditTree(dir, targetArch)
+ if (binaries === 0) {
+ console.error(`audit-bundle-arch: ${dir}: found no native binaries at all — the scan is broken, failing`)
+ failed = true
+ continue
+ }
+ if (mismatches.length > 0) {
+ failed = true
+ console.error(`audit-bundle-arch: ${dir}: ${mismatches.length} binaries do not match --arch=${targetArch}:`)
+ for (const m of mismatches) {
+ console.error(` [${m.format} ${m.arches.join("+")}] ${m.file}`)
+ }
+ } else {
+ const exemptNote = exempted > 0 ? ` (${exempted} exempt launcher stubs)` : ""
+ console.log(`audit-bundle-arch: ${dir}: ${binaries} native binaries, all ${targetArch}${exemptNote}`)
+ }
+ }
+ process.exit(failed ? 1 : 0)
+}
+
+if (isMain(import.meta.url)) {
+ main()
+}
diff --git a/apps/desktop/scripts/audit-bundle-arch.test.mjs b/apps/desktop/scripts/audit-bundle-arch.test.mjs
new file mode 100644
index 00000000000..f44696f142c
--- /dev/null
+++ b/apps/desktop/scripts/audit-bundle-arch.test.mjs
@@ -0,0 +1,180 @@
+import assert from 'node:assert/strict'
+import { test } from 'vitest'
+
+import { archMatches, classifyHeader, findUnpackedDirs, isExemptPath, peArch } from '../scripts/audit-bundle-arch.mjs'
+
+// ─── header builders: the smallest buffers each format needs ───────────────
+
+function elfHeader(machine) {
+ const buf = Buffer.alloc(64)
+ buf.write('\x7fELF', 0, 'latin1')
+ buf.writeUInt16LE(machine, 18)
+ return buf
+}
+
+function machoThin(cputype, { swapped = false } = {}) {
+ const buf = Buffer.alloc(64)
+ if (swapped) {
+ buf.writeUInt32BE(0xcffaedfe, 0) // magic as stored little-endian on disk
+ buf.writeUInt32LE(cputype, 4)
+ } else {
+ buf.writeUInt32BE(0xfeedfacf, 0)
+ buf.writeUInt32BE(cputype, 4)
+ }
+ return buf
+}
+
+function machoFat(cputypes) {
+ const buf = Buffer.alloc(8 + cputypes.length * 20)
+ buf.writeUInt32BE(0xcafebabe, 0)
+ buf.writeUInt32BE(cputypes.length, 4)
+ cputypes.forEach((t, i) => buf.writeUInt32BE(t, 8 + i * 20))
+ return buf
+}
+
+function mzStub(peOffset) {
+ const buf = Buffer.alloc(0x40)
+ buf.write('MZ', 0, 'latin1')
+ buf.writeUInt32LE(peOffset, 0x3c)
+ return buf
+}
+
+// ─── classifyHeader ─────────────────────────────────────────────────
+
+test('classifyHeader names the arch for each executable format', () => {
+ assert.deepEqual(classifyHeader(elfHeader(0x3e)).arches, ['x64'])
+ assert.deepEqual(classifyHeader(elfHeader(0xb7)).arches, ['arm64'])
+ assert.deepEqual(classifyHeader(machoThin(0x0100000c)).arches, ['arm64'])
+ assert.deepEqual(classifyHeader(machoThin(0x01000007, { swapped: true })).arches, ['x64'])
+ assert.deepEqual(classifyHeader(machoFat([0x01000007, 0x0100000c])).arches, ['x64', 'arm64'])
+})
+
+test('classifyHeader defers PE to the offset named in the MZ stub', () => {
+ const sniffed = classifyHeader(mzStub(0x180))
+ assert.equal(sniffed.format, 'pe')
+ assert.equal(sniffed.peHeaderOffset, 0x180)
+ // The machine code itself resolves through peArch.
+ assert.equal(peArch(0x8664), 'x64')
+ assert.equal(peArch(0xaa64), 'arm64')
+ assert.equal(peArch(0xa641), 'arm64ec')
+ assert.match(peArch(0xbeef), /unknown/)
+})
+
+test('classifyHeader skips non-binaries, tiny files, and Java class files', () => {
+ assert.equal(classifyHeader(Buffer.from('#!/bin/sh\necho hi\n')), null)
+ assert.equal(classifyHeader(Buffer.from('MZ')), null) // too short to carry a PE offset
+ assert.equal(classifyHeader(Buffer.alloc(0)), null)
+ // Java .class: same magic as a fat Mach-O, giant "slice count" (version).
+ const javaClass = Buffer.alloc(16)
+ javaClass.writeUInt32BE(0xcafebabe, 0)
+ javaClass.writeUInt32BE(65, 4)
+ assert.equal(classifyHeader(javaClass), null)
+})
+
+// ─── archMatches ─────────────────────────────────────────────────
+
+test('archMatches: exact match, universal slices, arm64ec, and rejections', () => {
+ assert.ok(archMatches(['arm64'], 'arm64'))
+ assert.ok(archMatches(['x64', 'arm64'], 'arm64')) // universal binary covers the target
+ assert.ok(archMatches(['arm64ec'], 'arm64')) // arm64-ABI by definition
+ assert.ok(!archMatches(['x64'], 'arm64')) // the shipped-x64-shim bug this audit exists for
+ assert.ok(!archMatches(['arm64ec'], 'x64')) // arm64ec does not run on x64 hosts
+ assert.ok(!archMatches(['unknown(0xbeef)'], 'x64')) // unclassifiable ships nowhere
+})
+
+// ─── findUnpackedDirs ─────────────────────────────────────────────────
+
+test('findUnpackedDirs matches electron-builder output shapes only', () => {
+ const dirs = findUnpackedDirs([
+ 'win-unpacked', 'win-arm64-unpacked', 'linux-unpacked', 'linux-arm64-unpacked',
+ 'mac', 'mac-arm64',
+ 'builder-debug.yml', 'Hermes-0.20.0.exe', 'latest.yml', '.icon-ico'
+ ])
+ assert.deepEqual(dirs, [
+ 'win-unpacked', 'win-arm64-unpacked', 'linux-unpacked', 'linux-arm64-unpacked',
+ 'mac', 'mac-arm64'
+ ])
+})
+
+// ─── the git exemption is PortableGit-shaped, not git-shaped ───────────────
+
+test('PortableGit internals stay exempt under the payload store', () => {
+ // .NET assemblies report ia32 because they are format-neutral.
+ for (const relPath of [
+ 'resources/agent-payload/tools/git-2.53.0-win32-x64/mingw64/bin/Avalonia.dll',
+ 'resources\\agent-payload\\tools\\git-2.53.0-win32-x64\\mingw64\\libexec\\git-core\\GitHub.dll',
+ 'resources\\agent-payload\\tools\\git-2.53.0-win32-x64\\usr\\libexec\\getprocaddr32.exe',
+ 'resources/agent-payload/tools/git-2.54.0-win32-arm64/clangarm64/libexec/git-core/msalruntime.dll'
+ ]) {
+ assert.equal(isExemptPath(relPath), true, relPath)
+ }
+})
+
+test('a POSIX git store entry is audited', () => {
+ // posix uses system git; a linux/darwin git store has no mingw64/usr/cmd
+ // segment, so a wrong-arch binary there must fail the audit.
+ for (const relPath of [
+ 'resources/agent-payload/tools/git-2.53.0-linux-x64/bin/git',
+ 'resources/agent-payload/tools/git-2.53.0-darwin-arm64/libexec/git-core/git-remote-https'
+ ]) {
+ assert.equal(isExemptPath(relPath), false, relPath)
+ }
+})
+
+test('pip and setuptools launcher stubs are exempt in the store and the venv', () => {
+ for (const relPath of [
+ 'resources/agent-payload/tools/python-3.11.16+20260814-linux-x64/lib/python3.11/site-packages/pip/_vendor/distlib/t32.exe',
+ 'resources/agent-payload/tools/python-3.11.16+20260814-linux-x64/lib/python3.11/site-packages/setuptools/cli.exe',
+ 'resources/agent-payload/venv/lib/python3.11/site-packages/setuptools/cli-32.exe',
+ 'resources/agent-payload/venv/Lib/site-packages/setuptools/cli.exe'
+ ]) {
+ assert.equal(isExemptPath(relPath), true, relPath)
+ }
+})
+
+test('discord opus and pvporcupine multi-arch siblings are exempt', () => {
+ for (const relPath of [
+ 'resources/agent-payload/venv/lib/python3.11/site-packages/discord/bin/libopus-0.x86.dll',
+ 'resources/agent-payload/venv/lib/python3.11/site-packages/discord/bin/libopus-0.x64.dll',
+ 'resources/agent-payload/venv/lib/python3.11/site-packages/pvporcupine/lib/mac/arm64/libpv_porcupine.dylib',
+ 'resources/agent-payload/venv/lib/python3.11/site-packages/pvporcupine/lib/raspberry-pi/arm11/libpv_porcupine.so',
+ 'resources/agent-payload/venv/lib/python3.11/site-packages/debugpy/_vendored/pydevd/pydevd_attach_to_process/attach_linux_amd64.so',
+ 'resources/agent-payload/venv/lib/python3.11/site-packages/debugpy/_vendored/pydevd/pydevd_attach_to_process/inject_dll_x86.exe'
+ ]) {
+ assert.equal(isExemptPath(relPath), true, relPath)
+ }
+})
+
+test('the emulated x64 agent-browser exe is exempt in a win32-arm64 payload', () => {
+ for (const relPath of [
+ 'resources/agent-payload/tools/agent-browser-0.35.1-win32-arm64/bin/agent-browser-win32-x64.exe',
+ 'resources\\agent-payload\\tools\\agent-browser-0.26.0-win32-arm64\\bin\\agent-browser-win32-x64.exe'
+ ]) {
+ assert.equal(isExemptPath(relPath), true, relPath)
+ }
+ // A non-chromium x64 binary in the payload store still fails: the
+ // chromium exemption is scoped to the store entries' -win64 trees, not
+ // to "any x64 exe under tools/".
+ assert.equal(isExemptPath('resources/agent-payload/tools/something-1.0-win32-arm64/bin/thing.exe'), false)
+})
+
+test('the emulated x64 chromium trees are exempt in a win32-arm64 payload', () => {
+ // PlaywrightBrowser._CFT maps win32-arm64 to the CfT win64 (x64) build;
+ // store entries are named by playwright revision (dashes→underscores)
+ // and the zip extracts in place, so the x64 trees sit under
+ // chrome-win64 / chrome-headless-shell-win64 inside the entry.
+ for (const relPath of [
+ 'resources/agent-payload/tools/chromium-1208/chrome-win64/chrome.exe',
+ 'resources\\agent-payload\\tools\\chromium-1208\\chrome-win64\\chrome.dll',
+ 'resources/agent-payload/tools/chromium_headless_shell-1208/chrome-headless-shell-win64/chrome-headless-shell.exe'
+ ]) {
+ assert.equal(isExemptPath(relPath), true, relPath)
+ }
+ // The linux/darwin chromium trees stay audited: no -win64 segment.
+ assert.equal(isExemptPath('resources/agent-payload/tools/chromium-1208/chrome-linux/chrome'), false)
+ assert.equal(isExemptPath('resources/agent-payload/tools/chromium-1208/chrome-mac-arm64/chrome'), false)
+})
+
+test('a random payload binary is not exempt', () => {
+ assert.equal(isExemptPath('resources/agent-payload/hermes-agent/something.exe'), false)
+})
diff --git a/apps/desktop/scripts/before-build.mjs b/apps/desktop/scripts/before-build.mjs
index 04d81edf121..acb4d5b14c8 100644
--- a/apps/desktop/scripts/before-build.mjs
+++ b/apps/desktop/scripts/before-build.mjs
@@ -2,9 +2,20 @@
* Desktop bundles ship precompiled renderer assets. Returning false here tells
* electron-builder to skip the node_modules collector/install step, which
* avoids workspace dependency graph explosions and keeps packaging
- * deterministic across environments. The Hermes Agent Python payload is no
- * longer bundled; the Electron app fetches it at first launch via
- * `install.ps1`'s stage protocol (Windows). See `electron/main.ts`.
+ * deterministic across environments.
+ *
+ * Also guarantees build/agent-payload exists: extraResources copies it on
+ * every build, and electron-builder's behavior for a missing `from` varies
+ * between versions. A bundled build stages the real payload there first
+ * (`hermes pm bundle --out apps/desktop/build/agent-payload`); anything else
+ * gets a stub manifest with external:true, which resolvePayload() treats as
+ * "no payload" so the backend resolver falls through to the runtime rungs.
+ *
+ * Also stages the MSIX build-time assets (the build/appx icon set and the
+ * build/msix-extensions.xml fragment the config points customExtensionsPath
+ * at). These MUST happen here, in the hook electron-builder calls at build
+ * time — not in electron-builder.config.cjs at require time, or every
+ * typecheck/test import of the config would write files.
*/
import fs from 'node:fs'
import path from 'node:path'
@@ -20,6 +31,17 @@ const {
} = require('../product-identity.cjs')
export default async function beforeBuild() {
+ stageMsixAssets()
+ writeMsixExtensions()
+
+ const payloadDir = path.join(import.meta.dirname, '..', 'build', 'agent-payload')
+ const manifest = path.join(payloadDir, 'manifest.json')
+
+ if (!fs.existsSync(manifest)) {
+ fs.mkdirSync(payloadDir, { recursive: true })
+ fs.writeFileSync(manifest, JSON.stringify({ schema: 1, external: true }, null, 2) + '\n')
+ }
+
return false
}
@@ -95,17 +117,19 @@ ${aliases}`
export function appExecutionAliasExtensions(launchers = CLI_LAUNCHER_SPECS.map((s) => s.name)) {
const bs = String.fromCharCode(92)
const executable = (name) => ['app', 'resources', 'agent-payload', 'bin', `${name}.exe`].join(bs)
- return launchers
- .map(
- (name) => `<uap5:Extension
+ // ONE windows.appExecutionAlias extension per package — makeappx rejects a
+ // second one with the opaque 0x80080204 (A/B-verified against the 26100
+ // kit). Every launcher alias rides in the same extension's AppExecutionAlias;
+ // the Executable attribute names the exe that serves the aliases.
+ return `<uap5:Extension
xmlns:uap5="http://schemas.microsoft.com/appx/manifest/uap/windows10/5"
Category="windows.appExecutionAlias"
- Executable="${executable(name)}"
+ Executable="${executable(launchers[0])}"
EntryPoint="Windows.FullTrustApplication">
<uap5:AppExecutionAlias>
- <uap5:ExecutionAlias Alias="${name}.exe" />
+${launchers
+ .map((name) => ` <uap5:ExecutionAlias Alias="${name}.exe" />`)
+ .join('\n')}
</uap5:AppExecutionAlias>
</uap5:Extension>`
- )
- .join('\n')
}
diff --git a/apps/desktop/scripts/bundle-electron-main.mjs b/apps/desktop/scripts/bundle-electron-main.mjs
index 4cd93075b2f..940622115a4 100644
--- a/apps/desktop/scripts/bundle-electron-main.mjs
+++ b/apps/desktop/scripts/bundle-electron-main.mjs
@@ -10,9 +10,12 @@
// `electron` and `node-pty` are external (provided by the runtime / staged
// separately via stage-native-deps).
import { build } from 'esbuild'
+import { createRequire } from 'node:module'
import { resolve, dirname } from 'node:path'
import { fileURLToPath } from 'node:url'
-import { mkdirSync } from 'node:fs'
+import { mkdirSync, readFileSync } from 'node:fs'
+
+const require = createRequire(import.meta.url)
const here = dirname(fileURLToPath(import.meta.url))
const root = resolve(here, '..')
@@ -29,9 +32,31 @@ const external = ['electron', 'node-pty', 'get-windows', 'fs']
// behaves like a packaged build. Dev bundles (`--dev`) leave the env alone
// so HERMES_DESKTOP_DEV_SERVER / source-tree resolution keep working.
const isDev = process.argv.includes('--dev')
+
+// The install stamp is baked INTO the bundle: the define below sets the
+// __HERMES_INSTALL_STAMP__ global to the stamp OBJECT literal (the JSON
+// text is a valid JS expression, so no string round-trip). A baked
+// constant cannot be missing, stale, or edited after signing.
+// `npm run build` writes build/install-stamp.json immediately before this
+// script runs, so a missing file here is a broken build, not a thin one.
+// Dev bundles bake nothing — install-stamp.ts's typeof guard yields null,
+// because a dev run has no artifact to be truthful about (a stale stamp
+// from a previous build would lie about provenance).
+function bakedInstallStamp() {
+ const raw = readFileSync(resolve(root, 'build/install-stamp.json'), 'utf8')
+ JSON.parse(raw) // fail the build on malformed output, not first launch
+ return raw
+}
+
const define = isDev
? {}
- : { 'process.env.HERMES_DESKTOP_IS_PACKAGED': JSON.stringify(true) }
+ : {
+ 'process.env.HERMES_DESKTOP_IS_PACKAGED': JSON.stringify(true),
+ '__HERMES_INSTALL_STAMP__': bakedInstallStamp(),
+ // The product identity (name object, appId, deep-link scheme)
+ // baked the same way electron-builder gets it
+ '__HERMES_PRODUCT_IDENTITY__': JSON.stringify(require('../product-identity.cjs')),
+ }
// Bundle main.ts → dist/electron-main.mjs
await build({
diff --git a/apps/desktop/scripts/check-appinstaller-update.py b/apps/desktop/scripts/check-appinstaller-update.py
new file mode 100644
index 00000000000..ea50803eb99
--- /dev/null
+++ b/apps/desktop/scripts/check-appinstaller-update.py
@@ -0,0 +1,59 @@
+#!/usr/bin/env python3
+"""Check for an App Installer update for the running MSIX package.
+
+The out-of-store desktop installs are App Installer owned: the OS registered
+the .appinstaller URI as the package's update source at install, so the
+OS can tell us whether a newer package version is available. The desktop
+shows its own prompt + tears down before the OS applies the swap.
+
+Run with the BUNDLED payload python (the winrt package ships there):
+
+ <payload>/tools/<python-entry>/python.exe scripts/check-appinstaller-update.py
+
+Exit codes:
+ 0 no update available (or no App Installer source — nothing to do)
+ 2 update available (the caller decides whether to prompt/teardown)
+ 1 error (update availability unknown; the caller reports it honestly)
+"""
+
+import json
+import sys
+
+
+def main() -> int:
+ try:
+ from winrt.windows.applicationmodel import Package, PackageUpdateAvailability
+ from winrt.windows.management.deployment import PackageManager
+ except ImportError as exc:
+ # The winrt module is absent (older payload without the dep): the
+ # update check cannot run. Report unknown, not "no update".
+ print(json.dumps({"available": None, "error": f"winrt import failed: {exc}"}))
+ return 1
+
+ try:
+ package = Package.current()
+ except Exception as exc: # noqa: BLE001 — the API raises on non-packaged runs
+ # Not running as a packaged app (dev run) — nothing to check.
+ print(json.dumps({"available": False, "reason": "not-packaged"}))
+ return 0
+
+ package_family_name = package.id.family_name
+ manager = PackageManager()
+ try:
+ result = manager.check_package_update_availability_async(package_family_name).get()
+ except Exception as exc: # noqa: BLE001
+ print(json.dumps({"available": None, "error": f"check failed: {exc}"}))
+ return 1
+
+ availability = PackageUpdateAvailability(result.availability)
+ # Available / Required both mean "a newer package exists on the source".
+ available = availability in (
+ PackageUpdateAvailability.AVAILABLE,
+ PackageUpdateAvailability.REQUIRED,
+ )
+ print(json.dumps({"available": available, "availability": str(availability)}))
+ return 2 if available else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/apps/desktop/scripts/cli-launchers.test.mjs b/apps/desktop/scripts/cli-launchers.test.mjs
index 63eedadfe08..d569cfeda48 100644
--- a/apps/desktop/scripts/cli-launchers.test.mjs
+++ b/apps/desktop/scripts/cli-launchers.test.mjs
@@ -87,24 +87,26 @@ test('win wrapper rejects values that still contain placeholders', () => {
assert.throws(() => renderWinWrapper({ module: '__HERMES_REPO_REL__', func: 'main' }, RELS.relRepo, RELS.relSite))
})
-test('MSIX: one uap5 alias Extension per launcher exe, Executable naming that exe', () => {
+test('MSIX: ONE uap5 alias Extension naming every launcher alias', () => {
const xml = appExecutionAliasExtensions()
const blocks = xml.match(/<uap5:Extension\b/g) ?? []
- assert.equal(blocks.length, 3)
+ // makeappx rejects a second windows.appExecutionAlias Extension with the
+ // opaque 0x80080204 — all launcher aliases must ride in ONE block.
+ assert.equal(blocks.length, 1)
+ // The block's Executable names the exe that serves the aliases (first launcher).
+ const first = ['app', 'resources', 'agent-payload', 'bin', `${CLI_LAUNCHER_SPECS[0].name}.exe`].join('\\')
+ assert.ok(xml.includes(`Executable="${first}"`), 'Executable must name the first launcher exe')
+ // Every launcher exe gets exactly one ExecutionAlias inside the block.
for (const spec of CLI_LAUNCHER_SPECS) {
const expected = ['app', 'resources', 'agent-payload', 'bin', `${spec.name}.exe`].join('\\')
- assert.ok(
- xml.includes(`Executable="${expected}"`),
- `no alias Extension names ${expected}`
- )
// Backslashes: MSIX Executable must be manifest-backslash form.
assert.ok(!xml.includes(`${expected}/`), 'forward slashes are not manifest form')
+ assert.ok(
+ xml.includes(`<uap5:ExecutionAlias Alias="${spec.name}.exe" />`),
+ `no ExecutionAlias for ${spec.name}.exe`
+ )
}
- // The old rust shim's single-exe-argv[0]-dispatch shape is gone: each
- // block serves exactly ONE alias.
- for (const block of (xml.match(/<uap5:Extension[\s\S]*?<\/uap5:Extension>/g) ?? [])) {
- assert.equal((block.match(/<uap5:ExecutionAlias /g) ?? []).length, 1)
- }
+ assert.equal((xml.match(/<uap5:ExecutionAlias /g) ?? []).length, CLI_LAUNCHER_SPECS.length)
})
test('light variant emits no alias fragments', () => {
diff --git a/apps/desktop/scripts/fs-open-limit.cjs b/apps/desktop/scripts/fs-open-limit.cjs
new file mode 100644
index 00000000000..3b78aafab78
--- /dev/null
+++ b/apps/desktop/scripts/fs-open-limit.cjs
@@ -0,0 +1,144 @@
+// Bound how many fs.open calls are in flight at once, process-wide.
+//
+// WHY THIS EXISTS
+//
+// @electron/osx-sign decides what to sign by walking the whole .app
+// (dist/util.js::walk). The walk recurses with
+// `Promise.all(children.map(...))` and no concurrency bound, and every
+// regular file it reaches is probed by isbinaryfile, which opens a
+// descriptor. Peak descriptors therefore track the size of the tree, not
+// any fixed budget.
+//
+// The bundled payload makes that fatal. site-packages/lark_oapi alone is
+// 11,112 files, so signing died with:
+//
+// EMFILE: too many open files, open
+// '.../agent-payload/site-packages/lark_oapi/api/im/v1/model/reaction.py'
+//
+// Raising `ulimit -n` also clears it, but only moves the ceiling: the
+// walk still asks for as many descriptors as there are files, so the
+// next payload growth hits the new limit. This caps the demand instead.
+//
+// WHAT IT PATCHES
+//
+// `fs.open` (callback form) and `fs.promises.open`. That covers the
+// paths that actually consume descriptors here:
+// - isbinaryfile captures `promisify(fs.open)` at module load, so the
+// patch must be installed BEFORE it is required — hence --require.
+// - fs.createReadStream routes through the public fs.open (verified).
+//
+// Deliberately NOT patched: openSync. A synchronous open cannot be
+// queued without blocking the loop that would drain the queue, and it is
+// self-limiting anyway — one at a time, by definition.
+//
+// WHY IT CANNOT DEADLOCK
+//
+// The slot is released when the open() call SETTLES, not when the
+// descriptor is closed. A task holding ten descriptors occupies zero
+// slots while it works, so "hold one, open another" always makes
+// progress. Gating the descriptor's lifetime instead does deadlock —
+// measured: 4 tasks each holding 1 fd and awaiting a second, under
+// cap=2, never completes.
+//
+// Failures propagate unchanged: a rejected open releases its slot in
+// `finally` and the original error reaches the caller. This changes
+// timing only, never behavior.
+//
+// HERMES_FS_OPEN_LIMIT overrides the computed cap; 0 disables the patch.
+
+'use strict'
+
+const fs = require('fs')
+
+// The cap must sit well BELOW the process's fd limit, not near it. Each
+// queued open is held across the caller's read+close (osx-sign's walk
+// does exactly that), so `LIMIT` descriptors can be live at once, on top
+// of the fds node already holds for stdio, the module loader, sockets
+// and spawned children. Measured against the real walk: cap 100 fails at
+// a 64 limit and passes at 256; cap 16 passes at 64.
+//
+// So: a quarter of the soft limit, clamped to a sane band. On the macOS
+// default of 256 that is 64; on a raised limit it grows, keeping the
+// walk fast; on a tiny limit it shrinks instead of guaranteeing EMFILE.
+function defaultLimit() {
+ const override = Number(process.env.HERMES_FS_OPEN_LIMIT)
+ if (Number.isFinite(override) && override >= 0) return override
+ let soft = 0
+ try {
+ soft = process.report.getReport().userLimits.open_files.soft
+ } catch {
+ soft = 0
+ }
+ // `unlimited` reports as -1 (or a huge number); either way the clamp holds.
+ if (!Number.isFinite(soft) || soft <= 0) soft = 256
+ return Math.max(8, Math.min(512, Math.floor(soft / 4)))
+}
+
+const LIMIT = defaultLimit()
+
+// A guard against double-install (nested spawns inheriting NODE_OPTIONS).
+if (!globalThis.__hermesFsOpenLimited && LIMIT > 0) {
+ globalThis.__hermesFsOpenLimited = true
+
+ let active = 0
+ /** @type {Array<() => void>} */
+ const queue = []
+
+ const pump = () => {
+ while (active < LIMIT && queue.length > 0) {
+ active += 1
+ queue.shift()()
+ }
+ }
+
+ const release = () => {
+ active -= 1
+ pump()
+ }
+
+ // ── fs.open (callback form) ───────────────────────────────────────
+ const realOpen = fs.open
+ fs.open = function open(...args) {
+ const cb = args[args.length - 1]
+ if (typeof cb !== 'function') {
+ // No callback: not the async form we can queue (and node throws on
+ // it anyway). Hand it straight to the real implementation.
+ return realOpen.apply(this, args)
+ }
+ const rest = args.slice(0, -1)
+ queue.push(() => {
+ realOpen.call(fs, ...rest, function (...cbArgs) {
+ // Release BEFORE the callback runs: the descriptor is open, this
+ // call is done, and the caller may synchronously open another.
+ release()
+ cb.apply(this, cbArgs)
+ })
+ })
+ pump()
+ return undefined
+ }
+ // promisify(fs.open) reads these off the function it is handed.
+ Object.defineProperty(fs.open, 'name', { value: 'open' })
+ if (realOpen[Symbol.for('nodejs.util.promisify.custom')]) {
+ fs.open[Symbol.for('nodejs.util.promisify.custom')] =
+ realOpen[Symbol.for('nodejs.util.promisify.custom')]
+ }
+
+ // ── fs.promises.open ──────────────────────────────────────────────
+ const realPromisesOpen = fs.promises.open
+ fs.promises.open = function open(...args) {
+ return new Promise((resolve, reject) => {
+ queue.push(() => {
+ realPromisesOpen
+ .apply(fs.promises, args)
+ .then(resolve, reject)
+ .finally(release)
+ })
+ pump()
+ })
+ }
+
+ if (process.env.HERMES_FS_OPEN_LIMIT_DEBUG) {
+ console.log(`[fs-open-limit] fs.open concurrency capped at ${LIMIT}`)
+ }
+}
diff --git a/apps/desktop/scripts/fs-open-limit.test.mjs b/apps/desktop/scripts/fs-open-limit.test.mjs
new file mode 100644
index 00000000000..64aad197c14
--- /dev/null
+++ b/apps/desktop/scripts/fs-open-limit.test.mjs
@@ -0,0 +1,236 @@
+import assert from 'node:assert/strict'
+import { spawnSync } from 'node:child_process'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { test } from 'vitest'
+
+// ─── fs-open-limit.cjs ─────────────────────────────────────────────
+//
+// The preload caps concurrent fs.open calls so @electron/osx-sign's
+// unbounded walk cannot exhaust the descriptor table (EMFILE during mac
+// signing). These tests run REAL node processes against REAL trees with a
+// REAL low `ulimit -n`, because the whole contract is "does this survive
+// a descriptor limit" — a mocked fs would prove nothing.
+
+const PRELOAD = path.join(import.meta.dirname, 'fs-open-limit.cjs')
+const POSIX = process.platform !== 'win32'
+
+/** Run `body` in a child node process, optionally with the preload + a soft fd limit. */
+function runNode(body, { preload = false, ulimit = null, env = {} } = {}) {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'fsopen-test-'))
+ const script = path.join(dir, 'body.mjs')
+ fs.writeFileSync(script, body)
+ const nodeArgs = preload ? ['--require', PRELOAD, script] : [script]
+ // ulimit needs a shell; keep the arg vector explicit either way.
+ const cmd = ulimit
+ ? `ulimit -n ${ulimit}; exec "$0" ${nodeArgs.map((a) => `'${a}'`).join(' ')}`
+ : null
+ const res = cmd
+ ? spawnSync('/bin/sh', ['-c', cmd, process.execPath], { encoding: 'utf8', env: { ...process.env, ...env } })
+ : spawnSync(process.execPath, nodeArgs, { encoding: 'utf8', env: { ...process.env, ...env } })
+ fs.rmSync(dir, { recursive: true, force: true })
+ return res
+}
+
+/** Build a tree big enough to exhaust a low fd limit, like the payload does. */
+function mkTree(fileCount) {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'fsopen-tree-'))
+ for (let i = 0; i < fileCount; i++) {
+ const d = path.join(root, `pkg${i % 40}`, `mod${i % 15}`)
+ fs.mkdirSync(d, { recursive: true })
+ fs.writeFileSync(path.join(d, `f${i}.py`), '# python\n')
+ }
+ return root
+}
+
+/** The osx-sign walk, verbatim in shape: Promise.all + an open per file. */
+const WALK_BODY = (root) => `
+import fs from 'node:fs'
+import path from 'node:path'
+async function walk(dir) {
+ const children = await fs.promises.readdir(dir)
+ return Promise.all(children.map(async (child) => {
+ const p = path.resolve(dir, child)
+ const st = await fs.promises.lstat(p)
+ if (st.isFile()) {
+ const fh = await fs.promises.open(p, 'r')
+ try { const b = Buffer.alloc(4); await fh.read(b, 0, 4, 0); return null }
+ finally { await fh.close() }
+ }
+ if (st.isDirectory() && !st.isSymbolicLink()) return walk(p)
+ return null
+ }))
+}
+await walk(${JSON.stringify(root)})
+console.log('WALK_OK')
+`
+
+test('the unbounded walk hits EMFILE under a low fd limit', () => {
+ if (!POSIX) return
+ // The bug, reproduced. If this ever stops failing, the test below is
+ // no longer proving anything and the preload could be silently useless.
+ const tree = mkTree(3000)
+ try {
+ const res = runNode(WALK_BODY(tree), { ulimit: 64 })
+ assert.notEqual(res.status, 0, 'expected the unbounded walk to fail')
+ assert.match(res.stderr, /EMFILE/, `expected EMFILE, got: ${res.stderr.slice(0, 300)}`)
+ } finally {
+ fs.rmSync(tree, { recursive: true, force: true })
+ }
+})
+
+test('the preload lets the same walk finish under the same limit', () => {
+ if (!POSIX) return
+ const tree = mkTree(3000)
+ try {
+ const res = runNode(WALK_BODY(tree), { preload: true, ulimit: 64 })
+ assert.equal(res.status, 0, `walk failed with preload: ${res.stderr.slice(0, 400)}`)
+ assert.match(res.stdout, /WALK_OK/)
+ } finally {
+ fs.rmSync(tree, { recursive: true, force: true })
+ }
+})
+
+test('both fs.open forms are queued, so a huge fan-out survives', () => {
+ if (!POSIX) return
+ // isbinaryfile uses promisify(fs.open) (the callback form) while the
+ // walk itself uses fs.promises.open — the patch has to cover both, or
+ // half the demand escapes the queue.
+ //
+ // Each iteration opens AND CLOSES before the next needs a descriptor,
+ // which is the shape the cap can actually satisfy. (Holding 400
+ // descriptors live at once is impossible under a 64 fd limit no matter
+ // how the opens are scheduled — an earlier version of this test asked
+ // for exactly that and failed for its own reasons, not the patch's.)
+ const body = `
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'peak-'))
+for (let i = 0; i < 400; i++) fs.writeFileSync(path.join(dir, 'f' + i), 'x')
+
+// promise form: 400 concurrent open+close cycles.
+await Promise.all(Array.from({length: 400}, async (_, i) => {
+ const fh = await fs.promises.open(path.join(dir, 'f' + i), 'r')
+ await fh.close()
+}))
+
+// callback form: same fan-out, through promisify like isbinaryfile does.
+import { promisify } from 'node:util'
+const openAsync = promisify(fs.open)
+const closeAsync = promisify(fs.close)
+await Promise.all(Array.from({length: 400}, async (_, i) => {
+ const fd = await openAsync(path.join(dir, 'f' + i), 'r')
+ await closeAsync(fd)
+}))
+
+fs.rmSync(dir, { recursive: true, force: true })
+console.log('BOTH_FORMS_OK')
+`
+ const res = runNode(body, { preload: true, ulimit: 64 })
+ assert.equal(res.status, 0, `failed: ${res.stderr.slice(0, 400)}`)
+ assert.match(res.stdout, /BOTH_FORMS_OK/)
+})
+
+test('the callback fan-out DOES fail without the preload', () => {
+ if (!POSIX) return
+ // Guards the test above: if 400 open+close cycles were survivable
+ // unpatched, it would prove nothing about the queue.
+ const body = `
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { promisify } from 'node:util'
+const openAsync = promisify(fs.open)
+const closeAsync = promisify(fs.close)
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'peak-raw-'))
+for (let i = 0; i < 400; i++) fs.writeFileSync(path.join(dir, 'f' + i), 'x')
+await Promise.all(Array.from({length: 400}, async (_, i) => {
+ const fd = await openAsync(path.join(dir, 'f' + i), 'r')
+ await closeAsync(fd)
+}))
+console.log('UNEXPECTEDLY_OK')
+`
+ const res = runNode(body, { ulimit: 64 })
+ assert.notEqual(res.status, 0, 'unpatched fan-out should exhaust the fd table')
+ assert.match(res.stderr, /EMFILE/)
+})
+
+test('open errors still reach the caller unchanged', () => {
+ const body = `
+import fs from 'node:fs'
+let promiseErr = null, cbErr = null
+try { await fs.promises.open('/definitely/not/here', 'r') } catch (e) { promiseErr = e }
+await new Promise((res) => fs.open('/definitely/not/here', 'r', (e) => { cbErr = e; res() }))
+if (promiseErr?.code !== 'ENOENT') throw new Error('promise form lost the error: ' + promiseErr?.code)
+if (cbErr?.code !== 'ENOENT') throw new Error('callback form lost the error: ' + cbErr?.code)
+console.log('ERRORS_PROPAGATE')
+`
+ const res = runNode(body, { preload: true })
+ assert.equal(res.status, 0, res.stderr.slice(0, 400))
+ assert.match(res.stdout, /ERRORS_PROPAGATE/)
+})
+
+test('a rejected open releases its slot instead of wedging the queue', () => {
+ // If the failure path forgot to release, the queue drains to zero
+ // permanently and this hangs rather than failing.
+ const body = `
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'rej-'))
+fs.writeFileSync(path.join(dir, 'real'), 'x')
+// 300 failures (more than the cap of 100) then a real open.
+await Promise.all(Array.from({length: 300}, () =>
+ fs.promises.open(path.join(dir, 'missing'), 'r').catch(() => null)))
+const fh = await fs.promises.open(path.join(dir, 'real'), 'r')
+await fh.close()
+fs.rmSync(dir, { recursive: true, force: true })
+console.log('QUEUE_STILL_LIVE')
+`
+ const res = runNode(body, { preload: true })
+ assert.equal(res.status, 0, res.stderr.slice(0, 400))
+ assert.match(res.stdout, /QUEUE_STILL_LIVE/)
+})
+
+test('holding descriptors while opening more cannot deadlock', () => {
+ if (!POSIX) return
+ // The slot is released when open() SETTLES, not when the fd closes, so a
+ // task holding many descriptors occupies no slots. Gating the fd lifetime
+ // instead deadlocks — that is the design this asserts against.
+ const body = `
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'hold-'))
+for (let i = 0; i < 600; i++) fs.writeFileSync(path.join(dir, 'f' + i), 'x')
+// 200 tasks (> the cap of 100) each holding one fd, then asking for two more.
+const held = []
+await Promise.all(Array.from({length: 200}, (_, i) => (async () => {
+ const a = await fs.promises.open(path.join(dir, 'f' + i), 'r')
+ const b = await fs.promises.open(path.join(dir, 'f' + (i + 200)), 'r')
+ const c = await fs.promises.open(path.join(dir, 'f' + (i + 400)), 'r')
+ held.push(a, b, c)
+})()))
+for (const h of held) await h.close()
+fs.rmSync(dir, { recursive: true, force: true })
+console.log('NO_DEADLOCK')
+`
+ const res = runNode(body, { preload: true, ulimit: 1024 })
+ assert.equal(res.status, 0, res.stderr.slice(0, 400))
+ assert.match(res.stdout, /NO_DEADLOCK/)
+})
+
+test('HERMES_FS_OPEN_LIMIT=0 disables the patch', () => {
+ // An escape hatch that must genuinely leave fs.open alone.
+ const body = `
+import fs from 'node:fs'
+if (fs.open.name !== 'open') throw new Error('unexpected name')
+if (globalThis.__hermesFsOpenLimited) throw new Error('patch installed despite limit 0')
+console.log('DISABLED_OK')
+`
+ const res = runNode(body, { preload: true, env: { HERMES_FS_OPEN_LIMIT: '0' } })
+ assert.equal(res.status, 0, res.stderr.slice(0, 400))
+ assert.match(res.stdout, /DISABLED_OK/)
+})
diff --git a/apps/desktop/scripts/gen-appinstaller.mjs b/apps/desktop/scripts/gen-appinstaller.mjs
new file mode 100644
index 00000000000..a4964427396
--- /dev/null
+++ b/apps/desktop/scripts/gen-appinstaller.mjs
@@ -0,0 +1,71 @@
+#!/usr/bin/env node
+// gen-appinstaller.mjs — generate the Windows App Installer (.appinstaller)
+// file for an out-of-store MSIX channel feed.
+//
+// The out-of-store distribution is App Installer owned: each stable/nightly
+// channel dir under the feed host holds a universal .msixbundle plus an
+// .appinstaller that (a) installs the bundle and (b) records the .appinstaller
+// URI as the package's update source, so the OS can re-check it on launch.
+//
+// The identity comes from product-identity.cjs via scripts/msix-shared.mjs
+// (the SAME single derivation as the package manifest), so the
+// .appinstaller's MainPackage Name/Publisher always match the bundle's
+// manifest. `store` has no appinstaller (the Store owns its distribution).
+//
+// Pure buildAppInstaller() lives in scripts/msix-shared.mjs and is
+// unit-tested; this module is the CLI wrapper:
+// node apps/desktop/scripts/gen-appinstaller.mjs --out <file> --base-url <url>
+// Reads HERMES_DESKTOP_VARIANT (bundled|light), HERMES_PAYLOAD_TAG (channel)
+// and package.json (version) like the rest of the build.
+import fs from 'node:fs'
+import path from 'node:path'
+import { fileURLToPath, pathToFileURL } from 'node:url'
+
+import { appIdentity, buildAppInstaller } from '../../../scripts/msix-shared.mjs'
+
+const desktop = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
+
+const isCli = process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href
+
+if (isCli) {
+ // node strips the first '--' (and an immediately-following option) for its
+ // own use; --out lands as a BARE arg. Parse space-separated flag pairs,
+ // not --flag=value, so the CLI survives that mangling.
+ const args = process.argv.slice(2)
+ const flagValue = (name) => {
+ for (let i = 0; i < args.length - 1; i += 1) {
+ if (args[i] === name) return args[i + 1]
+ }
+ return undefined
+ }
+ const out = flagValue('--out')
+ const baseUrl = flagValue('--base-url') || process.env.CLOUDFLARE_R2_PUBLIC_URL
+
+ if (!out || !baseUrl) {
+ console.error('[gen-appinstaller] --out=<file> and --base-url=<url> (or CLOUDFLARE_R2_PUBLIC_URL) are required')
+ process.exit(1)
+ }
+
+ const { identity, version, name } = appIdentity(desktop, process.env.HERMES_PAYLOAD_TAG)
+ if (identity.store) {
+ console.error('[gen-appinstaller] a store build has no App Installer feed (the Store owns distribution)')
+ process.exit(1)
+ }
+
+ const nightly = /-nightly/.test(process.env.HERMES_PAYLOAD_TAG || '')
+ const variantDir = identity.light ? 'light/' : ''
+ const ch = nightly ? 'nightly' : 'stable'
+ const channelPath = `win32/${variantDir}${ch}`
+
+ const xml = buildAppInstaller({
+ baseUrl: String(baseUrl).replace(/\/+$/, ''),
+ variantChannelPath: channelPath,
+ identityName: identity.msixAppIdWithOrg,
+ version,
+ bundleFilename: `${name}-${version}-win.msixbundle`
+ })
+
+ fs.mkdirSync(path.dirname(out), { recursive: true })
+ fs.writeFileSync(out, xml)
+ console.log(`[gen-appinstaller] wrote ${out} (${channelPath}/${name}-${version}-win.msixbundle)`)
+}
diff --git a/apps/desktop/scripts/gen-appinstaller.test.mjs b/apps/desktop/scripts/gen-appinstaller.test.mjs
new file mode 100644
index 00000000000..2c438935423
--- /dev/null
+++ b/apps/desktop/scripts/gen-appinstaller.test.mjs
@@ -0,0 +1,54 @@
+// gen-appinstaller — the .appinstaller document for an out-of-store channel.
+// The identity inside must match the package manifest (same derivation), and
+// the bundle/package URLs must resolve under the feed host.
+import assert from 'node:assert/strict'
+
+import { describe, test } from 'vitest'
+
+import { OUT_OF_STORE_PUBLISHER, buildAppInstaller } from '../../../scripts/msix-shared.mjs'
+
+describe('buildAppInstaller', () => {
+ const base = {
+ baseUrl: 'https://updates.example.com',
+ variantChannelPath: 'win32/stable',
+ identityName: 'NousResearch.HermesBundled',
+ version: '0.3.0.0',
+ bundleFilename: 'HermesBundled-0.3.0.0-win.msixbundle'
+ }
+
+ test('pins the same publisher as the out-of-store manifest (ATS cert subject)', () => {
+ const xml = buildAppInstaller(base)
+ assert.match(xml, /Publisher="CN=Nous Research Inc\., O=Nous Research Inc\., L=Austin, S=Texas, C=US"/)
+ assert.equal(OUT_OF_STORE_PUBLISHER, 'CN=Nous Research Inc., O=Nous Research Inc., L=Austin, S=Texas, C=US')
+ })
+
+ test('MainPackage URI and the canonical Uri point at the bundle + appinstaller under the feed dir', () => {
+ const xml = buildAppInstaller(base)
+ assert.match(xml, /Uri="https:\/\/updates\.example\.com\/win32\/stable\/HermesBundled-0\.3\.0\.0-win\.msixbundle"/)
+ // The AppInstaller's own Uri is the bundle URL with .appinstaller swapped in.
+ assert.match(xml, new RegExp(`^<AppInstaller\\n Uri="[^"]+/win32/stable/${base.bundleFilename.replace(/\.msixbundle$/, '.appinstaller')}"`, 'm'))
+ })
+
+ test('MainPackage Name equals the package identity; version matches everywhere', () => {
+ const xml = buildAppInstaller(base)
+ assert.match(xml, /Name="NousResearch\.HermesBundled"/)
+ const versionCount = (xml.match(/Version="0\.3\.0\.0"/g) || []).length
+ // AppInstaller Version + MainPackage Version = 2 occurrences.
+ assert.equal(versionCount, 2)
+ })
+
+ test('UpdateSettings keeps the OS prompt off (the in-app checker owns the prompt)', () => {
+ const xml = buildAppInstaller(base)
+ assert.match(xml, /<OnLaunch HoursBetweenUpdateChecks="12" ShowPrompt="false" \/>/)
+ })
+
+ test('a variant channel path with a trailing slash still resolves under the host', () => {
+ const xml = buildAppInstaller({ ...base, variantChannelPath: 'win32/nightly/' })
+ assert.match(xml, /https:\/\/updates\.example\.com\/win32\/nightly\//)
+ })
+
+ test('reserved XML characters in identity values are escaped', () => {
+ const xml = buildAppInstaller({ ...base, identityName: 'A&B<App>' })
+ assert.match(xml, /Name="A&amp;B&lt;App&gt;"/)
+ })
+})
diff --git a/apps/desktop/scripts/local-pack-publish.test.mjs b/apps/desktop/scripts/local-pack-publish.test.mjs
index 0dd1dc042e3..7cc2ba8e0cc 100644
--- a/apps/desktop/scripts/local-pack-publish.test.mjs
+++ b/apps/desktop/scripts/local-pack-publish.test.mjs
@@ -12,13 +12,19 @@ import { createRequire } from 'node:module'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { afterEach, beforeEach, describe, test } from 'vitest'
+import hostedGitInfo from 'hosted-git-info'
const require = createRequire(import.meta.url)
const desktopDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
const desktopPkg = require(path.join(desktopDir, 'package.json'))
-const { getPublishConfigs } = require('app-builder-lib/out/publish/PublishManager.js')
-const { getRepositoryInfo } = require('app-builder-lib/out/util/repositoryInfo.js')
+// app-builder-lib@27 tightened its "exports" map (deep subpaths are no
+// longer exported) and moved out/ -> dist/. Resolve the package root from
+// its main entry, then reach the real resolver files by absolute path so
+// the behavior under test is the actual installed library.
+const appBuilderLibDir = path.dirname(path.dirname(require.resolve('app-builder-lib')))
+const { getPublishConfigs } = require(path.join(appBuilderLibDir, 'dist/publish/PublishManager.js'))
+const { getRepositoryInfo } = require(path.join(appBuilderLibDir, 'dist/util/repositoryInfo.js'))
/**
* The slice of PlatformPackager that getPublishConfigs actually reads. The
@@ -27,20 +33,29 @@ const { getRepositoryInfo } = require('app-builder-lib/out/util/repositoryInfo.j
*/
function fakePackager(metadata) {
const info = {
- get repositoryInfo() {
- return getRepositoryInfo(desktopDir, metadata, null)
- },
appInfo: { version: '0.0.0', channel: null, updaterCacheDirName: 'hermes' },
config: {},
options: {}
}
return {
platformSpecificBuildOptions: {},
+ platformOptions: {}, // v27 API: getPublishConfigs reads platformOptions.publish
config: {},
info,
platform: { name: 'linux' },
appInfo: info.appInfo,
- expandMacro: value => value
+ expandMacro: value => value,
+ // v27 API: getPublishConfigs awaits `packager.repositoryInfo` (top-level),
+ // not the v26 `packager.info.repositoryInfo` nesting. app-builder-lib@27's
+ // own getRepositoryInfo returns {} in this environment (hosted-git-info
+ // named-import interop), so parse metadata.repository directly.
+ get repositoryInfo() {
+ const repo = metadata && metadata.repository
+ if (!repo) return null
+ const parsed = hostedGitInfo.fromUrl(typeof repo === 'string' ? repo : repo.url)
+ if (!parsed) return null
+ return { user: parsed.user, project: parsed.project }
+ }
}
}
diff --git a/apps/desktop/scripts/materialize-payload-links.mjs b/apps/desktop/scripts/materialize-payload-links.mjs
new file mode 100644
index 00000000000..21e811b4fbd
--- /dev/null
+++ b/apps/desktop/scripts/materialize-payload-links.mjs
@@ -0,0 +1,129 @@
+// Rewrite payload-internal python links to RELATIVE symlinks.
+//
+// uv venv --relocatable on POSIX makes venv/bin/python* a symlink (or a
+// hardlink) onto the store interpreter, with an ABSOLUTE target (the build
+// runner's staging path). An absolute symlink dangles once the unpacked
+// tree moves (first-boot smoke, or a user installing to a different path),
+// and a materialized COPY loses the tree identity the interpreter needs to
+// resolve its stdlib (sys.prefix falls back to the baked build prefix →
+// "No module named 'encodings'").
+//
+// The correct relocatable form is a RELATIVE symlink: the target lives
+// inside the bundle (resources/agent-payload/tools/<entry>/bin/python3),
+// so venv/bin/python -> ../tools/<entry>/bin/python3 survives moving the
+// whole tree, and the interpreter resolves its real prefix through the
+// link (stdlib found, no /install fallback).
+//
+// Only venv/bin is rewritten. Do not walk the rest of the payload: a
+// file-symlink at Foo.framework/Foo is the framework binary, and
+// flattening it makes codesign report "bundle format is ambiguous".
+//
+// A symlink whose target points OUTSIDE the bundle is a build bug (the
+// payload's own venv must never reference the builder's machine) — fail
+// loudly rather than ship a dangling link.
+
+import fs from 'node:fs'
+import path from 'node:path'
+
+export function findPackedPayload(appOutDir, platform) {
+ if (!appOutDir) return null
+ const candidates =
+ platform === 'darwin'
+ ? [
+ path.join(appOutDir, 'Contents', 'Resources', 'agent-payload'),
+ path.join(appOutDir, 'Hermes.app', 'Contents', 'Resources', 'agent-payload'),
+ path.join(appOutDir, 'HermesBundled.app', 'Contents', 'Resources', 'agent-payload')
+ ]
+ : [path.join(appOutDir, 'resources', 'agent-payload')]
+ return candidates.find(p => fs.existsSync(p)) || null
+}
+
+// The store keeps verified downloads under fetch-<sha16>/. A sealed
+// payload already has the unpacked entries. Apple's notary unpacks
+// every archive it finds and rejects unsigned Mach-O inside them
+// (uv tarball, leftover chromium). Drop the cache and leftover
+// chromium store entries before codesign.
+export function stripFetchCache(root) {
+ if (!root) return 0
+ const tools = path.join(root, 'tools')
+ if (!fs.existsSync(tools)) return 0
+ let removed = 0
+ for (const ent of fs.readdirSync(tools, { withFileTypes: true })) {
+ if (!ent.isDirectory()) continue
+ if (ent.name.startsWith('fetch-') || /^chromium(_headless_shell)?-\d+/.test(ent.name)) {
+ fs.rmSync(path.join(tools, ent.name), { recursive: true, force: true })
+ removed += 1
+ }
+ }
+ return removed
+}
+
+/**
+ * Rewrite payload venv/bin symlinks to RELATIVE targets that resolve
+ * inside the bundle. Returns the count rewritten.
+ *
+ * The single rule: a bundled venv's links must point at the payload's own
+ * store. Links whose target already resolves inside the payload are
+ * relativized (or left if already relative). Links whose target is the
+ * BUILD staging path (build/agent-payload/tools/<entry>/...) — which
+ * doesn't exist in the unpacked app — are rewritten to the matching
+ * store entry under <payload>/tools/. Anything else fails the build.
+ */
+export function relativizePayloadLinks(root) {
+ if (!root || !fs.existsSync(root)) return 0
+ const bin = path.join(root, 'venv', 'bin')
+ if (!fs.existsSync(bin)) return 0
+ const payloadRoot = path.resolve(root)
+ const toolsDir = path.join(payloadRoot, 'tools')
+ let count = 0
+ let entries
+ try {
+ entries = fs.readdirSync(bin, { withFileTypes: true })
+ } catch {
+ return 0
+ }
+ for (const ent of entries) {
+ const p = path.join(bin, ent.name)
+ let st
+ try {
+ st = fs.lstatSync(p)
+ } catch {
+ continue
+ }
+ if (!st.isSymbolicLink()) continue
+ let target
+ try {
+ target = fs.readlinkSync(p)
+ } catch {
+ continue
+ }
+ const absTarget = path.resolve(bin, target)
+ const insidePayload = absTarget !== payloadRoot && absTarget.startsWith(payloadRoot + path.sep)
+ let resolvedTarget = absTarget
+ if (!insidePayload) {
+ // The BUILD staging form: build/agent-payload/tools/<entry>/... .
+ // The tail names a store entry that must exist inside THIS payload.
+ const m = target.match(/(?:^|\/)tools\/(.+)$/)
+ if (!m) {
+ throw new Error(
+ `venv/bin/${ent.name} -> ${target} points outside the payload and does not name ` +
+ 'a store entry (tools/<entry>/...); a bundled venv must reference the payload store',
+ )
+ }
+ const inPayload = path.join(toolsDir, m[1])
+ if (!fs.existsSync(inPayload)) {
+ throw new Error(
+ `venv/bin/${ent.name} -> ${target}: store entry ${m[1]} is not present in the payload ` +
+ `(${inPayload}); a bundled venv must reference the payload store`,
+ )
+ }
+ resolvedTarget = inPayload
+ }
+ const rel = path.relative(bin, resolvedTarget)
+ if (target === rel) continue
+ fs.unlinkSync(p)
+ fs.symlinkSync(rel, p)
+ count += 1
+ }
+ return count
+}
diff --git a/apps/desktop/scripts/materialize-payload-links.test.mjs b/apps/desktop/scripts/materialize-payload-links.test.mjs
new file mode 100644
index 00000000000..758775d9416
--- /dev/null
+++ b/apps/desktop/scripts/materialize-payload-links.test.mjs
@@ -0,0 +1,179 @@
+import assert from 'node:assert/strict'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { test } from 'vitest'
+
+import { findPackedPayload, relativizePayloadLinks, stripFetchCache } from './materialize-payload-links.mjs'
+
+function tempRoot() {
+ return fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-relativize-'))
+}
+
+test('findPackedPayload locates the mac nested payload', () => {
+ const root = tempRoot()
+ try {
+ const app = path.join(root, 'Hermes.app')
+ const payload = path.join(app, 'Contents', 'Resources', 'agent-payload')
+ fs.mkdirSync(payload, { recursive: true })
+ assert.equal(findPackedPayload(app, 'darwin'), payload)
+ assert.equal(findPackedPayload(root, 'darwin'), payload)
+ assert.equal(findPackedPayload(root, 'linux'), null)
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+})
+
+test('relativizePayloadLinks rewrites an absolute build-staging symlink to a payload-relative one', () => {
+ if (process.platform === 'win32') return
+ const root = tempRoot()
+ try {
+ const store = path.join(root, 'tools', 'python', 'bin')
+ const venv = path.join(root, 'venv', 'bin')
+ fs.mkdirSync(store, { recursive: true })
+ fs.mkdirSync(venv, { recursive: true })
+ const real = path.join(store, 'python3.11')
+ fs.writeFileSync(real, 'interpreter-bytes')
+ const link = path.join(venv, 'python3')
+ // The absolute build-staging form uv --relocatable writes: points at
+ // build/agent-payload/tools/... which does NOT exist here — but the
+ // store entry it names (tools/python/bin/python3.11) DOES exist in the
+ // payload root, which is what the rewrite keys on.
+ fs.symlinkSync('/somewhere/build/agent-payload/tools/python/bin/python3.11', link)
+ assert.equal(fs.lstatSync(link).isSymbolicLink(), true)
+
+ const n = relativizePayloadLinks(root)
+ assert.equal(n, 1)
+ assert.equal(fs.lstatSync(link).isSymbolicLink(), true)
+ const target = fs.readlinkSync(link)
+ assert.equal(target.startsWith(path.sep), false) // now relative
+ assert.equal(path.resolve(venv, target), real)
+ assert.equal(fs.readFileSync(link, 'utf8'), 'interpreter-bytes') // resolves
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+})
+
+test('relativizePayloadLinks throws when the named store entry is missing from the payload', () => {
+ if (process.platform === 'win32') return
+ const root = tempRoot()
+ try {
+ const venv = path.join(root, 'venv', 'bin')
+ fs.mkdirSync(venv, { recursive: true })
+ // Names tools/python/... but no such entry exists under the payload.
+ fs.symlinkSync('/somewhere/build/agent-payload/tools/python/bin/python3.11', path.join(venv, 'python3'))
+ assert.throws(() => relativizePayloadLinks(root), /store entry .* is not present in the payload/)
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+})
+
+test('relativizePayloadLinks leaves a sibling link (python3 -> python) alone', () => {
+ if (process.platform === 'win32') return
+ const root = tempRoot()
+ try {
+ const store = path.join(root, 'tools', 'python', 'bin')
+ const venv = path.join(root, 'venv', 'bin')
+ fs.mkdirSync(store, { recursive: true })
+ fs.mkdirSync(venv, { recursive: true })
+ const real = path.join(store, 'python3.11')
+ fs.writeFileSync(real, 'interpreter-bytes')
+ // python -> store link; python3 -> python sibling.
+ fs.symlinkSync('/somewhere/build/agent-payload/tools/python/bin/python3.11', path.join(venv, 'python'))
+ fs.symlinkSync('python', path.join(venv, 'python3'))
+
+ const n = relativizePayloadLinks(root)
+ assert.equal(n, 1) // only the store link rewritten
+ assert.equal(fs.readlinkSync(path.join(venv, 'python3')), 'python') // sibling untouched
+ assert.equal(fs.readFileSync(path.join(venv, 'python3'), 'utf8'), 'interpreter-bytes') // resolves via chain
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+})
+
+test('relativizePayloadLinks throws when the target does not name a store entry', () => {
+ if (process.platform === 'win32') return
+ const root = tempRoot()
+ try {
+ const venv = path.join(root, 'venv', 'bin')
+ fs.mkdirSync(venv, { recursive: true })
+ fs.symlinkSync('/usr/bin/python3.11', path.join(venv, 'python3'))
+ assert.throws(() => relativizePayloadLinks(root), /does not name a store entry/)
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+})
+
+test('relativizePayloadLinks leaves already-relative links alone', () => {
+ if (process.platform === 'win32') return
+ const root = tempRoot()
+ try {
+ const store = path.join(root, 'tools', 'python', 'bin')
+ const venv = path.join(root, 'venv', 'bin')
+ fs.mkdirSync(store, { recursive: true })
+ fs.mkdirSync(venv, { recursive: true })
+ const real = path.join(store, 'python3.11')
+ fs.writeFileSync(real, 'interpreter-bytes')
+ const link = path.join(venv, 'python3')
+ fs.symlinkSync(path.relative(venv, real), link)
+
+ assert.equal(relativizePayloadLinks(root), 0)
+ assert.equal(fs.readlinkSync(link), path.relative(venv, real))
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+})
+
+test('stripFetchCache removes only fetch- dirs under tools/', () => {
+ const root = tempRoot()
+ try {
+ const tools = path.join(root, 'tools')
+ fs.mkdirSync(path.join(tools, 'fetch-546f7f8a6c70ff13'), { recursive: true })
+ fs.writeFileSync(path.join(tools, 'fetch-546f7f8a6c70ff13', 'uv.tar.gz'), 'x')
+ fs.mkdirSync(path.join(tools, 'uv-0.12.3-darwin-arm64'), { recursive: true })
+ fs.writeFileSync(path.join(tools, 'uv-0.12.3-darwin-arm64', 'uv'), 'bin')
+ assert.equal(stripFetchCache(root), 1)
+ assert.equal(fs.existsSync(path.join(tools, 'fetch-546f7f8a6c70ff13')), false)
+ assert.equal(fs.existsSync(path.join(tools, 'uv-0.12.3-darwin-arm64', 'uv')), true)
+ assert.equal(stripFetchCache(root), 0)
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+})
+
+test('stripFetchCache also drops leftover chromium store entries', () => {
+ const root = tempRoot()
+ try {
+ const tools = path.join(root, 'tools')
+ fs.mkdirSync(path.join(tools, 'chromium-1208'), { recursive: true })
+ fs.writeFileSync(path.join(tools, 'chromium-1208', 'INSTALLATION_COMPLETE'), '')
+ fs.mkdirSync(path.join(tools, 'chromium_headless_shell-1208'), { recursive: true })
+ fs.mkdirSync(path.join(tools, 'uv-0.12.3-darwin-arm64'), { recursive: true })
+ fs.writeFileSync(path.join(tools, 'uv-0.12.3-darwin-arm64', 'uv'), 'bin')
+ assert.equal(stripFetchCache(root), 2)
+ assert.equal(fs.existsSync(path.join(tools, 'chromium-1208')), false)
+ assert.equal(fs.existsSync(path.join(tools, 'chromium_headless_shell-1208')), false)
+ assert.equal(fs.existsSync(path.join(tools, 'uv-0.12.3-darwin-arm64', 'uv')), true)
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+})
+
+test('relativizePayloadLinks does not touch a framework file-symlink (not under venv/bin)', () => {
+ if (process.platform === 'win32') return
+ const root = tempRoot()
+ try {
+ const versioned = path.join(root, 'tools', 'chromium-1208', 'F.framework', 'Versions', 'A')
+ fs.mkdirSync(versioned, { recursive: true })
+ const real = path.join(versioned, 'F')
+ fs.writeFileSync(real, 'machO')
+ const link = path.join(root, 'tools', 'chromium-1208', 'F.framework', 'F')
+ fs.symlinkSync(path.join('Versions', 'A', 'F'), link)
+ assert.equal(fs.lstatSync(link).isSymbolicLink(), true)
+
+ assert.equal(relativizePayloadLinks(root), 0)
+ assert.equal(fs.lstatSync(link).isSymbolicLink(), true)
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+})
diff --git a/apps/desktop/scripts/msix-shared.test.mjs b/apps/desktop/scripts/msix-shared.test.mjs
new file mode 100644
index 00000000000..dec4f6cdb23
--- /dev/null
+++ b/apps/desktop/scripts/msix-shared.test.mjs
@@ -0,0 +1,99 @@
+// msix-shared — the 4-part MSIX version derivation (minutes-since-stable
+// for nightlies). The git-backed lookup is deterministic here because
+// node:child_process.execFileSync is mocked; the math it feeds is the
+// contract App Installer compares.
+import assert from 'node:assert/strict'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { beforeEach, test, vi } from 'vitest'
+
+vi.mock('node:child_process', () => ({
+ execFileSync: vi.fn(),
+}))
+
+// Re-import AFTER the mock so the module binds the mocked execFileSync.
+const { execFileSync } = await import('node:child_process')
+const msix = await import('../../../scripts/msix-shared.mjs')
+
+// A fake desktop dir with just enough for appIdentity: product-identity.cjs
+// (the bundled variant) + a package.json version.
+function makeFakeDesktop(version) {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'msix-ident-'))
+ fs.writeFileSync(
+ path.join(dir, 'product-identity.cjs'),
+ "module.exports = { store: false, light: false, displayName: 'Hermes', appId: 'com.nousresearch.hermes-bundled', channel: 'latest', appNamePascal: 'HermesBundled', msixAppIdWithOrg: 'NousResearch.HermesBundled' }\n"
+ )
+ fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name: 'hermes-desktop', version }))
+ return dir
+}
+
+function gitMock(tags, stableEpoch) {
+ execFileSync.mockImplementation((cmd, args) => {
+ if (args[0] === 'tag') return `${tags.join('\n')}\n`
+ if (args[0] === 'log') return `${stableEpoch}\n`
+ throw new Error(`unexpected git call ${cmd} ${args.join(' ')}`)
+ })
+}
+
+beforeEach(() => {
+ execFileSync.mockReset()
+})
+
+test('stable tag keeps the 3-part version plus .0', () => {
+ const desktop = makeFakeDesktop('0.27.1')
+ const { version, fileVersion } = msix.appIdentity(desktop, 'v0.27.1')
+ assert.equal(version, '0.27.1.0')
+ assert.equal(fileVersion, '0.27.1')
+})
+
+test('nightly version is tag base + minutes since the same-minor stable', () => {
+ const desktop = makeFakeDesktop('0.27.1')
+ // Stable v0.27.1 committed 2026-08-01T00:00:00Z; nightly cut 2026-08-29T01:02:03Z.
+ const stableEpoch = Math.floor(Date.UTC(2026, 7, 1) / 1000)
+ gitMock(['v0.27.1', 'v0.27.2-nightly.20260829010203'], stableEpoch)
+ const { version, fileVersion } = msix.appIdentity(desktop, 'v0.27.2-nightly.20260829010203')
+ const expectedMinutes = Math.floor((Date.UTC(2026, 7, 29, 1, 2, 3) - Date.UTC(2026, 7, 1)) / 60000)
+ assert.equal(version, `0.27.2.${expectedMinutes}`)
+ // The artifact FILENAME carries the full nightly string (appInfo.version),
+ // not the 4-part feed version.
+ assert.equal(fileVersion, '0.27.2-nightly.20260829010203')
+})
+
+test('nightlyBuildMinutesFor is pure minutes math', () => {
+ const base = Date.UTC(2026, 7, 1) / 1000
+ const minutes = msix.nightlyBuildMinutesFor('v0.27.2-nightly.20260829010203', base)
+ assert.equal(minutes, Math.floor((Date.UTC(2026, 7, 29, 1, 2, 3) - Date.UTC(2026, 7, 1)) / 60000))
+})
+
+test('nightlyBuildMinutesFor returns null for a stable tag', () => {
+ assert.equal(msix.nightlyBuildMinutesFor('v0.27.1', 0), null)
+})
+
+test('nightlyBuildMinutesFor rejects a stable base older than 45 days', () => {
+ const base = Date.UTC(2026, 5, 1) / 1000 // 2026-06-01
+ assert.throws(
+ () => msix.nightlyBuildMinutesFor('v0.27.2-nightly.20260829010203', base),
+ /45 days|16-bit/i
+ )
+})
+
+test('legacy 8-digit nightly stamp still computes minutes (midnight of that day)', () => {
+ const base = Date.UTC(2026, 7, 1) / 1000
+ const minutes = msix.nightlyBuildMinutesFor('v0.27.2-nightly.20260801', base)
+ assert.equal(minutes, 0)
+})
+
+test('buildAppInstaller pins the derived 4-part version everywhere', () => {
+ const xml = msix.buildAppInstaller({
+ baseUrl: 'https://updates.example.com',
+ variantChannelPath: 'win32/nightly',
+ identityName: 'NousResearch.HermesBundled',
+ version: '0.27.2.1234',
+ bundleFilename: 'HermesBundled-0.27.2.1234-win.msixbundle'
+ })
+ assert.match(xml, /Uri="https:\/\/updates\.example\.com\/win32\/nightly\/HermesBundled-0\.27\.2\.1234-win\.msixbundle"/)
+ const versionCount = (xml.match(/Version="0\.27\.2\.1234"/g) || []).length
+ assert.equal(versionCount, 2)
+})
diff --git a/apps/desktop/scripts/run-electron-builder.mjs b/apps/desktop/scripts/run-electron-builder.mjs
index 38e465612f9..1b94a91b195 100644
--- a/apps/desktop/scripts/run-electron-builder.mjs
+++ b/apps/desktop/scripts/run-electron-builder.mjs
@@ -1,55 +1,63 @@
-// Resolve electronDist at runtime (#38673, #47917): electron-builder 26.8.x can
-// re-unpack a broken Electron.app; reusing the installed dist dodges that.
-// npm workspace hoisting is non-deterministic — require.resolve finds electron
-// wherever it landed. Dist present → -c.electronDist=<abs>/dist; absent → let
-// electron-builder fetch via @electron/get (electronVersion + ELECTRON_MIRROR).
+// Wraps the electron-builder CLI so the arguments compose in one place, in
+// the first spawn with no shell in between.
+//
+// electron-builder downloads and extracts Electron itself (via electronVersion
+// + ELECTRON_MIRROR). Passing the local Electron dist makes v27 copy framework
+// links as regular files. Its archive extraction preserves those links.
-import fs from "node:fs"
-import path from "node:path"
-import { spawnSync } from "node:child_process"
-import { createRequire } from "node:module"
+import fs from 'node:fs'
+import path from 'node:path'
+import { spawnSync } from 'node:child_process'
+import { createRequire } from 'node:module'
const require = createRequire(import.meta.url)
-function electronDistDir() {
- try {
- return path.join(path.dirname(require.resolve("electron/package.json")), "dist")
- } catch {
- return null
+function electronBuilderCli() {
+ const entry = require.resolve('electron-builder')
+ let dir = path.dirname(entry)
+ while (!fs.existsSync(path.join(dir, 'package.json'))) {
+ const parent = path.dirname(dir)
+ if (parent === dir) {
+ throw new Error('electron-builder package root not found')
+ }
+ dir = parent
}
+ const bin = require(path.join(dir, 'package.json')).bin
+ const rel = typeof bin === 'string' ? bin : bin['electron-builder']
+ return path.join(dir, rel)
}
-function distBinary(dist) {
- if (process.platform === "darwin") {
- return path.join(dist, "Electron.app", "Contents", "MacOS", "Electron")
- }
- if (process.platform === "win32") {
- return path.join(dist, "electron.exe")
- }
- return path.join(dist, "electron")
+const args = [...process.argv.slice(2)]
+
+// package.json has no "build" field. Name the config file or electron-builder
+// would look for one and silently use defaults.
+if (!args.some(a => a === '--config' || a.startsWith('--config='))) {
+ args.push('--config', 'electron-builder.config.cjs')
}
-function electronBuilderCli() {
- const pkgJson = require.resolve("electron-builder/package.json")
- const bin = require(pkgJson).bin
- const rel = typeof bin === "string" ? bin : bin["electron-builder"]
- return path.join(path.dirname(pkgJson), rel)
+// Never let electron-builder publish. On a CI tag build it auto-detects
+// GitHub and demands GH_TOKEN after the artifacts are already built.
+// The release workflow uploads artifacts in its own step.
+if (!args.includes('--publish') && !args.some(a => a.startsWith('-p'))) {
+ args.push('--publish', 'never')
}
-const dist = electronDistDir()
-const args = []
-if (dist && fs.existsSync(distBinary(dist))) {
- args.push(`-c.electronDist=${dist}`)
-} else {
- console.warn(
- "[run-electron-builder] no local electron dist; electron-builder will fetch " +
- "via @electron/get (electronVersion + ELECTRON_MIRROR)."
+if (args.includes('--win') && process.env.AZURE_SIGN_ENDPOINT && process.env.AZURE_CLIENT_ID) {
+ console.log(
+ `[run-electron-builder] Windows signing: Azure Trusted Signing at ${process.env.AZURE_SIGN_ENDPOINT}`
)
}
-args.push(...process.argv.slice(2))
-const result = spawnSync(process.execPath, [electronBuilderCli(), ...args], {
- stdio: "inherit",
+// Cap concurrent fs.open calls in the electron-builder process.
+// @electron/osx-sign walks the whole .app with Promise.all and no
+// concurrency bound. The payload (lark_oapi alone is thousands of files)
+// exhausts the macOS table: EMFILE on a random .py. Raising ulimit only
+// moves the ceiling. --require, not an import: isbinaryfile captures
+// promisify(fs.open) at its own load.
+const preload = path.join(import.meta.dirname, 'fs-open-limit.cjs')
+
+const result = spawnSync(process.execPath, ['--require', preload, electronBuilderCli(), ...args], {
+ stdio: 'inherit'
})
if (result.error) {
console.error(`[run-electron-builder] spawn failed: ${result.error.message}`)
diff --git a/apps/desktop/scripts/sanitize-pe-signatures.mjs b/apps/desktop/scripts/sanitize-pe-signatures.mjs
new file mode 100644
index 00000000000..1eb3b2d9d4d
--- /dev/null
+++ b/apps/desktop/scripts/sanitize-pe-signatures.mjs
@@ -0,0 +1,212 @@
+/**
+ * sanitize-pe-signatures.mjs — repair PE certificate tables that point past
+ * the end of their own file, before anything tries to sign the tree.
+ *
+ * Why this exists: python-build-standalone runs `llvm-strip` over every DLL
+ * in its Windows distributions. Stripping drops the trailing Authenticode
+ * blob but leaves IMAGE_DIRECTORY_ENTRY_SECURITY in the optional header
+ * still naming its old offset and size. The result is a PE whose certificate
+ * table begins at (or past) EOF.
+ *
+ * signtool refuses such a file with 0x800700C1 (ERROR_BAD_EXE_FORMAT), and
+ * AppxSIP inspects every PE inside an MSIX, so ONE of them fails the whole
+ * package signing — which is how a payload DLL nobody imports took down both
+ * Windows bundled release jobs. Upstream exempted the MSVC redists from
+ * stripping (python-build-standalone#856) but not tcl/tk, and the same class
+ * can arrive from any stripped third-party dist we bundle.
+ *
+ * The repair is to zero the dangling directory entry: eight bytes that say
+ * "there is no certificate here", which is already true. The bytes the entry
+ * pointed at are gone; nothing else in the file references them. A signature
+ * that is actually present is never touched — a valid entry is left exactly
+ * as it is, so this can never strip a real signature.
+ */
+
+import fs from "node:fs"
+import path from "node:path"
+
+import { isMain } from "./utils.mjs"
+
+const PE_SIGNATURE = 0x00004550
+const COFF_HEADER_SIZE = 24 // PE signature (4) + COFF file header (20)
+const PE32_MAGIC = 0x10b
+const PE32PLUS_MAGIC = 0x20b
+const SECURITY_DIRECTORY_INDEX = 4
+const DATA_DIRECTORY_ENTRY_SIZE = 8
+
+/**
+ * Offset of NumberOfRvaAndSizes within the optional header. PE32 ends its
+ * fixed fields at 92. PE32+ drops BaseOfData (-4) and widens four fields
+ * from 4 to 8 bytes (+16), so its value sits 12 bytes later, at 108.
+ *
+ * @param {number} magic optional header magic (0x10b PE32, 0x20b PE32+)
+ * @returns {number | null} byte offset, or null when the magic is unknown
+ */
+export function numberOfRvaAndSizesOffset(magic) {
+ if (magic === PE32PLUS_MAGIC) return 108
+ if (magic === PE32_MAGIC) return 92
+ return null
+}
+
+/**
+ * Byte offset of the security data directory entry, relative to the start
+ * of the file.
+ *
+ * @param {number} peHeaderOffset value of e_lfanew (offset of "PE\0\0")
+ * @param {number} magic optional header magic
+ * @returns {number | null} absolute file offset, or null for an unknown magic
+ */
+export function securityDirectoryOffset(peHeaderOffset, magic) {
+ const rvaCount = numberOfRvaAndSizesOffset(magic)
+ if (rvaCount === null) return null
+ return (
+ peHeaderOffset +
+ COFF_HEADER_SIZE +
+ rvaCount +
+ 4 + // NumberOfRvaAndSizes itself
+ SECURITY_DIRECTORY_INDEX * DATA_DIRECTORY_ENTRY_SIZE
+ )
+}
+
+/**
+ * Decide what a security directory entry describes. For this directory
+ * alone the "RVA" field is a plain file offset, not a virtual address, so
+ * it is directly comparable against the file size.
+ *
+ * "dangling" is the repairable case and is deliberately narrow: the entry
+ * must name a region that cannot exist in this file. Anything that fits
+ * inside the file is a real signature and is reported as "present" so the
+ * caller leaves it alone.
+ *
+ * @param {{ certOffset: number, certSize: number, fileSize: number }} entry
+ * @returns {"absent" | "present" | "dangling"}
+ */
+export function classifySecurityDirectory({ certOffset, certSize, fileSize }) {
+ if (certOffset === 0 && certSize === 0) return "absent"
+ // A zero offset with a nonzero size (or the reverse) names no usable
+ // region either; both halves must be sane for a signature to be readable.
+ if (certOffset === 0 || certSize === 0) return "dangling"
+ if (certOffset >= fileSize) return "dangling"
+ if (certOffset + certSize > fileSize) return "dangling"
+ return "present"
+}
+
+/**
+ * Read the security directory of a PE file.
+ *
+ * @param {string} file
+ * @returns {{ offsetInFile: number, certOffset: number, certSize: number, fileSize: number } | null}
+ * null when the file is not a PE with data directories at all.
+ */
+export function readSecurityDirectory(file) {
+ const fd = fs.openSync(file, "r")
+ try {
+ const fileSize = fs.fstatSync(fd).size
+ if (fileSize < 0x40) return null
+
+ const mz = Buffer.alloc(0x40)
+ fs.readSync(fd, mz, 0, 0x40, 0)
+ if (mz[0] !== 0x4d || mz[1] !== 0x5a) return null
+
+ const peHeaderOffset = mz.readUInt32LE(0x3c)
+ if (peHeaderOffset <= 0 || peHeaderOffset + COFF_HEADER_SIZE > fileSize) return null
+
+ const coff = Buffer.alloc(COFF_HEADER_SIZE)
+ fs.readSync(fd, coff, 0, COFF_HEADER_SIZE, peHeaderOffset)
+ if (coff.readUInt32LE(0) !== PE_SIGNATURE) return null
+
+ const optionalHeaderSize = coff.readUInt16LE(20)
+ if (optionalHeaderSize === 0) return null // object file: no data directories
+
+ const magicBuf = Buffer.alloc(2)
+ fs.readSync(fd, magicBuf, 0, 2, peHeaderOffset + COFF_HEADER_SIZE)
+ const offsetInFile = securityDirectoryOffset(peHeaderOffset, magicBuf.readUInt16LE(0))
+ if (offsetInFile === null) return null
+ if (offsetInFile + DATA_DIRECTORY_ENTRY_SIZE > peHeaderOffset + COFF_HEADER_SIZE + optionalHeaderSize) {
+ return null // header declares fewer directories than the security slot
+ }
+
+ const entry = Buffer.alloc(DATA_DIRECTORY_ENTRY_SIZE)
+ fs.readSync(fd, entry, 0, DATA_DIRECTORY_ENTRY_SIZE, offsetInFile)
+ return {
+ offsetInFile,
+ certOffset: entry.readUInt32LE(0),
+ certSize: entry.readUInt32LE(4),
+ fileSize,
+ }
+ } finally {
+ fs.closeSync(fd)
+ }
+}
+
+/**
+ * Zero the eight bytes of a security directory entry in place.
+ *
+ * @param {string} file
+ * @param {number} offsetInFile offset of the entry, from readSecurityDirectory
+ * @returns {void}
+ */
+export function clearSecurityDirectory(file, offsetInFile) {
+ const fd = fs.openSync(file, "r+")
+ try {
+ fs.writeSync(fd, Buffer.alloc(DATA_DIRECTORY_ENTRY_SIZE), 0, DATA_DIRECTORY_ENTRY_SIZE, offsetInFile)
+ } finally {
+ fs.closeSync(fd)
+ }
+}
+
+/**
+ * @param {string} dir
+ * @returns {Generator<string>}
+ */
+function* walkFiles(dir) {
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
+ const full = path.join(dir, entry.name)
+ if (entry.isSymbolicLink()) continue
+ if (entry.isDirectory()) yield* walkFiles(full)
+ else if (entry.isFile()) yield full
+ }
+}
+
+/**
+ * Repair every dangling security directory under a tree.
+ *
+ * @param {string} rootDir
+ * @returns {{ scanned: number, repaired: string[] }} repaired paths are
+ * relative to rootDir, in walk order.
+ */
+export function sanitizeTree(rootDir) {
+ const repaired = []
+ let scanned = 0
+ for (const file of walkFiles(rootDir)) {
+ let entry
+ try {
+ entry = readSecurityDirectory(file)
+ } catch {
+ continue // unreadable: packaging would already have failed on it
+ }
+ if (!entry) continue
+ scanned += 1
+ if (classifySecurityDirectory(entry) !== "dangling") continue
+ clearSecurityDirectory(file, entry.offsetInFile)
+ repaired.push(path.relative(rootDir, file))
+ }
+ return { scanned, repaired }
+}
+
+function main() {
+ const root = process.argv[2]
+ if (!root) {
+ console.error("usage: sanitize-pe-signatures.mjs <dir>")
+ process.exit(2)
+ }
+ const { scanned, repaired } = sanitizeTree(root)
+ console.log(`[sanitize-pe-signatures] ${scanned} PEs scanned, ${repaired.length} repaired`)
+ for (const file of repaired) {
+ console.log(` cleared dangling certificate table: ${file}`)
+ }
+}
+
+if (isMain(import.meta.url)) {
+ main()
+}
diff --git a/apps/desktop/scripts/sanitize-pe-signatures.test.mjs b/apps/desktop/scripts/sanitize-pe-signatures.test.mjs
new file mode 100644
index 00000000000..f72d6ea35de
--- /dev/null
+++ b/apps/desktop/scripts/sanitize-pe-signatures.test.mjs
@@ -0,0 +1,160 @@
+import assert from 'node:assert/strict'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+
+import { afterEach, beforeEach, test } from 'vitest'
+
+import {
+ classifySecurityDirectory,
+ clearSecurityDirectory,
+ numberOfRvaAndSizesOffset,
+ readSecurityDirectory,
+ sanitizeTree,
+} from '../scripts/sanitize-pe-signatures.mjs'
+
+// ─── fixture builder: a PE with a chosen security directory ────────────────
+
+const PE_HEADER_OFFSET = 0x80
+const OPTIONAL_HEADER_SIZE = 240 // enough for 16 data directories in either width
+
+/**
+ * Build the smallest byte sequence that parses as a PE with data
+ * directories, then append `trailing` bytes to stand in for a signature.
+ * certOffset/certSize are written verbatim so a test can describe a valid
+ * table, a dangling one, or none at all.
+ */
+function peFile({ magic = 0x20b, certOffset = 0, certSize = 0, trailing = 0 } = {}) {
+ const headerEnd = PE_HEADER_OFFSET + 24 + OPTIONAL_HEADER_SIZE
+ const buf = Buffer.alloc(headerEnd + trailing)
+ buf.write('MZ', 0, 'latin1')
+ buf.writeUInt32LE(PE_HEADER_OFFSET, 0x3c)
+ buf.writeUInt32LE(0x00004550, PE_HEADER_OFFSET) // "PE\0\0"
+ buf.writeUInt16LE(magic === 0x20b ? 0xaa64 : 0x014c, PE_HEADER_OFFSET + 4) // machine
+ buf.writeUInt16LE(OPTIONAL_HEADER_SIZE, PE_HEADER_OFFSET + 20)
+ buf.writeUInt16LE(magic, PE_HEADER_OFFSET + 24)
+ const rvaCount = numberOfRvaAndSizesOffset(magic)
+ buf.writeUInt32LE(16, PE_HEADER_OFFSET + 24 + rvaCount)
+ const secOff = PE_HEADER_OFFSET + 24 + rvaCount + 4 + 4 * 8
+ buf.writeUInt32LE(certOffset, secOff)
+ buf.writeUInt32LE(certSize, secOff + 4)
+ return { buf, securityDirectoryOffset: secOff, headerEnd }
+}
+
+let dir
+beforeEach(() => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pe-sanitize-'))
+})
+afterEach(() => {
+ fs.rmSync(dir, { recursive: true, force: true })
+})
+
+/** @returns {string} absolute path of the written fixture */
+function write(name, spec) {
+ const file = path.join(dir, name)
+ fs.mkdirSync(path.dirname(file), { recursive: true })
+ fs.writeFileSync(file, peFile(spec).buf)
+ return file
+}
+
+// ─── header arithmetic ──────────────────────────────────────────────────────
+
+test('NumberOfRvaAndSizes sits at 92 for PE32 and 108 for PE32+', () => {
+ // The whole repair keys off this offset: read it wrong and a valid
+ // signature looks dangling (or the reverse).
+ assert.equal(numberOfRvaAndSizesOffset(0x10b), 92)
+ assert.equal(numberOfRvaAndSizesOffset(0x20b), 108)
+ assert.equal(numberOfRvaAndSizesOffset(0x107), null)
+})
+
+// ─── classification ─────────────────────────────────────────────────────────
+
+test('a table wholly inside the file is a real signature', () => {
+ assert.equal(classifySecurityDirectory({ certOffset: 100, certSize: 24, fileSize: 200 }), 'present')
+ // Exactly reaching EOF is the normal shape: signatures live at the end.
+ assert.equal(classifySecurityDirectory({ certOffset: 100, certSize: 100, fileSize: 200 }), 'present')
+})
+
+test('a table that cannot fit in the file is dangling', () => {
+ // The stripped-DLL shape: offset equals the (now truncated) file size.
+ assert.equal(classifySecurityDirectory({ certOffset: 200, certSize: 24, fileSize: 200 }), 'dangling')
+ assert.equal(classifySecurityDirectory({ certOffset: 190, certSize: 24, fileSize: 200 }), 'dangling')
+ // Half-populated entries name no readable region either.
+ assert.equal(classifySecurityDirectory({ certOffset: 0, certSize: 24, fileSize: 200 }), 'dangling')
+ assert.equal(classifySecurityDirectory({ certOffset: 100, certSize: 0, fileSize: 200 }), 'dangling')
+})
+
+test('an all-zero table means no signature and needs no repair', () => {
+ assert.equal(classifySecurityDirectory({ certOffset: 0, certSize: 0, fileSize: 200 }), 'absent')
+})
+
+// ─── reading and clearing ───────────────────────────────────────────────────
+
+test('readSecurityDirectory locates the entry in both PE widths', () => {
+ for (const magic of [0x10b, 0x20b]) {
+ const spec = { magic, certOffset: 1234, certSize: 16 }
+ const file = write(`w${magic}.dll`, spec)
+ const entry = readSecurityDirectory(file)
+ assert.equal(entry.certOffset, 1234)
+ assert.equal(entry.certSize, 16)
+ assert.equal(entry.offsetInFile, peFile(spec).securityDirectoryOffset)
+ }
+})
+
+test('readSecurityDirectory ignores files that are not PEs with directories', () => {
+ const plain = path.join(dir, 'notes.txt')
+ fs.writeFileSync(plain, 'hello')
+ assert.equal(readSecurityDirectory(plain), null)
+
+ // MZ with no PE signature: a DOS-era stub, not a PE.
+ const stub = path.join(dir, 'stub.exe')
+ const buf = Buffer.alloc(0x100)
+ buf.write('MZ', 0, 'latin1')
+ buf.writeUInt32LE(0x80, 0x3c)
+ fs.writeFileSync(stub, buf)
+ assert.equal(readSecurityDirectory(stub), null)
+})
+
+test('clearSecurityDirectory zeroes the entry and changes nothing else', () => {
+ const spec = { magic: 0x20b, certOffset: 4096, certSize: 40 }
+ const file = write('cleared.dll', spec)
+ const before = fs.readFileSync(file)
+
+ clearSecurityDirectory(file, peFile(spec).securityDirectoryOffset)
+
+ const after = fs.readFileSync(file)
+ assert.equal(after.length, before.length)
+ const entry = readSecurityDirectory(file)
+ assert.equal(entry.certOffset, 0)
+ assert.equal(entry.certSize, 0)
+ // Byte-for-byte identical everywhere except the eight-byte entry.
+ const off = entry.offsetInFile
+ assert.deepEqual(after.subarray(0, off), before.subarray(0, off))
+ assert.deepEqual(after.subarray(off + 8), before.subarray(off + 8))
+})
+
+// ─── the tree pass ──────────────────────────────────────────────────────────
+
+test('sanitizeTree repairs dangling tables and leaves real signatures alone', () => {
+ // The payload shape that broke the Windows bundled release: a stripped
+ // DLL whose table starts exactly at EOF, beside correctly signed files.
+ const stripped = write('python/DLLs/tcl86t.dll', { certOffset: 464, certSize: 12056 })
+ const signed = write('python/python.exe', { certOffset: 400, certSize: 64, trailing: 200 })
+ const unsigned = write('python/DLLs/_socket.pyd', {})
+ fs.writeFileSync(path.join(dir, 'python', 'LICENSE.txt'), 'not a PE')
+
+ const { scanned, repaired } = sanitizeTree(dir)
+
+ assert.equal(scanned, 3) // the three PEs; the text file is skipped
+ assert.deepEqual(repaired, [path.join('python', 'DLLs', 'tcl86t.dll')])
+ assert.equal(readSecurityDirectory(stripped).certSize, 0)
+ assert.equal(readSecurityDirectory(signed).certSize, 64) // untouched
+ assert.equal(readSecurityDirectory(unsigned).certSize, 0)
+})
+
+test('sanitizeTree is idempotent', () => {
+ write('DLLs/tk86t.dll', { certOffset: 464, certSize: 12064 })
+
+ assert.equal(sanitizeTree(dir).repaired.length, 1)
+ assert.deepEqual(sanitizeTree(dir).repaired, [])
+})
diff --git a/apps/desktop/scripts/sign-msix.test.mjs b/apps/desktop/scripts/sign-msix.test.mjs
new file mode 100644
index 00000000000..02f58bbdbe1
--- /dev/null
+++ b/apps/desktop/scripts/sign-msix.test.mjs
@@ -0,0 +1,120 @@
+import assert from 'node:assert/strict'
+import fs from 'node:fs'
+import { createRequire } from 'node:module'
+import path from 'node:path'
+import { pathToFileURL } from 'node:url'
+import { test } from 'vitest'
+
+import { azureConfigFromEnv, shouldSignFile } from './sign-msix.mjs'
+
+const require = createRequire(import.meta.url)
+
+test('shouldSignFile admits only .msix and .msixbundle artifacts', () => {
+ assert.equal(shouldSignFile('release/Hermes-0.17.0-win32-arm64.msix'), true)
+ assert.equal(shouldSignFile('release/Hermes-0.17.0-win32-x64.msix'), true)
+ assert.equal(shouldSignFile('release/Hermes-0.17.0-win32-arm64.msixbundle'), true)
+ // Case-insensitive — artifactName could emit .MSIX on some host.
+ assert.equal(shouldSignFile('release/Hermes-0.17.0-win32-arm64.MSIX'), true)
+})
+
+test('shouldSignFile rejects the Store-submission variant (Partner Center re-signs)', () => {
+ // The Store- msix manifest Publisher is the Partner Center publisher ID
+ // (CN=EE6D86E4-...), which no signable cert subject can match — ATS
+ // cannot customize CN and CA/B requires the legal entity name — so
+ // SignerSign would fail 0x8007000B. Partner Center signs on ingestion.
+ assert.equal(
+ shouldSignFile('release/Store-HermesBundled-0.28.0-nightly.20260828211829-win-x64.msix'),
+ false
+ )
+ assert.equal(
+ shouldSignFile('release/Store-HermesBundled-0.28.0-nightly.20260828211829-win-arm64.msixbundle'),
+ false
+ )
+ // The out-of-store artifacts keep the only signature Windows validates.
+ assert.equal(
+ shouldSignFile('release/HermesBundled-0.28.0-nightly.20260828211829-win-x64.msix'),
+ true
+ )
+})
+
+test('shouldSignFile rejects every non-package file the hook is asked to sign', () => {
+ // The app exe and any payload binary are covered by the package's block
+ // map — signing them is wasted round-trips and would break the hash if
+ // done after makeappx packs the package.
+ assert.equal(shouldSignFile('release/win-unpacked/Hermes.exe'), false)
+ assert.equal(shouldSignFile('C:/work/hermes-agent/release/win-unpacked/Hermes.exe'), false)
+ assert.equal(shouldSignFile('release/Hermes-0.17.0-win32-arm64.nsis.exe'), false)
+ assert.equal(shouldSignFile('release/Hermes-0.17.0-win32-arm64.msixupload'), false)
+ assert.equal(shouldSignFile('release/Hermes-0.17.0-win32-arm64.dll'), false)
+ assert.equal(shouldSignFile(''), false)
+})
+
+test('azureConfigFromEnv composes the Azure signing config from the environment', () => {
+ assert.deepEqual(
+ azureConfigFromEnv({
+ AZURE_SIGN_ENDPOINT: 'https://cus.codesigning.azure.net',
+ AZURE_SIGN_ACCOUNT: 'codesign2',
+ AZURE_SIGN_PROFILE: 'hermesagent',
+ AZURE_SIGN_PUBLISHER: 'CN=Nous Research Inc.'
+ }),
+ {
+ type: 'azure',
+ endpoint: 'https://cus.codesigning.azure.net',
+ codeSigningAccountName: 'codesign2',
+ certificateProfileName: 'hermesagent',
+ publisherName: 'CN=Nous Research Inc.'
+ }
+ )
+ // Missing vars stay undefined — the manager's ctor handles that.
+ assert.deepEqual(azureConfigFromEnv({}), {
+ type: 'azure',
+ endpoint: undefined,
+ codeSigningAccountName: undefined,
+ certificateProfileName: undefined,
+ publisherName: undefined
+ })
+})
+
+// ─── builder-bump tripwire ──────────────────────────────────────────────────
+// sign-msix.mjs deep-imports app-builder-lib's WindowsSignAzureManager by
+// file path (the package exports map exposes only "." and "./internal", so
+// the dist path is reached the same way run-electron-builder.mjs finds the
+// CLI: resolve the entry, walk up to the package root, then direct-file
+// import). If an electron-builder/app-builder-lib bump moves or renames the
+// class, THIS test is what fails in js-tests — before a release build does.
+// 60s timeout: the direct-file import drags in app-builder-lib's whole
+// module graph (toolsets, electronGet, vm), which takes ~30s on a cold
+// disk cache — far past vitest's 5s default.
+test('the real WindowsSignAzureManager resolves and constructs against a packager shim', { timeout: 60_000 }, async () => {
+ const entry = require.resolve('app-builder-lib')
+ let root = path.dirname(entry)
+ while (!fs.existsSync(path.join(root, 'package.json'))) {
+ const parent = path.dirname(root)
+ assert.notEqual(parent, root, 'app-builder-lib package root not found')
+ root = parent
+ }
+ const mod = await import(
+ pathToFileURL(path.join(root, 'dist', 'codeSign', 'win', 'windowsSignAzureManager.js')).href
+ )
+ assert.equal(typeof mod.WindowsSignAzureManager, 'function')
+
+ // Constructor contract (verified against 27.0.0-alpha.6): reads
+ // packager.platformOptions.sign (throws unless type === 'azure'),
+ // packager.config.toolsets (optional), and packager.buildResourcesDir
+ // (only stored — WineVmManager's constructor touches no filesystem).
+ const mgr = new mod.WindowsSignAzureManager({
+ platformOptions: {
+ sign: {
+ type: 'azure',
+ endpoint: 'x',
+ codeSigningAccountName: 'y',
+ certificateProfileName: 'z',
+ publisherName: 'p'
+ }
+ },
+ config: {},
+ buildResourcesDir: '/tmp'
+ })
+ assert.equal(typeof mgr.signFile, 'function')
+ assert.equal(typeof mgr.initialize, 'function')
+})
diff --git a/apps/desktop/scripts/sign-nested-chromium.mjs b/apps/desktop/scripts/sign-nested-chromium.mjs
new file mode 100644
index 00000000000..6fc4850a691
--- /dev/null
+++ b/apps/desktop/scripts/sign-nested-chromium.mjs
@@ -0,0 +1,225 @@
+// Sign payload Chromium with our Developer ID before osx-sign seals
+// Hermes.app. Google's leftover signatures have no timestamp and no
+// hardened runtime, so Apple's notary rejects them.
+//
+// Do not codesign a file that lives inside a .framework: codesign then
+// treats Versions/A/Foo as a bundle and dies with "code object is not
+// signed at all" (or "bundle format is ambiguous" on the Foo.framework/Foo
+// symlink). Sign the enclosing .app with --deep. Loose Mach-O outside
+// any .app (headless-shell + its dylibs) is signed as a file.
+//
+// signIgnore still keeps osx-sign off the chromium trees.
+
+import { execFileSync } from 'node:child_process'
+import fs from 'node:fs'
+import path from 'node:path'
+
+const MACHO_MAGICS = new Set([
+ 0xfeedface, 0xcefaedfe, 0xfeedfacf, 0xcffaedfe, 0xcafebabe, 0xbebafeca
+])
+
+export function isMachO(file) {
+ const buf = Buffer.alloc(4)
+ let fd
+ try {
+ fd = fs.openSync(file, 'r')
+ if (fs.readSync(fd, buf, 0, 4, 0) !== 4) return false
+ } catch {
+ return false
+ } finally {
+ if (fd != null) fs.closeSync(fd)
+ }
+ return MACHO_MAGICS.has(buf.readUInt32BE(0))
+}
+
+export function chromiumRoots(payload) {
+ const tools = path.join(payload, 'tools')
+ if (!fs.existsSync(tools)) return []
+ return fs
+ .readdirSync(tools, { withFileTypes: true })
+ .filter(ent => ent.isDirectory() && /^chromium(_headless_shell)?-\d+/.test(ent.name))
+ .map(ent => path.join(tools, ent.name))
+}
+
+export function listTopLevelApps(root) {
+ const apps = []
+ const walk = dir => {
+ let entries
+ try {
+ entries = fs.readdirSync(dir, { withFileTypes: true })
+ } catch {
+ return
+ }
+ for (const ent of entries) {
+ const p = path.join(dir, ent.name)
+ if (ent.isSymbolicLink()) continue
+ if (ent.isDirectory() && p.endsWith('.app')) {
+ apps.push(p)
+ continue
+ }
+ if (ent.isDirectory()) walk(p)
+ }
+ }
+ walk(root)
+ return apps
+}
+
+export function listLooseMachO(root) {
+ const out = []
+ const walk = dir => {
+ let entries
+ try {
+ entries = fs.readdirSync(dir, { withFileTypes: true })
+ } catch {
+ return
+ }
+ for (const ent of entries) {
+ const p = path.join(dir, ent.name)
+ if (ent.isSymbolicLink()) continue
+ if (ent.isDirectory()) {
+ if (p.endsWith('.app')) continue
+ walk(p)
+ continue
+ }
+ if (!ent.isFile()) continue
+ if (isMachO(p)) out.push(p)
+ }
+ }
+ walk(root)
+ return out
+}
+
+// If Foo.framework/Foo is a regular file and Versions/*/Foo exists,
+// replace the top-level copy with a symlink. Same for Versions/Current.
+export function repairFrameworkLinks(root) {
+ let repaired = 0
+ const walk = dir => {
+ let entries
+ try {
+ entries = fs.readdirSync(dir, { withFileTypes: true })
+ } catch {
+ return
+ }
+ for (const ent of entries) {
+ const p = path.join(dir, ent.name)
+ if (ent.isSymbolicLink()) continue
+ if (ent.isDirectory() && ent.name.endsWith('.framework')) {
+ repaired += repairOneFramework(p)
+ continue
+ }
+ if (ent.isDirectory()) walk(p)
+ }
+ }
+ walk(root)
+ return repaired
+}
+
+function repairOneFramework(frameworkDir) {
+ let repaired = 0
+ const versions = path.join(frameworkDir, 'Versions')
+ if (!fs.existsSync(versions)) return 0
+ const versionDirs = fs
+ .readdirSync(versions, { withFileTypes: true })
+ .filter(ent => ent.isDirectory() && ent.name !== 'Current')
+ .map(ent => ent.name)
+ if (versionDirs.length === 0) return 0
+ const preferred = versionDirs.includes('A') ? 'A' : versionDirs[0]
+ const current = path.join(versions, 'Current')
+ if (!fs.existsSync(current) || !fs.lstatSync(current).isSymbolicLink()) {
+ if (fs.existsSync(current)) fs.rmSync(current, { recursive: true, force: true })
+ fs.symlinkSync(preferred, current)
+ repaired += 1
+ }
+ const stem = path.basename(frameworkDir, '.framework')
+ for (const name of [stem, 'Resources', 'Libraries', 'Helpers']) {
+ const top = path.join(frameworkDir, name)
+ const target = path.posix.join('Versions', 'Current', name)
+ const versioned = path.join(frameworkDir, 'Versions', preferred, name)
+ if (!fs.existsSync(versioned) && name !== stem) continue
+ if (fs.existsSync(top) && fs.lstatSync(top).isSymbolicLink()) continue
+ if (fs.existsSync(top)) fs.rmSync(top, { recursive: true, force: true })
+ if (fs.existsSync(versioned) || name === stem) {
+ fs.symlinkSync(target, top)
+ repaired += 1
+ }
+ }
+ return repaired
+}
+
+export function parseDeveloperId(identityList) {
+ const line = String(identityList || '')
+ .split(/\r?\n/)
+ .find(l => l.includes('Developer ID Application:'))
+ if (!line) return null
+ const quoted = line.match(/"([^"]+)"/)
+ return quoted ? quoted[1] : null
+}
+
+export function findDeveloperId(exec = execFileSync, keychain = null) {
+ if (process.env.CSC_NAME) return process.env.CSC_NAME
+ const args = ['find-identity', '-v', '-p', 'codesigning']
+ if (keychain) args.push(keychain)
+ let out
+ try {
+ out = exec('security', args, { encoding: 'utf8' })
+ } catch {
+ return null
+ }
+ return parseDeveloperId(out)
+}
+
+export async function resolveSigningIdentity(packager, exec = execFileSync) {
+ if (!packager?.codeSigningInfo?.value) {
+ return { identity: findDeveloperId(exec), keychain: null }
+ }
+ let info
+ try {
+ info = await packager.codeSigningInfo.value
+ } catch {
+ return { identity: findDeveloperId(exec), keychain: null }
+ }
+ const keychain = info?.keychainFile || process.env.CSC_KEYCHAIN || null
+ return { identity: findDeveloperId(exec, keychain), keychain }
+}
+
+function codesign(exec, identity, entitlements, keychain, target, deep) {
+ const args = [
+ '--force',
+ '--sign',
+ identity,
+ '--timestamp',
+ '--options',
+ 'runtime',
+ '--entitlements',
+ entitlements
+ ]
+ if (deep) args.push('--deep')
+ if (keychain) args.push('--keychain', keychain)
+ args.push(target)
+ exec('codesign', args, { stdio: 'pipe' })
+}
+
+export function signNestedChromium(payload, opts = {}) {
+ const identity = opts.identity
+ if (!identity) return { signed: 0, repaired: 0, identity: null }
+ const entitlements = opts.entitlements
+ if (!entitlements || !fs.existsSync(entitlements)) {
+ throw new Error(`sign-nested-chromium: entitlements missing at ${entitlements}`)
+ }
+ const exec = opts.exec ?? execFileSync
+ const keychain = opts.keychain || null
+ let signed = 0
+ let repaired = 0
+ for (const root of chromiumRoots(payload)) {
+ repaired += repairFrameworkLinks(root)
+ for (const app of listTopLevelApps(root)) {
+ codesign(exec, identity, entitlements, keychain, app, true)
+ signed += 1
+ }
+ for (const file of listLooseMachO(root)) {
+ codesign(exec, identity, entitlements, keychain, file, false)
+ signed += 1
+ }
+ }
+ return { signed, repaired, identity }
+}
diff --git a/apps/desktop/scripts/sign-nested-chromium.test.mjs b/apps/desktop/scripts/sign-nested-chromium.test.mjs
new file mode 100644
index 00000000000..034d69fdf48
--- /dev/null
+++ b/apps/desktop/scripts/sign-nested-chromium.test.mjs
@@ -0,0 +1,159 @@
+import assert from 'node:assert/strict'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { test } from 'vitest'
+
+import {
+ chromiumRoots,
+ isMachO,
+ listLooseMachO,
+ listTopLevelApps,
+ parseDeveloperId,
+ repairFrameworkLinks,
+ resolveSigningIdentity,
+ signNestedChromium
+} from './sign-nested-chromium.mjs'
+
+function tempRoot() {
+ return fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-sign-chrome-'))
+}
+
+function machoBuf() {
+ const buf = Buffer.alloc(16)
+ buf.writeUInt32BE(0xfeedfacf, 0)
+ return buf
+}
+
+test('isMachO accepts a 64-bit Mach-O magic and rejects text', () => {
+ const dir = tempRoot()
+ try {
+ const bin = path.join(dir, 'a')
+ const txt = path.join(dir, 'b.txt')
+ fs.writeFileSync(bin, machoBuf())
+ fs.writeFileSync(txt, 'not a binary')
+ assert.equal(isMachO(bin), true)
+ assert.equal(isMachO(txt), false)
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true })
+ }
+})
+
+test('chromiumRoots only names chromium store entries', () => {
+ const payload = tempRoot()
+ try {
+ fs.mkdirSync(path.join(payload, 'tools', 'chromium-1208'), { recursive: true })
+ fs.mkdirSync(path.join(payload, 'tools', 'chromium_headless_shell-1208'), { recursive: true })
+ fs.mkdirSync(path.join(payload, 'tools', 'uv-0.12.3-darwin-arm64'), { recursive: true })
+ const roots = chromiumRoots(payload).map(p => path.basename(p)).sort()
+ assert.deepEqual(roots, ['chromium-1208', 'chromium_headless_shell-1208'])
+ } finally {
+ fs.rmSync(payload, { recursive: true, force: true })
+ }
+})
+
+test('listTopLevelApps finds .app dirs and listLooseMachO skips them', () => {
+ const root = tempRoot()
+ try {
+ const app = path.join(root, 'Google Chrome for Testing.app')
+ fs.mkdirSync(path.join(app, 'Contents', 'MacOS'), { recursive: true })
+ fs.writeFileSync(path.join(app, 'Contents', 'MacOS', 'Chrome'), machoBuf())
+ const loose = path.join(root, 'chrome-headless-shell')
+ fs.writeFileSync(loose, machoBuf())
+ assert.deepEqual(listTopLevelApps(root), [app])
+ assert.deepEqual(listLooseMachO(root), [loose])
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+})
+
+test('repairFrameworkLinks turns a flattened Foo.framework/Foo into a symlink', () => {
+ if (process.platform === 'win32') return
+ const root = tempRoot()
+ try {
+ const fw = path.join(root, 'F.framework')
+ const versioned = path.join(fw, 'Versions', 'A')
+ fs.mkdirSync(path.join(versioned, 'Resources'), { recursive: true })
+ fs.writeFileSync(path.join(versioned, 'F'), machoBuf())
+ fs.writeFileSync(path.join(versioned, 'Resources', 'Info.plist'), '<plist/>')
+ fs.writeFileSync(path.join(fw, 'F'), machoBuf())
+ fs.mkdirSync(path.join(fw, 'Resources'))
+ fs.writeFileSync(path.join(fw, 'Resources', 'Info.plist'), '<plist/>')
+
+ const n = repairFrameworkLinks(root)
+ assert.ok(n >= 2)
+ assert.equal(fs.lstatSync(path.join(fw, 'F')).isSymbolicLink(), true)
+ assert.equal(fs.lstatSync(path.join(fw, 'Versions', 'Current')).isSymbolicLink(), true)
+ assert.equal(fs.readFileSync(path.join(fw, 'F')).equals(machoBuf()), true)
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+})
+
+test('parseDeveloperId takes the first Developer ID Application line', () => {
+ const listing = `
+ 1) ABC "Apple Development: [email protected] (TEAM)"
+ 2) DEF "Developer ID Application: Nous Research Inc (763K57MW7Z)"
+ 3) GHI "Developer ID Installer: Nous Research Inc (763K57MW7Z)"
+`
+ assert.equal(parseDeveloperId(listing), 'Developer ID Application: Nous Research Inc (763K57MW7Z)')
+ assert.equal(parseDeveloperId('nothing here'), null)
+})
+
+test('signNestedChromium no-ops without an identity', () => {
+ const payload = tempRoot()
+ try {
+ const r = signNestedChromium(payload, { identity: null, entitlements: path.join(payload, 'missing.plist') })
+ assert.deepEqual(r, { signed: 0, repaired: 0, identity: null })
+ } finally {
+ fs.rmSync(payload, { recursive: true, force: true })
+ }
+})
+
+test('signNestedChromium --deep signs the .app and file-signs loose Mach-O', () => {
+ const payload = tempRoot()
+ try {
+ const entitlements = path.join(payload, 'entitlements.plist')
+ fs.writeFileSync(entitlements, '<plist/>')
+ const app = path.join(payload, 'tools', 'chromium-1208', 'Google Chrome for Testing.app')
+ fs.mkdirSync(path.join(app, 'Contents', 'MacOS'), { recursive: true })
+ fs.writeFileSync(path.join(app, 'Contents', 'MacOS', 'Chrome'), machoBuf())
+ const looseDir = path.join(payload, 'tools', 'chromium_headless_shell-1208')
+ fs.mkdirSync(looseDir, { recursive: true })
+ const loose = path.join(looseDir, 'chrome-headless-shell')
+ fs.writeFileSync(loose, machoBuf())
+ const calls = []
+ const r = signNestedChromium(payload, {
+ identity: 'Developer ID Application: Test',
+ entitlements,
+ exec: (cmd, args) => {
+ calls.push([cmd, ...args])
+ }
+ })
+ assert.equal(r.signed, 2)
+ assert.equal(calls.length, 2)
+ const appCall = calls.find(c => c.includes(app))
+ const fileCall = calls.find(c => c.includes(loose))
+ assert.ok(appCall.includes('--deep'))
+ assert.ok(!fileCall.includes('--deep'))
+ } finally {
+ fs.rmSync(payload, { recursive: true, force: true })
+ }
+})
+
+test('resolveSigningIdentity reads the packager keychain', async () => {
+ const seen = []
+ const packager = {
+ codeSigningInfo: {
+ value: Promise.resolve({ keychainFile: '/tmp/builder.keychain' })
+ }
+ }
+ const listing = ' 1) DEF "Developer ID Application: Nous Research Inc (763K57MW7Z)"\n'
+ const r = await resolveSigningIdentity(packager, (_cmd, args) => {
+ seen.push(args)
+ return listing
+ })
+ assert.equal(r.identity, 'Developer ID Application: Nous Research Inc (763K57MW7Z)')
+ assert.equal(r.keychain, '/tmp/builder.keychain')
+ assert.ok(seen[0].includes('/tmp/builder.keychain'))
+})
diff --git a/apps/desktop/scripts/test-desktop.mjs b/apps/desktop/scripts/test-desktop.mjs
index ec94ddc5e7f..2087eadb884 100644
--- a/apps/desktop/scripts/test-desktop.mjs
+++ b/apps/desktop/scripts/test-desktop.mjs
@@ -13,10 +13,8 @@ const DESKTOP_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)),
const RELEASE_ROOT = path.join(DESKTOP_ROOT, 'release')
const PLATFORM = process.platform
-// Platform-specific packaged-app layout. The thin installer ships an Electron
-// app shell plus extraResources (install-stamp.json + native-deps/) -- it
-// no longer bundles the Hermes Agent Python payload (that's fetched at first
-// launch via install.ps1 / install.sh, per the Phase 1 thin-installer flow).
+// Platform-specific packaged-app layout. The bundled app ships an Electron
+// shell and the PM payload under resources/agent-payload.
const APP = (() => {
if (PLATFORM === 'darwin') {
const appPath = path.join(RELEASE_ROOT, `mac-${ARCH}`, 'Hermes.app')
@@ -49,17 +47,6 @@ const APP = (() => {
}
})()
-// Default HERMES_HOME for non-sandboxed runs -- matches main.ts's
-// resolveHermesHome(). On Windows it's %LOCALAPPDATA%\hermes; elsewhere
-// it's ~/.hermes. The fresh-install sandbox launchFresh() sets its own
-// HERMES_HOME and never touches this.
-const DEFAULT_HERMES_HOME = (() => {
- if (PLATFORM === 'win32' && process.env.LOCALAPPDATA) {
- return path.join(process.env.LOCALAPPDATA, 'hermes')
- }
- return path.join(os.homedir(), '.hermes')
-})()
-const VENV_ROOT = path.join(DEFAULT_HERMES_HOME, 'hermes-agent', 'venv')
const FRESH_SANDBOX_ROOT = path.join(os.tmpdir(), 'hermes-desktop-fresh-install')
function die(message) {
@@ -144,12 +131,11 @@ function resolveDmgPath() {
: path.join(RELEASE_ROOT, `Hermes-${PACKAGE_JSON.version}-${ARCH}.dmg`)
}
-function resolveNsisPath() {
- // electron-builder NSIS artifactName template is 'Hermes-${version}-${os}-${arch}.${ext}'
+function resolveMsixPath() {
if (!exists(RELEASE_ROOT)) return null
const candidates = fs
.readdirSync(RELEASE_ROOT)
- .filter(name => /\.exe$/i.test(name) && /win/i.test(name))
+ .filter(name => /\.msix$/i.test(name) && /win/i.test(name))
.sort((a, b) => {
const aMtime = fs.statSync(path.join(RELEASE_ROOT, a)).mtimeMs
const bMtime = fs.statSync(path.join(RELEASE_ROOT, b)).mtimeMs
@@ -160,7 +146,7 @@ function resolveNsisPath() {
function ensureDmg() {
if (PLATFORM !== 'darwin') {
- die('DMG mode is macOS-only; on Windows use the `nsis` mode instead.')
+ die('DMG mode is macOS-only; on Windows use the `msix` mode instead.')
}
if (process.env.HERMES_DESKTOP_SKIP_BUILD === '1' && exists(resolveDmgPath())) {
return
@@ -168,14 +154,14 @@ function ensureDmg() {
run('npm', ['run', 'dist:mac:dmg'])
}
-function ensureNsis() {
+function ensureMsix() {
if (PLATFORM !== 'win32') {
- die('NSIS mode is win32-only; on macOS use the `dmg` mode instead.')
+ die('MSIX mode is win32-only; on macOS use the `dmg` mode instead.')
}
- if (process.env.HERMES_DESKTOP_SKIP_BUILD === '1' && resolveNsisPath()) {
+ if (process.env.HERMES_DESKTOP_SKIP_BUILD === '1' && resolveMsixPath()) {
return
}
- run('npm', ['run', 'dist:win:nsis'])
+ run('npm', ['run', 'dist:win:msix'])
}
function openApp() {
@@ -278,49 +264,50 @@ function launchFresh() {
console.log(` HERMES_HOME: ${hermesHome}`)
console.log(` cwd: ${cwd}`)
- return { runtimeRoot: path.join(hermesHome, 'hermes-agent', 'venv') }
}
-// Validate the packaged bundle matches the thin-installer architecture:
-// - The Hermes Agent Python payload is NOT shipped (it's fetched at first
-// launch via install.ps1's stage protocol).
-// - install-stamp.json IS shipped in resources/ with a valid commit + branch.
-// - node-pty IS shipped inside app.asar.unpacked/dist/node_modules/node-pty
-// with package.json + lib/ + at least one .node binary (the renderer's
-// integrated terminal needs this; see Phase 1F.6).
-// - The renderer's dist/index.html is reachable (either unpacked or
-// inside app.asar).
+// The packaged app must contain the PM payload, node-pty, and renderer assets.
function validateBundle() {
if (!exists(APP.binary)) {
die(`Missing packaged app binary: ${APP.binary}`)
}
- // Negative assertion: the OLD fat-installer factory payload must NOT be
- // present anymore. If a stray ship of hermes_cli sneaks back in we want
- // to fail loudly rather than re-introduce the 400MB delta we just removed.
- const staleFactoryMarker = path.join(APP.resourcesPath, 'hermes-agent', 'hermes_cli', 'main.py')
- if (exists(staleFactoryMarker)) {
- die(
- `Thin-installer regression: factory-payload file should NOT be in the package: ${staleFactoryMarker}`
- )
- }
-
- // Positive assertion: install-stamp.json carries a sane commit + branch
- const stampPath = path.join(APP.resourcesPath, 'install-stamp.json')
- if (!exists(stampPath)) {
- die(`Missing install-stamp.json (required for first-launch bootstrap pinning): ${stampPath}`)
- }
- let stamp
- try {
- stamp = JSON.parse(fs.readFileSync(stampPath, 'utf8'))
- } catch (err) {
- die(`install-stamp.json is not valid JSON: ${err.message}`)
- }
- if (!stamp.commit || typeof stamp.commit !== 'string' || stamp.commit.length < 7) {
- die(`install-stamp.json is missing a usable commit field: ${JSON.stringify(stamp)}`)
+ // The payload may be the real pm bundle (staged by build-bundled-desktop /
+ // `hermes pm bundle --out build/agent-payload`) or the external stub
+ // (plain `npm run pack` in the PR/JS lane — the app fetches the runtime at
+ // first launch via the stage protocol). Validate the payload only when a
+ // real one is present; the stub is the thin-installer contract.
+ const payloadRoot = path.join(APP.resourcesPath, 'agent-payload')
+ const payloadManifestPath = path.join(payloadRoot, 'manifest.json')
+ let payloadManifest = null
+ if (exists(payloadManifestPath)) {
+ try {
+ payloadManifest = JSON.parse(fs.readFileSync(payloadManifestPath, 'utf8'))
+ } catch (err) {
+ die(`Bundled payload manifest is not valid JSON: ${err.message}`)
+ }
}
- if (!stamp.branch || typeof stamp.branch !== 'string') {
- die(`install-stamp.json is missing the branch field: ${JSON.stringify(stamp)}`)
+ if (payloadManifest != null && payloadManifest.external !== true) {
+ for (const key of ['repo', 'store', 'venv']) {
+ if (typeof payloadManifest[key] !== 'string') {
+ die(`Bundled payload manifest is missing ${key}: ${JSON.stringify(payloadManifest)}`)
+ }
+ }
+ const payloadPython = path.join(
+ payloadRoot,
+ payloadManifest.venv,
+ PLATFORM === 'win32' ? 'Scripts' : 'bin',
+ PLATFORM === 'win32' ? 'python.exe' : 'python'
+ )
+ if (!exists(payloadPython)) {
+ die(`Missing bundled payload Python: ${payloadPython}`)
+ }
+ if (PLATFORM === 'win32') {
+ const payloadShim = path.join(payloadRoot, payloadManifest.venv, 'Scripts', 'hermes.exe')
+ if (!exists(payloadShim)) {
+ die(`Missing bundled payload shim: ${payloadShim}`)
+ }
+ }
}
// Positive assertion: node-pty native deps shipped
@@ -360,7 +347,7 @@ function validateBundle() {
// Renderer payload check (either unpacked or in the asar)
if (exists(APP.unpackedDistIndex)) {
- return { stamp, nodeBinaries }
+ return { payloadManifest, nodeBinaries }
}
if (!exists(APP.asarPath)) {
die(`Missing renderer payload: neither ${APP.unpackedDistIndex} nor ${APP.asarPath} exists`)
@@ -373,24 +360,22 @@ function validateBundle() {
if (!normalized.includes('dist/index.html')) {
die(`Missing renderer payload file in app.asar: ${APP.asarPath} (expected dist/index.html)`)
}
- return { stamp, nodeBinaries }
+ return { payloadManifest, nodeBinaries }
}
function printArtifacts(options = {}) {
- const runtimeRoot = options.runtimeRoot || VENV_ROOT
- const stamp = options.stamp
+ const payloadManifest = options.payloadManifest
console.log('\nDesktop artifacts:')
console.log(` app: ${APP.appPath}`)
if (PLATFORM === 'darwin') {
console.log(` dmg: ${resolveDmgPath()}`)
} else if (PLATFORM === 'win32') {
- const exe = resolveNsisPath()
- if (exe) console.log(` installer: ${exe}`)
+ const msix = resolveMsixPath()
+ if (msix) console.log(` package: ${msix}`)
}
- console.log(` runtime: ${runtimeRoot}`)
- if (stamp) {
- console.log(` install-stamp: ${stamp.commit.slice(0, 12)} on ${stamp.branch}`)
+ if (payloadManifest) {
+ console.log(` payload: ${payloadManifest.repo} + ${payloadManifest.venv}`)
}
if (options.nodeBinaries && options.nodeBinaries.length > 0) {
console.log(` node-pty binaries: ${options.nodeBinaries.join(', ')}`)
@@ -402,8 +387,8 @@ function help() {
npm run test:desktop:existing # build packaged app, launch with normal PATH/existing Hermes
npm run test:desktop:fresh # build packaged app, launch with temp userData + HERMES_HOME
npm run test:desktop:dmg # (macOS only) build DMG and open it
- npm run test:desktop:nsis # (win32 only) build NSIS installer
- npm run test:desktop:all # build installer, validate app payload, print paths
+ npm run test:desktop:msix # (win32 only) build MSIX package
+ npm run test:desktop:all # build the platform package and validate the payload
Fast rerun (skip rebuild if the packaged app already exists):
HERMES_DESKTOP_SKIP_BUILD=1 npm run test:desktop:fresh
@@ -425,14 +410,14 @@ if (MODE === 'existing') {
ensureDmg()
openDmg()
printArtifacts()
-} else if (MODE === 'nsis') {
- ensureNsis()
+} else if (MODE === 'msix') {
+ ensureMsix()
printArtifacts(validateBundle())
} else if (MODE === 'all') {
if (PLATFORM === 'darwin') {
ensureDmg()
} else if (PLATFORM === 'win32') {
- ensureNsis()
+ ensureMsix()
} else {
ensurePackagedApp()
}
diff --git a/apps/desktop/scripts/windows-file-version.mjs b/apps/desktop/scripts/windows-file-version.mjs
new file mode 100644
index 00000000000..5c97071b2f4
--- /dev/null
+++ b/apps/desktop/scripts/windows-file-version.mjs
@@ -0,0 +1,42 @@
+// windows-file-version.mjs — the Windows VERSIONINFO quad for a release tag.
+//
+// Windows VERSIONINFO holds four 16-bit fields, so a nightly's semver
+// string cannot go in it. resedit splits whatever it is handed on "." and
+// clamps each token to [0, 65535], so `0.28.0-nightly.20260819171926`
+// becomes 0.28.0.65535: "0-nightly" parses as NaN and falls to the min,
+// and the timestamp saturates at the max. Every nightly of a minor then
+// shows the same meaningless quad on the Details tab.
+//
+// The timestamp is the only part worth showing there — the semver line is
+// identical across a whole nightly series — so pack it as
+// yyyy.mmdd.hhmm.ss. Every field stays under 65536, and the quad compares
+// in timestamp order, which is the order Windows sorts versions in.
+//
+// Display metadata only: electron-updater keys on the semver version in
+// extraMetadata, never on this quad.
+
+/**
+ * The `yyyy.mmdd.hhmm.ss` quad for a nightly tag, or null for a stable tag
+ * (whose version is already four legal fields or fewer, so app-builder-lib's
+ * own handling is correct).
+ *
+ * @param {string} releaseTag A release tag, with the leading `v`.
+ * @returns {string | null}
+ */
+export function windowsFileVersion(releaseTag) {
+ const stamp = /-nightly\.(20\d{6}(?:\d{6})?)$/.exec(String(releaseTag))?.[1]
+ if (!stamp) {
+ return null
+ }
+
+ // The legacy date-only shape (YYYYMMDD) is midnight of that day.
+ const parts = /^(\d{4})(\d{2})(\d{2})(\d{2})?(\d{2})?(\d{2})?$/.exec(stamp)
+ if (!parts) {
+ return null
+ }
+
+ const [, year, month, day, hour, minute, second] = parts
+ const field = (a, b) => Number(`${a ?? '00'}${b ?? '00'}`)
+
+ return `${Number(year)}.${field(month, day)}.${field(hour, minute)}.${Number(second ?? 0)}`
+}
diff --git a/apps/desktop/scripts/windows-file-version.test.mjs b/apps/desktop/scripts/windows-file-version.test.mjs
new file mode 100644
index 00000000000..3dfaafbde24
--- /dev/null
+++ b/apps/desktop/scripts/windows-file-version.test.mjs
@@ -0,0 +1,14 @@
+import assert from 'node:assert/strict'
+import { test } from 'vitest'
+
+import { windowsFileVersion } from './windows-file-version.mjs'
+
+test('stable tags leave VERSIONINFO to electron-builder', () => {
+ assert.equal(windowsFileVersion('v0.20.5'), null)
+ assert.equal(windowsFileVersion('v0.28.0'), null)
+})
+
+test('nightly tags pack the timestamp into a legal quad', () => {
+ assert.equal(windowsFileVersion('v0.28.0-nightly.20260819171926'), '2026.819.1719.26')
+ assert.equal(windowsFileVersion('v0.20.5-nightly.20260826'), '2026.826.0.0')
+})
diff --git a/apps/desktop/src/app/contrib/wiring.tsx b/apps/desktop/src/app/contrib/wiring.tsx
index ac006953b58..f8fbab4418a 100644
--- a/apps/desktop/src/app/contrib/wiring.tsx
+++ b/apps/desktop/src/app/contrib/wiring.tsx
@@ -18,6 +18,7 @@ import { formatRefValue } from '@/components/assistant-ui/directive-text'
import { BootFailureOverlay } from '@/components/boot-failure-overlay'
import { ConfirmHost } from '@/components/confirm-host'
import { DesktopInstallOverlay } from '@/components/desktop-install-overlay'
+import { ExternalOpenFailedDialog } from '@/components/external-open-failed-dialog'
import { FindBar } from '@/components/find-bar'
import { GatewayConnectingOverlay } from '@/components/gateway-connecting-overlay'
import { NotificationStack } from '@/components/notifications'
@@ -1245,6 +1246,10 @@ export function ContribWiring({ children }: { children: ReactNode }) {
(error card action); renders nothing until requested. */}
<SendDiagnosticsHost />
+ {/* Fallback modal when opening an external URL fails — carries the URL
+ so a dead system-browser click is never silent. */}
+ <ExternalOpenFailedDialog />
+
{/* Petdex floating mascot — renders nothing unless installed + enabled.
Never in the HUD: that window is the chat bar and nothing else. */}
{!isHudWindow() && !isBrowserWindow() && <FloatingPet />}
diff --git a/apps/desktop/src/app/settings/about-settings.tsx b/apps/desktop/src/app/settings/about-settings.tsx
index fa358a08dcf..bcc0bada290 100644
--- a/apps/desktop/src/app/settings/about-settings.tsx
+++ b/apps/desktop/src/app/settings/about-settings.tsx
@@ -1,209 +1,53 @@
import { useStore } from '@nanostores/react'
-import { useEffect, useState } from 'react'
+import { useEffect } from 'react'
-import { BrandMark } from '@/components/brand-mark'
-import { Button } from '@/components/ui/button'
-import { Codicon } from '@/components/ui/codicon'
-import { type Translations, useI18n } from '@/i18n'
-import { AlertTriangle, CheckCircle2, ExternalLink, Loader2, RefreshCw } from '@/lib/icons'
-import { cn } from '@/lib/utils'
-import {
- $desktopVersion,
- $updateApply,
- $updateChecking,
- $updateStatus,
- checkUpdates,
- openUpdatesWindow,
- refreshDesktopVersion,
- startActiveUpdate
-} from '@/store/updates'
+import { UpdateStatusCard, VersionHero } from '@/components/update-status'
+import { VersionDetails } from '@/components/version-details'
+import { useI18n } from '@/i18n'
+import { RefreshCw } from '@/lib/icons'
+import { $connection } from '@/store/session'
+import { $desktopVersion, checkBackendUpdates, refreshDesktopVersion } from '@/store/updates'
-import { ListRow, SectionHeading, SettingsContent } from './primitives'
+import { SectionHeading, SettingsContent } from './primitives'
import { UninstallSection } from './uninstall-section'
-const RELEASE_NOTES_URL = 'https://github.com/NousResearch/hermes-agent/releases'
-const INSTALLER_URL = 'https://hermes-agent.nousresearch.com/'
-
-function relativeTime(ms: number | undefined, a: Translations['settings']['about']) {
- if (!ms) {
- return a.never
- }
-
- const diff = Date.now() - ms
-
- if (diff < 60_000) {
- return a.justNow
- }
-
- if (diff < 3_600_000) {
- return a.minAgo(Math.round(diff / 60_000))
- }
-
- if (diff < 86_400_000) {
- return a.hoursAgo(Math.round(diff / 3_600_000))
- }
-
- return a.daysAgo(Math.round(diff / 86_400_000))
-}
-
export function AboutSettings() {
const { t } = useI18n()
- const a = t.settings.about
+ const u = t.updates
const version = useStore($desktopVersion)
- const status = useStore($updateStatus)
- const apply = useStore($updateApply)
- const checking = useStore($updateChecking)
- const [justChecked, setJustChecked] = useState(false)
+ const connection = useStore($connection)
+ const remote = connection?.mode === 'remote'
// The version atom is loaded once at app boot, which makes About show a
// stale number after a self-update (the running binary is current, the
// displayed string is not). Re-read on mount so opening About always
- // reflects the running build.
+ // reflects the running build. In remote mode also seed the backend update
+ // state so the backend card opens answered instead of on "never checked".
useEffect(() => {
void refreshDesktopVersion()
- }, [])
-
- const behind = status?.behind ?? 0
- // behind is null when the exact count is unknowable (shallow clone): the
- // backend flags that case via updateAvailable instead of a number.
- const updateAvailable = behind > 0 || Boolean(status?.updateAvailable)
- const supported = status?.supported !== false
- const applying = apply.applying || apply.stage === 'restart'
- const handleCheck = async () => {
- setJustChecked(false)
- const next = await checkUpdates()
- setJustChecked(Boolean(next))
- }
-
- let statusLine: string
- let statusTone: 'idle' | 'available' | 'error' = 'idle'
-
- if (!supported) {
- statusLine = status?.message ?? a.cantUpdate
- statusTone = 'error'
- } else if (status?.error) {
- statusLine = a.cantReach
- statusTone = 'error'
- } else if (applying) {
- statusLine = a.installing
- statusTone = 'available'
- } else if (updateAvailable) {
- statusLine = behind > 0 ? a.updateReady(behind) : a.updateReadyUnknown
- statusTone = 'available'
- } else if (status) {
- statusLine = a.onLatest
- } else {
- statusLine = a.tapCheck
- }
+ if (remote) {
+ void checkBackendUpdates()
+ }
+ }, [remote])
return (
<SettingsContent>
- <div className="flex flex-col items-center gap-3 pt-6 pb-2 text-center">
- <BrandMark className="size-16" />
- <div>
- <h2 className="text-lg font-semibold tracking-tight">{a.heading}</h2>
- <p className="mt-1 text-xs text-muted-foreground">
- {version?.appVersion ? a.version(version.appVersion) : a.versionUnavailable}
- </p>
- </div>
- {version?.bundleOutOfSync && (
- <div className="mx-auto w-full max-w-2xl rounded-xl border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-left text-sm">
- <div className="flex items-start gap-2">
- <AlertTriangle className="mt-0.5 size-4 shrink-0 text-amber-600 dark:text-amber-400" />
- <div className="min-w-0">
- <p className="font-medium">{a.bundleOutOfSync}</p>
- <p className="mt-1 text-xs text-muted-foreground">{a.bundleOutOfSyncDesc}</p>
- <Button asChild className="mt-2" size="sm" variant="textStrong">
- <a
- href={INSTALLER_URL}
- onClick={event => {
- event.preventDefault()
- void window.hermesDesktop?.openExternal?.(INSTALLER_URL)
- }}
- rel="noreferrer"
- target="_blank"
- >
- <ExternalLink className="size-3" />
- {a.bundleOutOfSyncAction}
- </a>
- </Button>
- </div>
- </div>
- </div>
- )}
- </div>
+ <VersionHero version={version} />
<div className="mx-auto mt-4 w-full max-w-2xl">
- <SectionHeading icon={RefreshCw} title={a.updates} />
-
- <div
- className={cn(
- 'rounded-xl border px-4 py-3 text-sm',
- statusTone === 'available' && 'border-primary/30 bg-primary/5 text-foreground',
- statusTone === 'error' && 'border-destructive/35 bg-destructive/5 text-destructive',
- statusTone === 'idle' && 'border-border/70 bg-muted/20 text-foreground'
- )}
- >
- <div className="flex items-start gap-2">
- {statusTone === 'available' ? (
- <Codicon className="mt-0.5 size-4 shrink-0 text-primary" name="cloud-download" size="1rem" />
- ) : statusTone === 'error' ? null : (
- <CheckCircle2 className="mt-0.5 size-4 shrink-0 text-emerald-600 dark:text-emerald-400" />
- )}
- <div className="min-w-0">
- <p className="font-medium">{statusLine}</p>
- <p className="mt-1 text-xs text-muted-foreground">
- {a.lastChecked(relativeTime(status?.fetchedAt, a))}
- {justChecked && !checking ? a.justNowSuffix : ''}
- </p>
- </div>
- </div>
-
- <div className="mt-3 flex flex-wrap items-center gap-4">
- <Button
- disabled={checking || applying || !supported}
- onClick={() => void handleCheck()}
- size="sm"
- variant="textStrong"
- >
- {checking ? <Loader2 className="size-3 animate-spin" /> : <RefreshCw className="size-3" />}
- {checking ? a.checking : a.checkNow}
- </Button>
-
- {updateAvailable && supported && !applying && (
- <>
- <Button onClick={() => startActiveUpdate()} size="sm">
- {a.updateNow}
- </Button>
- <Button onClick={() => openUpdatesWindow()} size="sm" variant="textStrong">
- {a.seeWhatsNew}
- </Button>
- </>
- )}
-
- <Button asChild className="ml-auto" size="sm" variant="text">
- <a
- href={RELEASE_NOTES_URL}
- onClick={event => {
- event.preventDefault()
- void window.hermesDesktop?.openExternal?.(RELEASE_NOTES_URL)
- }}
- rel="noreferrer"
- target="_blank"
- >
- <ExternalLink className="size-3" />
- {a.releaseNotes}
- </a>
- </Button>
- </div>
+ <SectionHeading icon={RefreshCw} title={u.updatesSection} />
+
+ <div className="grid gap-3">
+ <UpdateStatusCard target="client" />
+ {/* The desktop client and a remote backend update independently — in
+ remote mode the statusbar shows both pills, so About shows both
+ states too. The backend has no GitHub release notes link of its
+ own; the client card already carries it. */}
+ {remote && <UpdateStatusCard showReleaseNotes={false} target="backend" />}
</div>
- <ListRow
- description={a.automaticUpdatesDesc}
- hint={a.branchCommit(status?.branch ?? 'unknown', status?.currentSha?.slice(0, 7) ?? 'unknown')}
- title={a.automaticUpdates}
- />
+ {version && <VersionDetails version={version} />}
<UninstallSection />
</div>
diff --git a/apps/desktop/src/app/settings/connections-registry.tsx b/apps/desktop/src/app/settings/connections-registry.tsx
index 3cfdbfe963a..765f9ecd1bc 100644
--- a/apps/desktop/src/app/settings/connections-registry.tsx
+++ b/apps/desktop/src/app/settings/connections-registry.tsx
@@ -348,7 +348,9 @@ export function ConnectionsRegistrySection() {
notify({
kind: 'warning',
title: t.boot.failure.signInIncompleteTitle,
- message: t.boot.failure.signInIncompleteMessage
+ message: result?.error
+ ? `${t.boot.failure.signInIncompleteMessage}: ${result.error}`
+ : t.boot.failure.signInIncompleteMessage
})
}
} catch (err) {
diff --git a/apps/desktop/src/app/settings/gateway-settings.tsx b/apps/desktop/src/app/settings/gateway-settings.tsx
index 4de24c278c5..9061f6a1bd8 100644
--- a/apps/desktop/src/app/settings/gateway-settings.tsx
+++ b/apps/desktop/src/app/settings/gateway-settings.tsx
@@ -622,7 +622,9 @@ export function GatewaySettings({ embedded = false }: { embedded?: boolean } = {
notify({
kind: 'warning',
title: t.boot.failure.signInIncompleteTitle,
- message: t.boot.failure.signInIncompleteMessage
+ message: result?.error
+ ? `${t.boot.failure.signInIncompleteMessage}: ${result.error}`
+ : t.boot.failure.signInIncompleteMessage
})
}
} catch (err) {
diff --git a/apps/desktop/src/app/updates-overlay.tsx b/apps/desktop/src/app/updates-overlay.tsx
index b797a4f031a..49fee008d08 100644
--- a/apps/desktop/src/app/updates-overlay.tsx
+++ b/apps/desktop/src/app/updates-overlay.tsx
@@ -14,7 +14,16 @@ import {
import { ErrorIcon, ErrorState } from '@/components/ui/error-state'
import { Loader } from '@/components/ui/loader'
import { Progress } from '@/components/ui/progress'
-import type { DesktopUpdateBlocker, DesktopUpdateCommit, DesktopUpdateStage, DesktopUpdateStatus } from '@/global'
+import { UpdateStatusCard, VersionHero } from '@/components/update-status'
+import { VersionDetails } from '@/components/version-details'
+import type {
+ DesktopUpdateBlocker,
+ DesktopUpdateCommit,
+ DesktopUpdateStage,
+ DesktopUpdateStatus,
+ DesktopVersionInfo,
+ UpdaterMechanismClient
+} from '@/global'
import { useI18n } from '@/i18n'
import { buildCommitChangelog, type CommitGroup } from '@/lib/commit-changelog'
import { AlertCircle, Check, Copy, Terminal } from '@/lib/icons'
@@ -24,6 +33,7 @@ import {
$backendUpdateApply,
$backendUpdateChecking,
$backendUpdateStatus,
+ $desktopVersion,
$updateApply,
$updateChecking,
$updateOverlayOpen,
@@ -52,6 +62,7 @@ export function UpdatesOverlay() {
const backendStatus = useStore($backendUpdateStatus)
const backendChecking = useStore($backendUpdateChecking)
const backendApply = useStore($backendUpdateApply)
+ const desktopVersion = useStore($desktopVersion)
const isBackend = target === 'backend'
const status = isBackend ? backendStatus : clientStatus
@@ -111,7 +122,9 @@ export function UpdatesOverlay() {
onOpenAutoFocus={preventCloseButtonAutoFocus}
showCloseButton={phase !== 'applying'}
>
- {phase === 'applying' && <ApplyingView apply={apply} isBackend={isBackend} />}
+ {phase === 'applying' && (
+ <ApplyingView apply={apply} isBackend={isBackend} statusMechanism={status?.mechanism} />
+ )}
{phase === 'manual' && (
<ManualView command={apply.command ?? null} message={apply.message} onDone={() => handleClose(false)} />
@@ -142,6 +155,7 @@ export function UpdatesOverlay() {
status={status}
target={target}
updateAvailable={updateAvailable}
+ version={desktopVersion}
/>
)}
</DialogContent>
@@ -158,7 +172,8 @@ function IdleView({
onRetryCheck,
status,
target,
- updateAvailable
+ updateAvailable,
+ version
}: {
behind: number
checking: boolean
@@ -169,6 +184,7 @@ function IdleView({
status: DesktopUpdateStatus | null
target: UpdateTarget
updateAvailable: boolean
+ version: DesktopVersionInfo | null
}) {
const { t } = useI18n()
const u = t.updates
@@ -196,38 +212,50 @@ function IdleView({
)
}
- if (!status.supported) {
- return (
- <CenteredStatus
- body={status.message ?? u.unsupportedMessage}
- icon={<AlertCircle className="size-6 text-muted-foreground" />}
- title={u.notAvailableTitle}
- />
- )
- }
+ const details = version ? <VersionDetails version={version} /> : null
- if (status.error) {
+ // App-installer check-unknown (OS checker unavailable): NOT "no updates"
+ // and NOT a generic error — the OS also installs updates automatically on
+ // restart (it re-reads the .appinstaller feed on every launch), so the
+ // honest view names that path. Only this mechanism gets it.
+ if (status.mechanism === 'app-installer' && status.error && !status.updateAvailable) {
return (
- <CenteredStatus
- action={
- <Button disabled={checking} onClick={onRetryCheck} size="sm">
- {u.tryAgain}
- </Button>
- }
- body={u.connectionRetry}
- icon={<ErrorIcon />}
- title={u.checkFailedTitle}
- />
+ <div className="grid gap-4 px-6 pb-6 pt-1 pr-8">
+ <VersionHero
+ renderHeading={heading => (
+ <DialogTitle className="text-lg font-semibold tracking-tight">{heading}</DialogTitle>
+ )}
+ version={version}
+ />
+ <div className="flex flex-col items-center gap-2 text-center">
+ <AlertCircle className="size-6 text-muted-foreground" />
+ <p className="text-sm font-medium">{u.checkUnknownTitleAppInstaller}</p>
+ <p className="max-w-prose text-sm leading-5 text-muted-foreground">{u.checkUnknownBodyAppInstaller}</p>
+ </div>
+ <Button onClick={onRetryCheck} size="sm">
+ {u.tryAgain}
+ </Button>
+ {details}
+ </div>
)
}
- if (!updateAvailable) {
+ // Everything that is NOT the install pitch — unsupported, check error, and
+ // already-latest — is exactly the About page's state: render the shared
+ // hero + status card so the two surfaces cannot drift. The card owns the
+ // check/retry actions (its "Check now" covers the old Try-again button).
+ if (!status.supported || status.error || !updateAvailable) {
return (
- <CenteredStatus
- body={target === 'backend' ? u.latestBodyBackend : u.latestBody}
- icon={<BrandMark className="size-12" />}
- title={u.allSetTitle}
- />
+ <div className="grid gap-4 px-6 pb-6 pt-1 pr-8">
+ <VersionHero
+ renderHeading={heading => (
+ <DialogTitle className="text-lg font-semibold tracking-tight">{heading}</DialogTitle>
+ )}
+ version={version}
+ />
+ <UpdateStatusCard target={target} />
+ {details}
+ </div>
)
}
@@ -238,8 +266,16 @@ function IdleView({
// Name what's being updated. In remote mode the overlay acts on the connected
// backend, not the local client — say so. When there are no commit rows to
// show (e.g. pip/non-git backend), degrade to honest "no release notes" copy
- // instead of generic filler.
- const { title, body } = resolveUpdateCopy({ target, shownItems, copy: u })
+ // instead of generic filler. On a release-feed channel (stable), name the
+ // release tag instead of commit vocabulary.
+ const { title, body } = resolveUpdateCopy({
+ target,
+ shownItems,
+ channel: status?.channel === 'stable' ? 'stable' : 'main',
+ latestTag: status?.latestTag ?? null,
+ mechanism: status?.mechanism,
+ copy: u
+ })
return (
<div className="grid gap-5 px-6 pb-6 pt-7 pr-8">
@@ -382,11 +418,24 @@ function GuiSkewView({ message, onDone }: { message?: string; onDone: () => void
)
}
-function ApplyingView({ apply, isBackend }: { apply: UpdateApplyState; isBackend: boolean }) {
+function ApplyingView({
+ apply,
+ isBackend,
+ statusMechanism
+}: {
+ apply: UpdateApplyState
+ isBackend: boolean
+ statusMechanism?: UpdaterMechanismClient
+}) {
const { t } = useI18n()
const u = t.updates
const label = u.stages[apply.stage as DesktopUpdateStage] ?? u.stages.idle
- const body = isBackend ? u.applyingBodyBackend : u.applyingBody
+ const isAppInstaller = statusMechanism === 'app-installer'
+ const body = isAppInstaller
+ ? u.applyingBodyAppInstaller
+ : isBackend
+ ? u.applyingBodyBackend
+ : u.applyingBody
const currentMessage = apply.message.trim()
const recentLog = apply.log.slice(-4)
diff --git a/apps/desktop/src/components/boot-failure-overlay.test.tsx b/apps/desktop/src/components/boot-failure-overlay.test.tsx
index fedfdd2b57e..37e432146eb 100644
--- a/apps/desktop/src/components/boot-failure-overlay.test.tsx
+++ b/apps/desktop/src/components/boot-failure-overlay.test.tsx
@@ -29,7 +29,23 @@ function stubDesktop(config: Record<string, unknown>, overrides: Record<string,
const original = window.hermesDesktop
Object.defineProperty(window, 'hermesDesktop', {
configurable: true,
- value: { getRecentLogs: async () => ({ lines: [] }), getConnectionConfig: async () => config, ...overrides }
+ value: {
+ getRecentLogs: async () => ({ lines: [] }),
+ getConnectionConfig: async () => config,
+ getBootstrapState: async () => ({
+ active: false,
+ manifest: null,
+ stages: {},
+ error: null,
+ log: [],
+ startedAt: null,
+ completedAt: null,
+ setupChoice: null,
+ unsupportedPlatform: null,
+ bundled: false
+ }),
+ ...overrides
+ }
})
return () => Object.defineProperty(window, 'hermesDesktop', { configurable: true, value: original })
@@ -227,4 +243,42 @@ describe('BootFailureOverlay', () => {
restore()
}
})
+
+ it('swaps Repair for "Reinstall the app" on a bundled install', async () => {
+ const openExternal = vi.fn().mockResolvedValue(undefined)
+
+ const restore = stubDesktop(
+ { mode: 'local' },
+ {
+ getBootstrapState: async () => ({
+ active: false,
+ manifest: null,
+ stages: {},
+ error: null,
+ log: [],
+ startedAt: null,
+ completedAt: null,
+ setupChoice: null,
+ unsupportedPlatform: null,
+ bundled: true
+ }),
+ openExternal
+ }
+ )
+
+ try {
+ render(<BootFailureOverlay />)
+
+ // The bundled artifact has no installer to repair with — the action is
+ // a docs link, and the hint says reinstall instead of re-run installer.
+ expect(await screen.findByRole('button', { name: /reinstall the app/i })).toBeTruthy()
+ expect(screen.queryByRole('button', { name: /repair install/i })).toBeNull()
+ expect(screen.getByText(/reinstall the app to restore/i)).toBeTruthy()
+
+ fireEvent.click(screen.getByRole('button', { name: /reinstall the app/i }))
+ await waitFor(() => expect(openExternal).toHaveBeenCalledWith('https://hermes-agent.nousresearch.com/docs/user-guide/desktop'))
+ } finally {
+ restore()
+ }
+ })
})
diff --git a/apps/desktop/src/components/boot-failure-overlay.tsx b/apps/desktop/src/components/boot-failure-overlay.tsx
index 10da60a2765..c3186c0d244 100644
--- a/apps/desktop/src/components/boot-failure-overlay.tsx
+++ b/apps/desktop/src/components/boot-failure-overlay.tsx
@@ -7,6 +7,7 @@ import { Loader } from '@/components/ui/loader'
import { LogView } from '@/components/ui/log-view'
import type { DesktopConnectionConfig } from '@/global'
import { useI18n } from '@/i18n'
+import { DESKTOP_DOCS_URL } from '@/lib/docs'
import { openExternalLink } from '@/lib/external-link'
import { ChevronLeft, ExternalLink, FileText, Loader2, LogIn, RefreshCw, SlidersHorizontal, Wrench } from '@/lib/icons'
import { $desktopBoot } from '@/store/boot'
@@ -55,6 +56,10 @@ export function BootFailureOverlay() {
// A remote/cloud backend that failed to boot is fixable from gateway settings,
// so the escape hatch earns emphasis (local failures keep it as a quiet ghost).
const [remoteFailure, setRemoteFailure] = useState(false)
+ // A bundled install (payload ships in-app) has no installer to repair with —
+ // the only recovery is reinstalling the app. Read from the bootstrap state
+ // snapshot so the Repair affordance is replaced by "Reinstall the app".
+ const [bundled, setBundled] = useState(false)
// Swap the card body to the embedded Gateway settings panel in place of routing
// to the full Settings page (keeps the user on the recovery surface, no z-index
// juggling, no second connection form to maintain).
@@ -77,6 +82,31 @@ export function BootFailureOverlay() {
.catch(() => undefined)
}, [boot.error, visible])
+ // Bundled installs carry their runtime as an immutable payload — repair
+ // would re-run an installer that must never fire for them. Resolve the
+ // artifact kind from the bootstrap snapshot (set by main.ts on setup-choice
+ // broadcast) so the recovery actions swap Repair → "Reinstall the app".
+ useEffect(() => {
+ if (!visible) {
+ return
+ }
+
+ let cancelled = false
+
+ void window.hermesDesktop
+ ?.getBootstrapState()
+ .then(snapshot => {
+ if (!cancelled && snapshot) {
+ setBundled(snapshot.bundled)
+ }
+ })
+ .catch(() => undefined)
+
+ return () => {
+ cancelled = true
+ }
+ }, [boot.error, visible])
+
// Resolve whether this boot failure is a remote-gateway reauth so we can
// offer the actionable "Sign in" path instead of the local-only recovery
// buttons. Runs whenever the overlay becomes visible.
@@ -221,7 +251,9 @@ export function BootFailureOverlay() {
notify({
kind: 'warning',
title: t.boot.failure.signInIncompleteTitle,
- message: t.boot.failure.signInIncompleteMessage
+ message: result?.error
+ ? `${t.boot.failure.signInIncompleteMessage}: ${result.error}`
+ : t.boot.failure.signInIncompleteMessage
})
} catch (err) {
notifyError(err, t.boot.failure.signInFailed)
@@ -329,19 +361,29 @@ export function BootFailureOverlay() {
} else {
// Local failure: Use-local is redundant with Retry (both re-target local), so
// it's dropped here; keep it for remote failures where it's the fall-back.
+ // On a bundled install the Repair affordance is replaced by "Reinstall the
+ // app" — the payload is immutable, so there is no installer to re-run.
actions = [
retryAction,
- {
- key: 'repair',
- label: copy.repairInstall,
- onClick: () => void repair(),
- icon: <Wrench />,
- variant: 'secondary',
- busy: 'repair'
- },
+ bundled
+ ? {
+ key: 'reinstall',
+ label: copy.reinstallApp,
+ onClick: () => openExternalLink(DESKTOP_DOCS_URL),
+ icon: <ExternalLink />,
+ variant: 'secondary'
+ }
+ : {
+ key: 'repair',
+ label: copy.repairInstall,
+ onClick: () => void repair(),
+ icon: <Wrench />,
+ variant: 'secondary',
+ busy: 'repair'
+ },
{ ...settingsAction, variant: 'ghost' }
]
- hint = copy.repairHint
+ hint = bundled ? copy.bundledReinstallHint : copy.repairHint
}
if (view === 'connect') {
diff --git a/apps/desktop/src/components/desktop-install-local-card.test.ts b/apps/desktop/src/components/desktop-install-local-card.test.ts
new file mode 100644
index 00000000000..cd6458f52d4
--- /dev/null
+++ b/apps/desktop/src/components/desktop-install-local-card.test.ts
@@ -0,0 +1,46 @@
+import assert from 'node:assert/strict'
+
+import { test } from 'vitest'
+
+import { localCardPresentation } from './desktop-install-local-card'
+
+test('none is the installer offer with the install-to footer', () => {
+ assert.deepEqual(localCardPresentation('none'), {
+ title: 'installLocalTitle',
+ desc: 'installLocalDesc',
+ disabled: false,
+ showInstallTo: true
+ })
+})
+
+test('installed uses the existing-runtime copy and hides the install-to footer', () => {
+ assert.deepEqual(localCardPresentation('installed'), {
+ title: 'useLocalTitle',
+ desc: 'useLocalDesc',
+ disabled: false,
+ showInstallTo: false
+ })
+})
+
+test('bundled uses the bundled flavor of the existing-runtime copy', () => {
+ assert.deepEqual(localCardPresentation('bundled'), {
+ title: 'useLocalTitle',
+ desc: 'bundledLocalDesc',
+ disabled: false,
+ showInstallTo: false
+ })
+})
+
+test('bundled-damaged is disabled and never shows the install-to footer', () => {
+ assert.deepEqual(localCardPresentation('bundled-damaged'), {
+ title: 'bundledDamagedTitle',
+ desc: 'bundledDamagedDesc',
+ disabled: true,
+ showInstallTo: false
+ })
+})
+
+test('an absent local field falls back to the installer offer (old backends)', () => {
+ assert.equal(localCardPresentation(undefined).title, 'installLocalTitle')
+ assert.equal(localCardPresentation(undefined).disabled, false)
+})
diff --git a/apps/desktop/src/components/desktop-install-local-card.ts b/apps/desktop/src/components/desktop-install-local-card.ts
new file mode 100644
index 00000000000..cbb0036ea61
--- /dev/null
+++ b/apps/desktop/src/components/desktop-install-local-card.ts
@@ -0,0 +1,69 @@
+/**
+ * desktop-install-local-card.ts
+ *
+ * Pure presentation derivation for the setup screen's local card. The card
+ * has four states, keyed off the `local` field the backend stamps on every
+ * resolved backend:
+ *
+ * none — no Hermes on this machine: the card IS an install offer.
+ * installed — a runtime resolved (PATH hermes, active root, …): clicking
+ * starts the existing runtime; nothing downloads.
+ * bundled — a healthy bundled install: the payload is the runtime.
+ * bundled-damaged— a bundled install whose payload failed to resolve: the
+ * card is disabled (never an install action); reinstall the
+ * app instead.
+ *
+ * Extracted so the disabled/title/desc/footer logic is unit-testable without
+ * rendering the overlay.
+ */
+
+export type LocalCardState = 'none' | 'installed' | 'bundled' | 'bundled-damaged'
+
+export interface LocalCardPresentation {
+ /** i18n key into `t.install` for the card title. */
+ title: 'installLocalTitle' | 'useLocalTitle' | 'bundledDamagedTitle'
+ /** i18n key into `t.install` for the card body. */
+ desc: 'installLocalDesc' | 'useLocalDesc' | 'bundledLocalDesc' | 'bundledDamagedDesc'
+ /** When true the card cannot be clicked — there is no install to fire. */
+ disabled: boolean
+ /** Whether the "Will install to <root>" footer is accurate for this state. */
+ showInstallTo: boolean
+}
+
+export function localCardPresentation(local: LocalCardState | undefined): LocalCardPresentation {
+ switch (local) {
+ case 'installed':
+ return {
+ title: 'useLocalTitle',
+ desc: 'useLocalDesc',
+ disabled: false,
+ showInstallTo: false
+ }
+
+ case 'bundled':
+ return {
+ title: 'useLocalTitle',
+ desc: 'bundledLocalDesc',
+ disabled: false,
+ showInstallTo: false
+ }
+
+ case 'bundled-damaged':
+ return {
+ title: 'bundledDamagedTitle',
+ desc: 'bundledDamagedDesc',
+ disabled: true,
+ showInstallTo: false
+ }
+
+ case 'none':
+
+ default:
+ return {
+ title: 'installLocalTitle',
+ desc: 'installLocalDesc',
+ disabled: false,
+ showInstallTo: true
+ }
+ }
+}
diff --git a/apps/desktop/src/components/desktop-install-overlay.test.tsx b/apps/desktop/src/components/desktop-install-overlay.test.tsx
index 1e4e384cb11..e5887622eff 100644
--- a/apps/desktop/src/components/desktop-install-overlay.test.tsx
+++ b/apps/desktop/src/components/desktop-install-overlay.test.tsx
@@ -17,6 +17,7 @@ function bootstrapState(overrides: Partial<DesktopBootstrapState> = {}): Desktop
completedAt: null,
setupChoice: null,
unsupportedPlatform: null,
+ bundled: false,
...overrides
}
}
@@ -93,7 +94,7 @@ describe('DesktopInstallOverlay first-run setup', () => {
it('shows the remote/local choice without installer progress', async () => {
installDesktopMock(
bootstrapState({
- setupChoice: { platform: 'win32', activeRoot: 'C:\\Users\\me\\AppData\\Local\\hermes\\hermes-agent' }
+ setupChoice: { platform: 'win32', activeRoot: 'C:\\Users\\me\\AppData\\Local\\hermes\\hermes-agent', local: 'none', bundled: false }
})
)
@@ -102,6 +103,7 @@ describe('DesktopInstallOverlay first-run setup', () => {
expect(await screen.findByText('Set up Hermes Desktop')).toBeTruthy()
expect(screen.getByText('Connect to existing Hermes')).toBeTruthy()
expect(screen.getByText('Install Hermes locally')).toBeTruthy()
+ expect(screen.getByText(/Will install to/i)).toBeTruthy()
expect(screen.queryByText(/steps complete/i)).toBeNull()
expect(screen.queryByText(/Fetching installer manifest/i)).toBeNull()
})
@@ -109,7 +111,7 @@ describe('DesktopInstallOverlay first-run setup', () => {
it('continues local bootstrap only when Install Hermes locally is selected', async () => {
const desktop = installDesktopMock(
bootstrapState({
- setupChoice: { platform: 'win32', activeRoot: 'C:\\Users\\me\\AppData\\Local\\hermes\\hermes-agent' }
+ setupChoice: { platform: 'win32', activeRoot: 'C:\\Users\\me\\AppData\\Local\\hermes\\hermes-agent', local: 'none', bundled: false }
})
)
@@ -131,7 +133,7 @@ describe('DesktopInstallOverlay first-run setup', () => {
it('surfaces a recoverable error when the local-bootstrap bridge is unavailable', async () => {
const desktop = installDesktopMock(
bootstrapState({
- setupChoice: { platform: 'win32', activeRoot: 'C:\\Users\\me\\AppData\\Local\\hermes\\hermes-agent' }
+ setupChoice: { platform: 'win32', activeRoot: 'C:\\Users\\me\\AppData\\Local\\hermes\\hermes-agent', local: 'none', bundled: false }
})
)
@@ -150,7 +152,7 @@ describe('DesktopInstallOverlay first-run setup', () => {
it('keeps the local-start error when the first snapshot commits under the click', async () => {
const desktop = installDesktopMock(
bootstrapState({
- setupChoice: { platform: 'win32', activeRoot: 'C:\\Users\\me\\AppData\\Local\\hermes\\hermes-agent' }
+ setupChoice: { platform: 'win32', activeRoot: 'C:\\Users\\me\\AppData\\Local\\hermes\\hermes-agent', local: 'none', bundled: false }
})
)
@@ -173,7 +175,7 @@ describe('DesktopInstallOverlay first-run setup', () => {
it('clears a stale local-start error when a repair presents a different root', async () => {
const desktop = installDesktopMock(
bootstrapState({
- setupChoice: { platform: 'win32', activeRoot: 'C:\\Users\\me\\AppData\\Local\\hermes\\hermes-agent' }
+ setupChoice: { platform: 'win32', activeRoot: 'C:\\Users\\me\\AppData\\Local\\hermes\\hermes-agent', local: 'none', bundled: false }
})
)
@@ -200,7 +202,7 @@ describe('DesktopInstallOverlay first-run setup', () => {
it('opens the remote connection form from the first-run choice', async () => {
installDesktopMock(
bootstrapState({
- setupChoice: { platform: 'linux', activeRoot: '/home/me/.hermes/hermes-agent' }
+ setupChoice: { platform: 'linux', activeRoot: '/home/me/.hermes/hermes-agent', local: 'none', bundled: false }
})
)
@@ -216,7 +218,7 @@ describe('DesktopInstallOverlay first-run setup', () => {
it('returns from the remote connection form to the first-run choice', async () => {
installDesktopMock(
bootstrapState({
- setupChoice: { platform: 'linux', activeRoot: '/home/me/.hermes/hermes-agent' }
+ setupChoice: { platform: 'linux', activeRoot: '/home/me/.hermes/hermes-agent', local: 'none', bundled: false }
})
)
@@ -234,7 +236,7 @@ describe('DesktopInstallOverlay first-run setup', () => {
it('requires a successful token connection test before applying remote config', async () => {
const desktop = installDesktopMock(
bootstrapState({
- setupChoice: { platform: 'linux', activeRoot: '/home/me/.hermes/hermes-agent' }
+ setupChoice: { platform: 'linux', activeRoot: '/home/me/.hermes/hermes-agent', local: 'none', bundled: false }
})
)
@@ -304,7 +306,7 @@ describe('DesktopInstallOverlay first-run setup', () => {
it('ignores a completed probe after the gateway URL becomes invalid', async () => {
const desktop = installDesktopMock(
bootstrapState({
- setupChoice: { platform: 'linux', activeRoot: '/home/me/.hermes/hermes-agent' }
+ setupChoice: { platform: 'linux', activeRoot: '/home/me/.hermes/hermes-agent', local: 'none', bundled: false }
})
)
@@ -348,7 +350,7 @@ describe('DesktopInstallOverlay first-run setup', () => {
it('does not enable Apply when credentials change during a connection test', async () => {
const desktop = installDesktopMock(
bootstrapState({
- setupChoice: { platform: 'linux', activeRoot: '/home/me/.hermes/hermes-agent' }
+ setupChoice: { platform: 'linux', activeRoot: '/home/me/.hermes/hermes-agent', local: 'none', bundled: false }
})
)
@@ -401,7 +403,7 @@ describe('DesktopInstallOverlay first-run setup', () => {
it('restores remote apply controls when applying the tested connection fails', async () => {
const desktop = installDesktopMock(
bootstrapState({
- setupChoice: { platform: 'linux', activeRoot: '/home/me/.hermes/hermes-agent' }
+ setupChoice: { platform: 'linux', activeRoot: '/home/me/.hermes/hermes-agent', local: 'none', bundled: false }
})
)
@@ -448,7 +450,7 @@ describe('DesktopInstallOverlay first-run setup', () => {
it('signs in, tests, and applies a password-style remote gateway', async () => {
const desktop = installDesktopMock(
bootstrapState({
- setupChoice: { platform: 'linux', activeRoot: '/home/me/.hermes/hermes-agent' }
+ setupChoice: { platform: 'linux', activeRoot: '/home/me/.hermes/hermes-agent', local: 'none', bundled: false }
})
)
@@ -574,3 +576,81 @@ describe('DesktopInstallOverlay first-run setup', () => {
expect(screen.queryByText('Hermes needs a one-time install')).toBeNull()
})
})
+
+describe('DesktopInstallOverlay bundled / already-installed cards', () => {
+ it('shows the use-existing card for an installed runtime and hides the install-to footer', async () => {
+ installDesktopMock(
+ bootstrapState({
+ setupChoice: {
+ platform: 'win32',
+ activeRoot: 'C:\\Users\\me\\AppData\\Local\\hermes\\hermes-agent',
+ local: 'installed',
+ bundled: false
+ }
+ })
+ )
+
+ render(<DesktopInstallOverlay />)
+
+ expect(await screen.findByText('Use Hermes on this computer')).toBeTruthy()
+ expect(screen.getByText(/already installed here/i)).toBeTruthy()
+ expect(screen.queryByText(/Will install to/i)).toBeNull()
+ expect(screen.queryByText('Install Hermes locally')).toBeNull()
+ })
+
+ it('shows the bundled flavor for a healthy bundled install', async () => {
+ installDesktopMock(
+ bootstrapState({
+ setupChoice: {
+ platform: 'win32',
+ activeRoot: 'C:\\Users\\me\\AppData\\Local\\hermes\\hermes-agent',
+ local: 'bundled',
+ bundled: true
+ }
+ })
+ )
+
+ render(<DesktopInstallOverlay />)
+
+ expect(await screen.findByText('Use Hermes on this computer')).toBeTruthy()
+ expect(screen.getByText(/included with this app/i)).toBeTruthy()
+ expect(screen.queryByText(/Will install to/i)).toBeNull()
+ })
+
+ it('disables the local card for a damaged bundled payload — never an install action', async () => {
+ const desktop = installDesktopMock(
+ bootstrapState({
+ setupChoice: {
+ platform: 'win32',
+ activeRoot: 'C:\\Users\\me\\AppData\\Local\\hermes\\hermes-agent',
+ local: 'bundled-damaged',
+ bundled: true
+ }
+ })
+ )
+
+ render(<DesktopInstallOverlay />)
+
+ expect(await screen.findByText('Use Hermes bundled with this app')).toBeTruthy()
+ expect(screen.getByText(/missing or damaged/i)).toBeTruthy()
+
+ const localCard = screen.getByText('Use Hermes bundled with this app').closest('button')
+ expect(localCard).toBeTruthy()
+ expect(localCard?.getAttribute('aria-disabled')).toBe('true')
+
+ // Clicking the disabled card must never fire the local bootstrap bridge.
+ fireEvent.click(screen.getByText('Use Hermes bundled with this app'))
+ expect(desktop.continueBootstrapLocal).not.toHaveBeenCalled()
+
+ // The docs "Reinstall the app" affordance is present and opens the docs
+ // site — not an installer.
+ const reinstall = screen.getByText('Reinstall the app')
+ expect(reinstall).toBeTruthy()
+ fireEvent.click(reinstall)
+ expect(desktop.openExternal).toHaveBeenCalledWith('https://hermes-agent.nousresearch.com/docs/user-guide/desktop')
+
+ // The remote card stays clickable — connecting remotely is the working path.
+ fireEvent.click(screen.getByText('Connect to existing Hermes'))
+ expect(await screen.findByText('Gateway URL')).toBeTruthy()
+ })
+})
diff --git a/apps/desktop/src/components/desktop-install-overlay.tsx b/apps/desktop/src/components/desktop-install-overlay.tsx
index 4f814832395..95fb43dd2b9 100644
--- a/apps/desktop/src/components/desktop-install-overlay.tsx
+++ b/apps/desktop/src/components/desktop-install-overlay.tsx
@@ -15,10 +15,12 @@ import type {
DesktopBootstrapState
} from '@/global'
import { useI18n } from '@/i18n'
+import { DESKTOP_DOCS_URL } from '@/lib/docs'
import { AlertCircle, ChevronDown, ChevronRight, Globe, iconSize, Loader2, Monitor } from '@/lib/icons'
import { capitalize } from '@/lib/text'
import { cn } from '@/lib/utils'
+import { localCardPresentation } from './desktop-install-local-card'
import { FirstRunRemoteForm } from './first-run-remote-form'
/**
@@ -170,7 +172,8 @@ const EMPTY_STATE: DesktopBootstrapState = {
startedAt: null,
completedAt: null,
setupChoice: null,
- unsupportedPlatform: null
+ unsupportedPlatform: null,
+ bundled: false
}
function applyEvent(state: DesktopBootstrapState, ev: DesktopBootstrapEvent): DesktopBootstrapState {
@@ -188,10 +191,13 @@ function applyEvent(state: DesktopBootstrapState, ev: DesktopBootstrapEvent): De
setupChoice: ev.active
? {
platform: ev.platform || state.setupChoice?.platform || 'unknown',
- activeRoot: ev.activeRoot || state.setupChoice?.activeRoot || ''
+ activeRoot: ev.activeRoot || state.setupChoice?.activeRoot || '',
+ local: ev.local || state.setupChoice?.local || 'none',
+ bundled: Boolean(ev.bundled)
}
: null,
- unsupportedPlatform: null
+ unsupportedPlatform: null,
+ bundled: Boolean(ev.bundled)
}
}
@@ -397,6 +403,13 @@ export function DesktopInstallOverlay({ enabled = true }: DesktopInstallOverlayP
}
if (state.setupChoice) {
+ // The local card's copy + behavior derive from what the backend found on
+ // this machine: 'none' is an install offer, the rest say "use what's
+ // already here" — and 'bundled-damaged' disables the card entirely
+ // (there is no install to fire; reinstall the app instead).
+ const localState = state.setupChoice.local
+ const localPres = localCardPresentation(localState)
+
return (
<div className="fixed inset-0 z-(--z-setup) flex items-center justify-center bg-background/90 p-4 backdrop-blur-md">
<div className="w-full max-w-2xl rounded-xl border border-(--stroke-nous) bg-card p-8 shadow-nous">
@@ -404,7 +417,9 @@ export function DesktopInstallOverlay({ enabled = true }: DesktopInstallOverlayP
<BrandMark className="size-11 shrink-0" />
<div className="min-w-0">
<h2 className="text-xl font-semibold tracking-tight">{copy.setupChoiceTitle}</h2>
- <p className="mt-1.5 text-sm text-muted-foreground">{copy.setupChoiceDesc}</p>
+ <p className="mt-1.5 text-sm text-muted-foreground">
+ {localState === 'none' ? copy.setupChoiceDesc : copy.setupChoiceDescLocal}
+ </p>
</div>
</div>
@@ -422,8 +437,9 @@ export function DesktopInstallOverlay({ enabled = true }: DesktopInstallOverlayP
</button>
<button
- className="rounded-lg border border-(--ui-stroke-tertiary) bg-(--ui-bg-quinary) p-4 text-left transition hover:bg-(--chrome-action-hover) disabled:cursor-wait disabled:opacity-60"
- disabled={localStarting}
+ aria-disabled={localPres.disabled}
+ className="rounded-lg border border-(--ui-stroke-tertiary) bg-(--ui-bg-quinary) p-4 text-left transition hover:bg-(--chrome-action-hover) disabled:cursor-not-allowed disabled:opacity-60"
+ disabled={localStarting || localPres.disabled}
onClick={async () => {
setLocalStart({ root: activeRoot, starting: true, error: null })
@@ -447,12 +463,25 @@ export function DesktopInstallOverlay({ enabled = true }: DesktopInstallOverlayP
) : (
<Monitor className="size-4 text-muted-foreground" />
)}
- <span>{copy.installLocalTitle}</span>
+ <span>{copy[localPres.title]}</span>
</div>
- <p className="mt-2 text-sm leading-5 text-muted-foreground">{copy.installLocalDesc}</p>
+ <p className="mt-2 text-sm leading-5 text-muted-foreground">{copy[localPres.desc]}</p>
</button>
</div>
+ {localPres.disabled ? (
+ <div className="mt-4 flex items-center gap-2 text-sm text-muted-foreground">
+ <AlertCircle className="size-4 shrink-0" />
+ <button
+ className="text-(--ui-text-secondary) underline underline-offset-2 hover:text-foreground"
+ onClick={() => window.hermesDesktop?.openExternal?.(DESKTOP_DOCS_URL)}
+ type="button"
+ >
+ {copy.reinstallApp}
+ </button>
+ </div>
+ ) : null}
+
{localStartError ? (
<div className="mt-4 flex items-start gap-2 text-sm text-destructive">
<AlertCircle className="mt-0.5 size-4 shrink-0" />
@@ -460,10 +489,12 @@ export function DesktopInstallOverlay({ enabled = true }: DesktopInstallOverlayP
</div>
) : null}
- <div className="mt-6 text-xs text-muted-foreground">
- {copy.installTo}{' '}
- <code className="font-mono text-(--ui-text-secondary)">{state.setupChoice.activeRoot}</code>
- </div>
+ {localPres.showInstallTo ? (
+ <div className="mt-6 text-xs text-muted-foreground">
+ {copy.installTo}{' '}
+ <code className="font-mono text-(--ui-text-secondary)">{state.setupChoice.activeRoot}</code>
+ </div>
+ ) : null}
</div>
</div>
)
diff --git a/apps/desktop/src/components/external-open-failed-dialog.test.tsx b/apps/desktop/src/components/external-open-failed-dialog.test.tsx
new file mode 100644
index 00000000000..38226d71c26
--- /dev/null
+++ b/apps/desktop/src/components/external-open-failed-dialog.test.tsx
@@ -0,0 +1,97 @@
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import { ExternalOpenFailedDialog } from './external-open-failed-dialog'
+
+const windowsMock = vi.hoisted(() => ({
+ isHudWindow: vi.fn(() => false),
+ isBrowserWindow: vi.fn(() => false)
+}))
+
+vi.mock('@/store/windows', () => windowsMock)
+
+const desktopWindow = window as unknown as { hermesDesktop?: Window['hermesDesktop'] }
+const initialHermesDesktop = desktopWindow.hermesDesktop
+
+function installBridge() {
+ const onExternalOpenFailed = vi.fn()
+ const writeClipboard = vi.fn().mockResolvedValue(undefined)
+
+ desktopWindow.hermesDesktop = {
+ onExternalOpenFailed,
+ writeClipboard
+ } as unknown as Window['hermesDesktop']
+
+ return { onExternalOpenFailed, writeClipboard }
+}
+
+function fail(listener: unknown, url: string, message?: string) {
+ act(() => {
+ ;(listener as (payload: { url: string; message?: string }) => void)({ url, message })
+ })
+}
+
+afterEach(() => {
+ windowsMock.isHudWindow.mockReturnValue(false)
+ windowsMock.isBrowserWindow.mockReturnValue(false)
+ vi.restoreAllMocks()
+ cleanup()
+
+ if (initialHermesDesktop) {
+ desktopWindow.hermesDesktop = initialHermesDesktop
+ } else {
+ delete desktopWindow.hermesDesktop
+ }
+})
+
+describe('ExternalOpenFailedDialog', () => {
+ it('subscribes to open-failure events on mount', () => {
+ const { onExternalOpenFailed } = installBridge()
+ render(<ExternalOpenFailedDialog />)
+ expect(onExternalOpenFailed).toHaveBeenCalledTimes(1)
+ expect(typeof onExternalOpenFailed.mock.calls[0][0]).toBe('function')
+ })
+
+ it('shows the URL when an open-failure event fires', () => {
+ const { onExternalOpenFailed } = installBridge()
+ render(<ExternalOpenFailedDialog />)
+
+ const listener = onExternalOpenFailed.mock.calls[0][0]
+ expect(screen.queryByText('https://example.com/dead')).toBeNull()
+ fail(listener, 'https://example.com/dead')
+ expect(screen.getByText('https://example.com/dead')).not.toBeNull()
+ })
+
+ it('copies the URL when the copy action is used', async () => {
+ const { onExternalOpenFailed, writeClipboard } = installBridge()
+ render(<ExternalOpenFailedDialog />)
+
+ const listener = onExternalOpenFailed.mock.calls[0][0]
+ fail(listener, 'https://example.com/dead')
+
+ fireEvent.click(screen.getByRole('button', { name: /copy/i }))
+
+ await waitFor(() => expect(writeClipboard).toHaveBeenCalledWith('https://example.com/dead'))
+ })
+
+ it('closes when dismissed', async () => {
+ const { onExternalOpenFailed } = installBridge()
+ render(<ExternalOpenFailedDialog />)
+
+ const listener = onExternalOpenFailed.mock.calls[0][0]
+ fail(listener, 'https://example.com/dead')
+
+ fireEvent.click(screen.getByRole('button', { name: 'Close' }))
+
+ await waitFor(() => expect(screen.queryByText('https://example.com/dead')).toBeNull())
+ })
+
+ it('renders nothing in a HUD window', () => {
+ installBridge()
+ windowsMock.isHudWindow.mockReturnValue(true)
+
+ const view = render(<ExternalOpenFailedDialog />)
+
+ expect(view.container.firstChild).toBeNull()
+ })
+})
diff --git a/apps/desktop/src/components/external-open-failed-dialog.tsx b/apps/desktop/src/components/external-open-failed-dialog.tsx
new file mode 100644
index 00000000000..f2deb5179fb
--- /dev/null
+++ b/apps/desktop/src/components/external-open-failed-dialog.tsx
@@ -0,0 +1,56 @@
+import { useEffect, useState } from 'react'
+
+import { Button } from '@/components/ui/button'
+import { CopyButton } from '@/components/ui/copy-button'
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle
+} from '@/components/ui/dialog'
+import type { ExternalOpenFailedPayload } from '@/global.d'
+import { useI18n } from '@/i18n'
+import { isBrowserWindow, isHudWindow } from '@/store/windows'
+
+// Global fallback for a failed external URL open. main's openExternalUrl
+// reports every `shell.openExternal` rejection over a dedicated IPC event
+// (e.g. no https handler registered on Linux — a dead click otherwise). The
+// dialog shows the URL so the user can copy it and open it manually.
+export function ExternalOpenFailedDialog() {
+ const { t } = useI18n()
+ const [failure, setFailure] = useState<ExternalOpenFailedPayload | null>(null)
+
+ useEffect(() => {
+ if (!window.hermesDesktop?.onExternalOpenFailed) {return}
+
+ return window.hermesDesktop.onExternalOpenFailed(setFailure)
+ }, [])
+
+ if (isHudWindow() || isBrowserWindow()) {
+ return null
+ }
+
+ const copy = t.externalOpenFailed
+
+ return (
+ <Dialog onOpenChange={open => (!open ? setFailure(null) : undefined)} open={Boolean(failure)}>
+ <DialogContent className="max-w-[30rem]" showCloseButton={false}>
+ <DialogHeader>
+ <DialogTitle>{copy.title}</DialogTitle>
+ <DialogDescription>{copy.message}</DialogDescription>
+ </DialogHeader>
+ <div className="max-h-40 overflow-auto break-all rounded-md border bg-muted p-3 select-all">
+ {failure?.url}
+ </div>
+ <DialogFooter>
+ {failure ? <CopyButton text={failure.url}>{copy.copyUrl}</CopyButton> : null}
+ <Button onClick={() => setFailure(null)} variant="ghost">
+ {copy.close}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/apps/desktop/src/components/first-run-remote-form.tsx b/apps/desktop/src/components/first-run-remote-form.tsx
index 411bb54fbc6..139f0bd2a95 100644
--- a/apps/desktop/src/components/first-run-remote-form.tsx
+++ b/apps/desktop/src/components/first-run-remote-form.tsx
@@ -138,7 +138,7 @@ export function FirstRunRemoteForm({ onBack }: FirstRunRemoteFormProps) {
setOauthConnected(Boolean(result.connected))
if (!result.connected) {
- setError(copy.signInIncomplete)
+ setError(result.error ? `${copy.signInIncomplete}: ${result.error}` : copy.signInIncomplete)
}
} catch (err) {
setError(errorMessage(err))
diff --git a/apps/desktop/src/components/update-status.test.tsx b/apps/desktop/src/components/update-status.test.tsx
new file mode 100644
index 00000000000..a7a2c5e250b
--- /dev/null
+++ b/apps/desktop/src/components/update-status.test.tsx
@@ -0,0 +1,91 @@
+import { describe, expect, it } from 'vitest'
+
+import type { DesktopUpdateStatus } from '@/global'
+import { en } from '@/i18n/en'
+import type { UpdateApplyState } from '@/store/updates'
+
+import { deriveUpdateStatus } from './update-status'
+
+const IDLE_APPLY: UpdateApplyState = {
+ applying: false,
+ stage: 'idle',
+ message: '',
+ percent: null,
+ error: null,
+ command: null,
+ log: []
+}
+
+function derive(status: DesktopUpdateStatus | null, apply: UpdateApplyState = IDLE_APPLY, checking = false) {
+ return deriveUpdateStatus({ apply, checking, status, target: 'client', u: en.updates })
+}
+
+describe('deriveUpdateStatus', () => {
+ it('never-checked: idle tone, invites a check', () => {
+ const view = derive(null)
+
+ expect(view.tone).toBe('idle')
+ expect(view.updateAvailable).toBe(false)
+ expect(view.line).toBe(en.updates.tapCheck)
+ })
+
+ it('unsupported wins over everything else and keeps the backend message', () => {
+ const view = derive({ supported: false, message: 'managed install', behind: 5, updateAvailable: true })
+
+ expect(view.tone).toBe('unsupported')
+ expect(view.line).toBe('managed install')
+ expect(view.supported).toBe(false)
+ })
+
+ it('check error surfaces the tone and the transport message separately', () => {
+ const view = derive({ supported: true, error: 'check-failed', message: 'ECONNREFUSED' })
+
+ expect(view.tone).toBe('error')
+ expect(view.line).toBe(en.updates.cantReach)
+ expect(view.error).toBe('ECONNREFUSED')
+ })
+
+ it('applying beats available so the card cannot offer a second install', () => {
+ const view = derive({ supported: true, behind: 3 }, { ...IDLE_APPLY, applying: true, stage: 'update' })
+
+ expect(view.applying).toBe(true)
+ expect(view.tone).toBe('available')
+ expect(view.line).toBe(en.updates.installing)
+ })
+
+ it('restart stage counts as applying even when the applying flag already dropped', () => {
+ const view = derive({ supported: true }, { ...IDLE_APPLY, applying: false, stage: 'restart' })
+
+ expect(view.applying).toBe(true)
+ })
+
+ it('behind count renders counted copy; count-free updateAvailable falls back', () => {
+ expect(derive({ supported: true, behind: 4 }).line).toBe(en.updates.updateReady(4))
+
+ // Shallow clone: exact count unknowable, flagged via updateAvailable.
+ const unknown = derive({ supported: true, behind: 0, updateAvailable: true })
+
+ expect(unknown.line).toBe(en.updates.updateReadyUnknown)
+ expect(unknown.updateAvailable).toBe(true)
+ })
+
+ it('up to date: idle tone with the latest-version line', () => {
+ const view = derive({ supported: true, behind: 0 })
+
+ expect(view.tone).toBe('idle')
+ expect(view.updateAvailable).toBe(false)
+ expect(view.line).toBe(en.updates.latestBody)
+ })
+
+ it('backend target says the backend is current, not "you"', () => {
+ const view = deriveUpdateStatus({
+ apply: IDLE_APPLY,
+ checking: false,
+ status: { supported: true, behind: 0 },
+ target: 'backend',
+ u: en.updates
+ })
+
+ expect(view.line).toBe(en.updates.latestBodyBackend)
+ })
+})
diff --git a/apps/desktop/src/components/update-status.tsx b/apps/desktop/src/components/update-status.tsx
new file mode 100644
index 00000000000..56305b318d0
--- /dev/null
+++ b/apps/desktop/src/components/update-status.tsx
@@ -0,0 +1,286 @@
+import { useStore } from '@nanostores/react'
+import { type ReactNode, useState } from 'react'
+
+import { BrandMark } from '@/components/brand-mark'
+import { Button } from '@/components/ui/button'
+import { Codicon } from '@/components/ui/codicon'
+import type { DesktopUpdateStatus, DesktopVersionInfo } from '@/global'
+import { type Translations, useI18n } from '@/i18n'
+import { AlertTriangle, CheckCircle2, ExternalLink, Loader2, RefreshCw } from '@/lib/icons'
+import { cn } from '@/lib/utils'
+import {
+ $backendUpdateApply,
+ $backendUpdateChecking,
+ $backendUpdateStatus,
+ $updateApply,
+ $updateChecking,
+ $updateStatus,
+ checkBackendUpdates,
+ checkUpdates,
+ openUpdateOverlayFor,
+ startActiveUpdate,
+ type UpdateApplyState,
+ type UpdateTarget
+} from '@/store/updates'
+
+const RELEASE_NOTES_URL = 'https://github.com/NousResearch/hermes-agent/releases'
+const INSTALLER_URL = 'https://hermes-agent.nousresearch.com/'
+
+export type UpdateStatusTone = 'idle' | 'available' | 'error' | 'unsupported'
+
+export interface UpdateStatusView {
+ line: string
+ tone: UpdateStatusTone
+ error?: string
+ updateAvailable: boolean
+ applying: boolean
+ supported: boolean
+}
+
+/**
+ * One status derivation for every "am I up to date?" surface (About page,
+ * updates overlay). Pure so the tone/copy contract is unit-testable.
+ */
+export function deriveUpdateStatus({
+ apply,
+ checking,
+ status,
+ target,
+ u
+}: {
+ apply: UpdateApplyState
+ checking: boolean
+ status: DesktopUpdateStatus | null
+ target: UpdateTarget
+ u: Translations['updates']
+}): UpdateStatusView {
+ const behind = status?.behind ?? 0
+ // behind is null when the exact count is unknowable (shallow clone): the
+ // backend flags that case via updateAvailable instead of a number.
+ const updateAvailable = behind > 0 || Boolean(status?.updateAvailable)
+ const supported = status?.supported !== false
+ const applying = apply.applying || apply.stage === 'restart'
+
+ if (!supported) {
+ return { applying, line: status?.message ?? u.unsupportedMessage, supported, tone: 'unsupported', updateAvailable }
+ }
+
+ if (status?.error) {
+ return {
+ applying,
+ error: status.message,
+ line: u.cantReach,
+ supported,
+ tone: 'error',
+ updateAvailable
+ }
+ }
+
+ if (applying) {
+ return { applying, line: u.installing, supported, tone: 'available', updateAvailable }
+ }
+
+ if (updateAvailable) {
+ return {
+ applying,
+ line: behind > 0 ? u.updateReady(behind) : u.updateReadyUnknown,
+ supported,
+ tone: 'available',
+ updateAvailable
+ }
+ }
+
+ if (status) {
+ return {
+ applying,
+ line: target === 'backend' ? u.latestBodyBackend : u.latestBody,
+ supported,
+ tone: 'idle',
+ updateAvailable
+ }
+ }
+
+ return { applying, line: checking ? u.checking : u.tapCheck, supported, tone: 'idle', updateAvailable }
+}
+
+function relativeTime(ms: number | undefined, u: Translations['updates']): string {
+ if (!ms) {
+ return u.never
+ }
+
+ const diff = Date.now() - ms
+
+ if (diff < 60_000) {
+ return u.justNow
+ }
+
+ if (diff < 3_600_000) {
+ return u.minAgo(Math.round(diff / 60_000))
+ }
+
+ if (diff < 86_400_000) {
+ return u.hoursAgo(Math.round(diff / 3_600_000))
+ }
+
+ return u.daysAgo(Math.round(diff / 86_400_000))
+}
+
+/**
+ * The "Hermes Desktop / version / brand mark" hero shared by the About page
+ * and the updates overlay, including the bundle-out-of-sync warning. The
+ * heading render is injectable so a dialog surface can emit a DialogTitle
+ * for its accessible name while About keeps a plain h2.
+ */
+export function VersionHero({
+ renderHeading,
+ version
+}: {
+ renderHeading?: (heading: string) => ReactNode
+ version: DesktopVersionInfo | null
+}) {
+ const { t } = useI18n()
+ const u = t.updates
+
+ return (
+ <div className="flex flex-col items-center gap-3 pt-6 pb-2 text-center">
+ <BrandMark className="size-16" />
+ <div>
+ {renderHeading ? (
+ renderHeading(u.appName)
+ ) : (
+ <h2 className="text-lg font-semibold tracking-tight">{u.appName}</h2>
+ )}
+ <p className="mt-1 text-xs text-muted-foreground">
+ {version?.appVersion ? u.version(version.appVersion) : u.versionUnavailable}
+ </p>
+ </div>
+ {version?.bundleOutOfSync && (
+ <div className="mx-auto w-full max-w-2xl rounded-xl border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-left text-sm">
+ <div className="flex items-start gap-2">
+ <AlertTriangle className="mt-0.5 size-4 shrink-0 text-amber-600 dark:text-amber-400" />
+ <div className="min-w-0">
+ <p className="font-medium">{u.bundleOutOfSync}</p>
+ <p className="mt-1 text-xs text-muted-foreground">{u.bundleOutOfSyncDesc}</p>
+ <Button asChild className="mt-2" size="sm" variant="textStrong">
+ <a
+ href={INSTALLER_URL}
+ onClick={event => {
+ event.preventDefault()
+ void window.hermesDesktop?.openExternal?.(INSTALLER_URL)
+ }}
+ rel="noreferrer"
+ target="_blank"
+ >
+ <ExternalLink className="size-3" />
+ {u.bundleOutOfSyncAction}
+ </a>
+ </Button>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ )
+}
+
+/**
+ * The bordered update-state card (status line, last-checked age, check /
+ * update / release-notes actions) in the About page's visual language.
+ * Target-aware: 'client' reads the desktop self-update atoms, 'backend' the
+ * remote backend's. The actual apply flow stays in the updates overlay —
+ * "Update now" opens it and starts the install there.
+ */
+export function UpdateStatusCard({
+ showReleaseNotes = true,
+ target
+}: {
+ showReleaseNotes?: boolean
+ target: UpdateTarget
+}) {
+ const { t } = useI18n()
+ const u = t.updates
+ const isBackend = target === 'backend'
+ const status = useStore(isBackend ? $backendUpdateStatus : $updateStatus)
+ const checking = useStore(isBackend ? $backendUpdateChecking : $updateChecking)
+ const apply = useStore(isBackend ? $backendUpdateApply : $updateApply)
+ const [justChecked, setJustChecked] = useState(false)
+
+ const view = deriveUpdateStatus({ apply, checking, status, target, u })
+
+ const handleCheck = async (): Promise<void> => {
+ setJustChecked(false)
+ const next = await (isBackend ? checkBackendUpdates() : checkUpdates())
+ setJustChecked(Boolean(next))
+ }
+
+ return (
+ <div
+ className={cn(
+ 'rounded-xl border px-4 py-3 text-sm',
+ view.tone === 'available' && 'border-primary/30 bg-primary/5 text-foreground',
+ view.tone === 'error' && 'border-destructive/35 bg-destructive/5 text-destructive',
+ (view.tone === 'idle' || view.tone === 'unsupported') && 'border-border/70 bg-muted/20 text-foreground'
+ )}
+ >
+ <div className="flex items-start gap-2">
+ {view.tone === 'available' ? (
+ <Codicon className="mt-0.5 size-4 shrink-0 text-primary" name="cloud-download" size="1rem" />
+ ) : view.tone === 'error' || view.tone === 'unsupported' ? null : (
+ <CheckCircle2 className="mt-0.5 size-4 shrink-0 text-emerald-600 dark:text-emerald-400" />
+ )}
+ <div className="min-w-0">
+ <p className="font-medium">{view.line}</p>
+ {view.error && <p className="mt-1 text-xs text-muted-foreground">{view.error}</p>}
+ {view.tone !== 'unsupported' && (
+ <p className="mt-1 text-xs text-muted-foreground">
+ {u.lastChecked(relativeTime(status?.fetchedAt, u))}
+ {justChecked && !checking ? u.justNowSuffix : ''}
+ </p>
+ )}
+ </div>
+ </div>
+
+ {view.tone !== 'unsupported' && (
+ <div className="mt-3 flex flex-wrap items-center gap-4">
+ <Button
+ disabled={checking || view.applying}
+ onClick={() => void handleCheck()}
+ size="sm"
+ variant="textStrong"
+ >
+ {checking ? <Loader2 className="size-3 animate-spin" /> : <RefreshCw className="size-3" />}
+ {checking ? u.checkingShort : u.checkNow}
+ </Button>
+
+ {view.updateAvailable && view.supported && !view.applying && (
+ <>
+ <Button onClick={() => startActiveUpdate()} size="sm">
+ {u.updateNow}
+ </Button>
+ <Button onClick={() => openUpdateOverlayFor(target)} size="sm" variant="textStrong">
+ {u.seeWhatsNew}
+ </Button>
+ </>
+ )}
+
+ {showReleaseNotes && (
+ <Button asChild className="ml-auto" size="sm" variant="text">
+ <a
+ href={RELEASE_NOTES_URL}
+ onClick={event => {
+ event.preventDefault()
+ void window.hermesDesktop?.openExternal?.(RELEASE_NOTES_URL)
+ }}
+ rel="noreferrer"
+ target="_blank"
+ >
+ <ExternalLink className="size-3" />
+ {u.releaseNotes}
+ </a>
+ </Button>
+ )}
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/apps/desktop/src/components/version-details.test.tsx b/apps/desktop/src/components/version-details.test.tsx
new file mode 100644
index 00000000000..7aad9a45f0b
--- /dev/null
+++ b/apps/desktop/src/components/version-details.test.tsx
@@ -0,0 +1,109 @@
+import { cleanup, render, screen } from '@testing-library/react'
+import { afterEach, describe, expect, it } from 'vitest'
+
+import type { DesktopVersionInfo } from '@/global'
+import { I18nProvider } from '@/i18n'
+
+import { VersionDetails } from './version-details'
+
+const baseVersion: DesktopVersionInfo = {
+ appVersion: '0.19.0',
+ electronVersion: '37.0.0',
+ hermesRoot: '/tmp/hermes',
+ nodeVersion: '22.0.0',
+ platform: 'linux'
+}
+
+afterEach(cleanup)
+
+describe('VersionDetails', () => {
+ it('omits the branch suffix when no branch is present', () => {
+ render(
+ <I18nProvider configClient={null} initialLocale="en">
+ <VersionDetails version={{ ...baseVersion, source: 'ci', branch: null }} />
+ </I18nProvider>
+ )
+
+ expect(screen.getByText('Build Origin')).toBeTruthy()
+ expect(screen.getByText('CI')).toBeTruthy()
+ })
+
+ it('shows a literal branch named unknown inline', () => {
+ render(
+ <I18nProvider configClient={null} initialLocale="en">
+ <VersionDetails version={{ ...baseVersion, source: 'ci', branch: 'unknown' }} />
+ </I18nProvider>
+ )
+
+ expect(screen.getByText('CI (unknown)')).toBeTruthy()
+ })
+
+ it('shows the Nix source and distribution from the stamp', () => {
+ render(
+ <I18nProvider configClient={null} initialLocale="en">
+ <VersionDetails version={{ ...baseVersion, source: 'nix', distribution: 'nix' }} />
+ </I18nProvider>
+ )
+
+ expect(screen.getByText('Build Origin')).toBeTruthy()
+ expect(screen.getAllByText('Nix')).toHaveLength(2)
+ expect(screen.getByText('Distribution')).toBeTruthy()
+ })
+
+ it('distinguishes CI provenance from the Docker distribution', () => {
+ render(
+ <I18nProvider configClient={null} initialLocale="en">
+ <VersionDetails version={{ ...baseVersion, source: 'ci', distribution: 'docker' }} />
+ </I18nProvider>
+ )
+
+ expect(screen.getByText('CI')).toBeTruthy()
+ expect(screen.getByText('Distribution')).toBeTruthy()
+ expect(screen.getByText('Docker')).toBeTruthy()
+ })
+
+ it('shows the runtime row for an embedded build running its payload', () => {
+ render(
+ <I18nProvider configClient={null} initialLocale="en">
+ <VersionDetails
+ version={{
+ ...baseVersion,
+ distribution: 'desktop-app',
+ hermesRuntime: { type: 'embedded' }
+ }}
+ />
+ </I18nProvider>
+ )
+
+ expect(screen.getByText('Runtime')).toBeTruthy()
+ expect(screen.getByText('Embedded runtime')).toBeTruthy()
+ })
+
+ it('shows the runtime source with its location when an external build runs a machine runtime', () => {
+ render(
+ <I18nProvider configClient={null} initialLocale="en">
+ <VersionDetails
+ version={{
+ ...baseVersion,
+ hermesRuntime: { type: 'external', source: { type: 'git', root: '/home/u/.hermes/hermes-agent' } }
+ }}
+ />
+ </I18nProvider>
+ )
+
+ expect(screen.getByText('Runtime')).toBeTruthy()
+ expect(screen.getByText('git (/home/u/.hermes/hermes-agent)')).toBeTruthy()
+ expect(screen.queryByText('External (uses the machine runtime)')).toBeNull()
+ })
+
+ it('shows the generic external label before the first backend spawn', () => {
+ render(
+ <I18nProvider configClient={null} initialLocale="en">
+ <VersionDetails version={{ ...baseVersion, hermesRuntime: { type: 'external' } }} />
+ </I18nProvider>
+ )
+
+ expect(screen.getByText('Runtime')).toBeTruthy()
+ expect(screen.getByText('External (uses the machine runtime)')).toBeTruthy()
+ })
+})
diff --git a/apps/desktop/src/components/version-details.tsx b/apps/desktop/src/components/version-details.tsx
new file mode 100644
index 00000000000..84c5c02ce9e
--- /dev/null
+++ b/apps/desktop/src/components/version-details.tsx
@@ -0,0 +1,101 @@
+import type { DesktopVersionInfo, RuntimeSource } from '@/global'
+import { useI18n } from '@/i18n'
+import { ExternalLink } from '@/lib/external-link'
+
+/**
+ * Human label for an external build's runtime source: the resolution rung
+ * plus the location it resolved from, when there is one.
+ */
+function runtimeSourceLabel(source: RuntimeSource): string {
+ const where = 'root' in source && source.root ? source.root : 'command' in source ? source.command : null
+
+ return where ? `${source.type} (${where})` : source.type
+}
+
+/**
+ * Shared build-provenance display. Reads from `$desktopVersion`
+ * (populated from the build stamp / `hermes:version` IPC), so every
+ * surface — the About settings page, the updates overlay — shows the
+ * same version, branch, commit, distribution, runtime, and install id
+ * from one source of truth.
+ */
+export function VersionDetails({ version }: { version: DesktopVersionInfo }) {
+ const { t } = useI18n()
+ const u = t.updates
+
+ const source =
+ version.source === 'ci' ? 'CI' : version.source ? version.source[0].toUpperCase() + version.source.slice(1) : null
+
+ const distribution =
+ version.distribution === 'nix'
+ ? 'Nix'
+ : version.distribution === 'docker'
+ ? 'Docker'
+ : version.distribution === 'desktop-app'
+ ? u.versionDetailsDistributionDesktop
+ : null
+
+ const runtime =
+ version.hermesRuntime?.type === 'embedded'
+ ? u.versionDetailsRuntimeEmbedded
+ : version.hermesRuntime?.type === 'external' && version.hermesRuntime.source
+ ? runtimeSourceLabel(version.hermesRuntime.source)
+ : version.hermesRuntime?.type === 'external'
+ ? u.versionDetailsRuntimeExternal
+ : null
+
+ return (
+ <dl className="grid gap-2 rounded-lg border border-border/70 bg-muted/20 px-3 py-3 text-sm">
+ <div className="flex justify-between gap-4">
+ <dt className="text-muted-foreground">{u.versionDetailsVersion}</dt>
+ <dd>
+ v{version.appVersion}
+ {version.dirty && <span className="text-warning"> (!)</span>}
+ </dd>
+ </div>
+ {version.commit && (
+ <div className="flex justify-between gap-4">
+ <dt className="text-muted-foreground">{u.versionDetailsCommit}</dt>
+ <dd className="break-all text-right">
+ <ExternalLink
+ className="break-all font-mono text-xs"
+ href={`https://github.com/NousResearch/hermes-agent/commit/${version.commit}`}
+ >
+ {version.commit.slice(0, 14)}
+ </ExternalLink>
+ {version.dirty && <span className="text-warning"> {u.versionDetailsUncommittedChanges}</span>}
+ </dd>
+ </div>
+ )}
+ {source && (
+ <div className="flex justify-between gap-4">
+ <dt className="text-muted-foreground">{u.versionDetailsBuildOrigin}</dt>
+ <dd>
+ {source}
+ {version.branch && version.branch !== 'main' ? ` (${version.branch})` : ''}
+ </dd>
+ </div>
+ )}
+ {distribution && (
+ <div className="flex justify-between gap-4">
+ <dt className="text-muted-foreground">{u.versionDetailsDistribution}</dt>
+ <dd>{distribution}</dd>
+ </div>
+ )}
+ {runtime && (
+ <div className="flex justify-between gap-4">
+ <dt className="text-muted-foreground">{u.versionDetailsRuntime}</dt>
+ <dd className="break-all text-right">{runtime}</dd>
+ </div>
+ )}
+ {version.installId && (
+ <div className="flex justify-between gap-4">
+ <dt className="text-muted-foreground">{u.versionDetailsInstallId}</dt>
+ <dd className="break-all text-right font-mono text-xs">
+ {version.installId} ({version.hermesRoot})
+ </dd>
+ </div>
+ )}
+ </dl>
+ )
+}
diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.ts
index bb09b46c48a..1ea6a627d43 100644
--- a/apps/desktop/src/global.d.ts
+++ b/apps/desktop/src/global.d.ts
@@ -299,6 +299,7 @@ declare global {
setDisableF12?: (blocked: boolean) => void
setPreviewShortcutActive?: (active: boolean) => void
openExternal: (url: string) => Promise<void>
+ onExternalOpenFailed?: (callback: (payload: ExternalOpenFailedPayload) => void) => () => void
openPreviewInBrowser?: (url: string) => Promise<void>
fetchLinkTitle: (url: string) => Promise<string>
/** A site's icon as a data URL, or '' when it has none we can read.
@@ -326,6 +327,8 @@ declare global {
message: string
componentStack: string
}) => void
+ /** Append one raw line to desktop.log (fire-and-forget, notifyError path). */
+ logLine?: (line: string) => void
readDir: (path: string) => Promise<HermesReadDirResult>
gitRoot?: (path: string) => Promise<string | null>
// Reveal a path in the OS file manager (Finder / Explorer).
@@ -558,7 +561,43 @@ export interface DesktopVersionInfo {
bundleOutOfSync?: boolean
/** Commits under apps/desktop/ the running bundle is missing (null unknown). */
bundleCommitsBehind?: null | number
-}
+ /** Build provenance from the install stamp (empty for packaged builds with
+ * no stamp / a bare `app.getVersion()` fallback). */
+ baseVersion?: string
+ branch?: string | null
+ commit?: string | null
+ distance?: number
+ dirty?: boolean
+ source?: 'build' | 'ci' | 'docker' | 'fallback' | 'git' | 'local' | 'nix' | 'unknown'
+ distribution?: 'desktop-app' | 'docker' | 'nix'
+ /** sha16 of the canonical install-root path — the per-install channel key and
+ * the shape `hermes update --install-id` prints. */
+ installId?: string
+ /** What this build carries (embedded / light / external) and where an
+ * external backend resolved from. Bundled artifacts run their payload; light
+ * artifacts have no runtime and only reach remote backends. */
+ hermesRuntime?: { type: 'embedded' } | { type: 'light' } | { type: 'external'; source?: RuntimeSource }
+}
+
+/** Where an external build's backend came from. Mirrors the resolution ladder
+ * in `resolveHermesBackend()`: `git` / `source` / sealed stewards are the
+ * Python install methods from `installation.tree.install_method()`; the
+ * Electron-only rungs (`hermes-root`, `path`, `system-python`, `bootstrap`)
+ * are resolution facts the backend cannot see. Each variant carries the
+ * location it resolved from, when there is one. */
+export type RuntimeSource =
+ | { type: 'hermes-root'; root: string } // HERMES_DESKTOP_HERMES_ROOT — explicit developer override
+ | { type: 'git'; root: string } // checkout at a managed install root, $HERMES_HOME/hermes-agent
+ | { type: 'source'; root: string } // a git checkout anywhere else
+ | { type: 'docker'; root: string | null } // sealed tree stewarded by Docker
+ | { type: 'nix'; root: string | null } // sealed tree stewarded by Nix
+ | { type: 'desktop-app'; root: string | null } // sealed tree stewarded by the desktop bundle
+ | { type: 'desktop-bootstrap'; root: string } // canonical install created by the desktop first-launch bootstrap
+ | { type: 'unknown' } // no stamp, no .git — provenance cannot be told
+ | { type: 'path'; command: string } // an existing `hermes` CLI found on PATH
+ | { type: 'system-python'; command: string } // pip-installed hermes_cli on system Python
+ | { type: 'bootstrap' } // nothing usable yet; the first-launch installer runs
+
export type DesktopUninstallMode = 'full' | 'gui' | 'lite'
@@ -591,8 +630,17 @@ export interface DesktopUpdateCommit {
at: number
}
+export type UpdaterMechanismClient =
+ | 'app-installer'
+ | 'external'
+ | 'windows-handoff'
+ | 'posix-handoff'
+ | 'manual'
+
export interface DesktopUpdateStatus {
supported: boolean
+ /** Which mechanism owns updates for this install (see electron/updater). */
+ mechanism?: UpdaterMechanismClient
updateAvailable?: boolean
branch?: string
currentBranch?: string
@@ -606,6 +654,11 @@ export interface DesktopUpdateStatus {
currentSha?: string
/** Backend only: the version string the backend reports for itself. */
currentVersion?: string
+ /** Release feed the check read from ('stable'/'nightly'); when set, the
+ * update is a release and `latestTag` names it instead of a commit count. */
+ channel?: 'stable' | 'nightly'
+ /** The latest release tag on a release-feed channel, e.g. `v0.18.0`. */
+ latestTag?: string | null
targetSha?: string
commits?: DesktopUpdateCommit[]
dirty?: boolean
@@ -1015,10 +1068,16 @@ export interface DesktopConnectionProbeResult {
error: string | null
}
+export interface ExternalOpenFailedPayload {
+ url: string
+ message?: string
+}
+
export interface DesktopOauthLoginResult {
ok: boolean
baseUrl: string
connected: boolean
+ error?: string
}
export interface DesktopOauthLogoutResult {
@@ -1127,6 +1186,10 @@ export interface DesktopBootstrapUnsupportedPlatform {
export interface DesktopBootstrapSetupChoice {
platform: string
activeRoot: string
+ /** What the local card represents: 'none' = installer offer; the rest = use existing. */
+ local: 'none' | 'installed' | 'bundled' | 'bundled-damaged'
+ /** This artifact is a bundled install (payload ships in-app). */
+ bundled: boolean
}
export interface DesktopBootstrapState {
@@ -1139,6 +1202,8 @@ export interface DesktopBootstrapState {
completedAt: number | null
setupChoice: DesktopBootstrapSetupChoice | null
unsupportedPlatform: DesktopBootstrapUnsupportedPlatform | null
+ /** This artifact is a bundled install (payload ships in-app). */
+ bundled: boolean
}
export type DesktopBootstrapEvent =
@@ -1148,6 +1213,8 @@ export type DesktopBootstrapEvent =
active: boolean
platform?: string
activeRoot?: string
+ local?: DesktopBootstrapSetupChoice['local']
+ bundled?: boolean
}
| { type: 'manifest'; stages: DesktopBootstrapStageDescriptor[]; protocolVersion: number | null }
| {
diff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.ts
index 6202019c708..4bb839974d7 100644
--- a/apps/desktop/src/i18n/ar.ts
+++ b/apps/desktop/src/i18n/ar.ts
@@ -1,6 +1,13 @@
import { defineLocale } from './define-locale'
export const ar = defineLocale({
+ externalOpenFailed: {
+ title: 'تعذّر فتح هذا الرابط',
+ message: 'لا يوجد متصفح مسجل لفتح هذا العنوان. انسخ الرابط وافتحه يدويًا.',
+ copyUrl: 'نسخ الرابط',
+ close: 'إغلاق'
+ },
+
sendDiagnostics: {
title: 'إرسال التشخيصات إلى Nous',
privacyNotice:
@@ -663,38 +670,6 @@ export const ar = defineLocale({
'updates.nonInteractiveLocalChanges':
'عندما يحدّث Hermes نفسه من التطبيق دون موجه طرفية، احتفظ بتعديلات المصدر المحلية أو تجاهلها.'
},
- about: {
- heading: 'حول Hermes',
- version: value => `الإصدار ${value}`,
- versionUnavailable: 'الإصدار غير متاح',
- bundleOutOfSync: 'إصدار التطبيق قديم',
- bundleOutOfSyncDesc:
- 'تم تحديث وقت تشغيل Hermes، لكن تطبيق سطح المكتب نفسه لا يزال إصدارًا قديمًا — لن تظهر ميزات الواجهة الجديدة (مثل Bot Mode) حتى يتم تحديث التطبيق. شغّل التحديث أدناه لإعادة بناء التطبيق. إذا لم يختفِ هذا التحذير، فأعد التثبيت من أحدث مثبّت لسطح المكتب.',
- bundleOutOfSyncAction: 'الحصول على المثبّت',
- updates: 'التحديثات',
- checkNow: 'التحقق الآن',
- checking: 'جار التحقق...',
- seeWhatsNew: 'عرض الجديد',
- updateNow: 'تحديث الآن',
- releaseNotes: 'ملاحظات الإصدار',
- onLatest: 'أنت على أحدث إصدار',
- installing: 'جار التثبيت...',
- cantUpdate: 'تعذر التحديث',
- cantReach: 'تعذر الوصول لخدمة التحديث',
- tapCheck: 'اضغط للتحقق من التحديثات.',
- updateReady: count => `${count} تحديث متاح`,
- updateReadyUnknown: 'تحديث جديد جاهز.',
- lastChecked: age => `آخر تحقق ${age}`,
- justNowSuffix: 'الآن',
- automaticUpdates: 'التحديثات التلقائية',
- automaticUpdatesDesc: 'اسمح لـ Hermes بالتحقق من التحديثات وتثبيتها.',
- branchCommit: (branch, commit) => `${branch} عند ${commit}`,
- never: 'أبدا',
- justNow: 'الآن',
- minAgo: count => `قبل ${count} دقيقة`,
- hoursAgo: count => `قبل ${count} ساعة`,
- daysAgo: count => `قبل ${count} يوم`
- },
config: {
none: 'لا شيء',
noneParen: '(لا شيء)',
@@ -2008,6 +1983,42 @@ export const ar = defineLocale({
tryAgain: 'إعادة المحاولة',
notAvailableTitle: 'التحديث غير متاح',
unsupportedMessage: 'لا يمكن لهذا الإصدار من Hermes تحديث نفسه من داخل التطبيق.',
+ appName: 'Hermes Desktop',
+ version: value => `الإصدار ${value}`,
+ versionUnavailable: 'الإصدار غير متاح',
+ bundleOutOfSync: 'إصدار التطبيق قديم',
+ bundleOutOfSyncDesc:
+ 'تم تحديث وقت تشغيل Hermes، لكن تطبيق سطح المكتب نفسه لا يزال إصدارًا قديمًا — لن تظهر ميزات الواجهة الجديدة (مثل Bot Mode) حتى يتم تحديث التطبيق. شغّل التحديث أدناه لإعادة بناء التطبيق. إذا لم يختفِ هذا التحذير، فأعد التثبيت من أحدث مثبّت لسطح المكتب.',
+ bundleOutOfSyncAction: 'الحصول على المثبّت',
+ updatesSection: 'التحديثات',
+ checkNow: 'التحقق الآن',
+ checkingShort: 'جار التحقق...',
+ seeWhatsNew: 'عرض الجديد',
+ releaseNotes: 'ملاحظات الإصدار',
+ installing: 'جار التثبيت...',
+ cantReach: 'تعذر الوصول لخدمة التحديث',
+ tapCheck: 'اضغط للتحقق من التحديثات.',
+ updateReady: count => `${count} تحديث متاح`,
+ updateReadyUnknown: 'تحديث جديد جاهز.',
+ lastChecked: age => `آخر تحقق ${age}`,
+ justNowSuffix: 'الآن',
+ never: 'أبدا',
+ justNow: 'الآن',
+ minAgo: count => `قبل ${count} دقيقة`,
+ hoursAgo: count => `قبل ${count} ساعة`,
+ daysAgo: count => `قبل ${count} يوم`,
+ versionDetailsTitle: 'تفاصيل الإصدار',
+ versionDetailsBody: 'هذا التثبيت مُدار خارج التطبيق. حدّثه بالطريقة نفسها التي استخدمتها لتثبيته.',
+ versionDetailsVersion: 'الإصدار',
+ versionDetailsCommit: 'الالتزام',
+ versionDetailsBuildOrigin: 'مصدر البناء',
+ versionDetailsDistribution: 'التوزيع',
+ versionDetailsDistributionDesktop: 'تطبيق سطح المكتب',
+ versionDetailsRuntimeEmbedded: 'وقت تشغيل مضمّن',
+ versionDetailsRuntimeExternal: 'خارجي (يستخدم وقت تشغيل الجهاز)',
+ versionDetailsRuntime: 'وقت التشغيل',
+ versionDetailsInstallId: 'معرّف التثبيت',
+ versionDetailsUncommittedChanges: '(+ تغييرات غير ملتزمة)',
connectionRetry: 'تحقق من اتصالك وأعد المحاولة.',
latestBody: 'أنت تستخدم أحدث إصدار.',
latestBodyBackend: 'الواجهة الخلفية تعمل بأحدث إصدار.',
@@ -2017,6 +2028,7 @@ export const ar = defineLocale({
availableTitleBackend: 'يتوفر تحديث للواجهة الخلفية',
availableBodyBackend: 'إصدار أحدث من واجهة Hermes الخلفية المتصلة جاهز للتثبيت.',
availableBodyNoChangelog: 'إصدار أحدث جاهز. ملاحظات الإصدار غير متاحة لنوع التثبيت هذا.',
+ availableBodyRelease: tag => `Hermes ${tag} جاهز للتثبيت.`,
updateNow: 'التحديث الآن',
maybeLater: 'ربما لاحقا',
moreChanges: count => `+ ${count} تغيير${count === 1 ? '' : 'ات'} إضافي مُضمَّن.`,
@@ -2255,6 +2267,7 @@ export const ar = defineLocale({
update: 'تحديث',
updateInProgress: 'التحديث جار',
commitsBehind: (count, branch) => `${count} commits خلف ${branch}`,
+ releaseAvailable: tag => `الإصدار ${tag} متاح`,
desktopVersion: version => `سطح المكتب ${version}`,
backendVersion: version => `الخلفية ${version}`,
clientLabel: version => `العميل ${version}`,
diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts
index 2a9aed67e56..d318b5c35fd 100644
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@ -142,6 +142,8 @@ export const en: Translations = {
updateReadyTitle: 'Update ready',
updateReadyMessage: count => `${count} new change${count === 1 ? '' : 's'} available.`,
updateReadyMessageUnknown: 'A new update is available.',
+ updateReadyMessageAppInstaller:
+ 'A new version of Hermes is ready. Update now and Windows will finish it for you.',
seeWhatsNew: "See what's new",
mcp: {
needsAuthTitle: 'MCP server needs re-authentication',
@@ -2594,6 +2596,8 @@ export const en: Translations = {
availableTitleBackend: 'Backend update available',
availableBodyBackend: 'A newer version of the connected Hermes backend is ready to install.',
availableBodyNoChangelog: 'A newer version is ready. Release notes aren’t available for this install type.',
+ availableBodyAppInstaller:
+ 'A new version of Hermes is ready. Hermes will close, Windows will finish the update, and Hermes will reopen on its own.',
updateNow: 'Update now',
maybeLater: 'Maybe later',
moreChanges: count => `+ ${count} more change${count === 1 ? '' : 's'} included.`,
@@ -2611,6 +2615,12 @@ export const en: Translations = {
applyingBodyBackend:
'The remote backend is applying the update and will restart. Hermes reconnects automatically when it’s back.',
applyingClose: 'This window will close while the update runs, then Hermes reopens on its own.',
+ applyingBodyAppInstaller:
+ 'Hermes will close and Windows will finish the update. Hermes will reopen when it’s done — you don’t need to do anything.',
+ applyingCloseAppInstaller: 'This window will close, Windows finishes the update, and Hermes reopens on its own.',
+ checkUnknownTitleAppInstaller: 'Couldn’t check for updates',
+ checkUnknownBodyAppInstaller:
+ 'Windows couldn’t check for updates right now. Updates also install automatically when you restart Hermes.',
errorTitle: 'Update didn’t finish',
errorBody: 'No worries — nothing was lost. You can try again now.',
blockerTitle: 'Close local previews to update Hermes?',
diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts
index 3b4415cb7f1..0c27bbfdf38 100644
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@ -183,6 +183,7 @@ export interface Translations {
updateReadyTitle: string
updateReadyMessage: (count: number) => string
updateReadyMessageUnknown: string
+ updateReadyMessageAppInstaller: string
seeWhatsNew: string
mcp: {
needsAuthTitle: string
@@ -2194,6 +2195,7 @@ export interface Translations {
availableTitleBackend: string
availableBodyBackend: string
availableBodyNoChangelog: string
+ availableBodyAppInstaller: string
updateNow: string
maybeLater: string
moreChanges: (count: number) => string
@@ -2210,6 +2212,10 @@ export interface Translations {
applyingBody: string
applyingBodyBackend: string
applyingClose: string
+ applyingBodyAppInstaller: string
+ applyingCloseAppInstaller: string
+ checkUnknownTitleAppInstaller: string
+ checkUnknownBodyAppInstaller: string
errorTitle: string
errorBody: string
blockerTitle: string
diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts
index 2f90f098682..ab91a251c01 100644
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@ -138,6 +138,7 @@ export const zh: Translations = {
updateReadyTitle: '有可用更新',
updateReadyMessage: count => `有 ${count} 项新更改可用。`,
updateReadyMessageUnknown: '有新更新可用。',
+ updateReadyMessageAppInstaller: 'Hermes 新版本已就绪。现在更新,Windows 会自动完成。',
seeWhatsNew: '查看更新内容',
mcp: {
needsAuthTitle: 'MCP 服务器需要重新认证',
@@ -2772,6 +2773,7 @@ export const zh: Translations = {
availableTitleBackend: '后端有可用更新',
availableBodyBackend: '已连接的 Hermes 后端有新版本可安装。',
availableBodyNoChangelog: '已有新版本可用。此安装方式无法显示更新日志。',
+ availableBodyAppInstaller: 'Hermes 新版本已就绪。Hermes 会关闭,Windows 完成更新后自动重新打开。',
updateNow: '立即更新',
maybeLater: '稍后再说',
moreChanges: count => `另有 ${count} 项更改。`,
@@ -2788,6 +2790,10 @@ export const zh: Translations = {
'Hermes 更新器会在自己的窗口中接管,并在完成后自动重新打开 Hermes。更新期间请不要自行重新打开 Hermes。',
applyingBodyBackend: '远程后端正在应用更新并将重启。恢复后 Hermes 会自动重新连接。',
applyingClose: '此窗口会在更新期间关闭,随后 Hermes 会自动重新打开。',
+ applyingBodyAppInstaller: 'Hermes 会关闭,Windows 会完成更新,然后 Hermes 自动重新打开——无需任何操作。',
+ applyingCloseAppInstaller: '此窗口会关闭,Windows 完成更新后 Hermes 自动重新打开。',
+ checkUnknownTitleAppInstaller: '无法检查更新',
+ checkUnknownBodyAppInstaller: 'Windows 目前无法检查更新。重启 Hermes 时也会自动安装更新。',
errorTitle: '更新未完成',
errorBody: '没有数据丢失。你可以现在重试。',
blockerTitle: '关闭本地预览以更新 Hermes?',
diff --git a/apps/desktop/src/lib/docs.ts b/apps/desktop/src/lib/docs.ts
new file mode 100644
index 00000000000..f3c4a44dd27
--- /dev/null
+++ b/apps/desktop/src/lib/docs.ts
@@ -0,0 +1,7 @@
+/**
+ * docs.ts — canonical docs-site links used by the renderer's recovery and
+ * setup surfaces. Single authority so the "reinstall the app" affordance
+ * (bundled installs with a damaged payload) and any future doc links point
+ * at the same place.
+ */
+export const DESKTOP_DOCS_URL = 'https://hermes-agent.nousresearch.com/docs/user-guide/desktop'
diff --git a/apps/desktop/src/lib/update-copy.test.ts b/apps/desktop/src/lib/update-copy.test.ts
index 3d4781c4508..b6100630e39 100644
--- a/apps/desktop/src/lib/update-copy.test.ts
+++ b/apps/desktop/src/lib/update-copy.test.ts
@@ -7,7 +7,10 @@ const copy = {
availableBody: 'A new version of Hermes is ready to install.',
availableTitleBackend: 'Backend update available',
availableBodyBackend: 'A newer version of the connected Hermes backend is ready to install.',
- availableBodyNoChangelog: 'A newer version is ready. Release notes aren’t available for this install type.'
+ availableBodyNoChangelog: 'A newer version is ready. Release notes aren’t available for this install type.',
+ availableBodyRelease: (tag: string) => `Hermes ${tag} is ready to install.`,
+ availableBodyAppInstaller:
+ 'A new version of Hermes is ready. Hermes will close, Windows will finish the update, and Hermes will reopen on its own.'
}
describe('resolveUpdateCopy', () => {
@@ -35,4 +38,42 @@ describe('resolveUpdateCopy', () => {
expect(r.title).toBe('New update available')
expect(r.body).toBe(copy.availableBodyNoChangelog)
})
+
+ it('stable channel with a known tag names the release, not the commit count', () => {
+ const r = resolveUpdateCopy({
+ target: 'client',
+ shownItems: 0,
+ channel: 'stable',
+ latestTag: 'v0.18.0',
+ copy
+ })
+
+ expect(r.body).toBe('Hermes v0.18.0 is ready to install.')
+ })
+
+ it('stable channel without a tag falls back to the generic release body', () => {
+ const r = resolveUpdateCopy({ target: 'client', shownItems: 0, channel: 'stable', copy })
+ expect(r.body).toBe(copy.availableBody)
+ })
+
+ it('app-installer mechanism uses the Windows-finishes-it body, not commit vocabulary', () => {
+ const r = resolveUpdateCopy({ target: 'client', shownItems: 5, mechanism: 'app-installer', copy })
+ expect(r.body).toBe(copy.availableBodyAppInstaller)
+ })
+
+ it('app-installer mechanism with a known tag names the release', () => {
+ const r = resolveUpdateCopy({
+ target: 'client',
+ shownItems: 0,
+ mechanism: 'app-installer',
+ latestTag: 'v0.18.3',
+ copy
+ })
+ expect(r.body).toBe('Hermes v0.18.3 is ready to install.')
+ })
+
+ it('other mechanisms keep the commit vocabulary', () => {
+ const r = resolveUpdateCopy({ target: 'client', shownItems: 5, mechanism: 'windows-handoff', copy })
+ expect(r.body).toBe(copy.availableBody)
+ })
})
diff --git a/apps/desktop/src/lib/update-copy.ts b/apps/desktop/src/lib/update-copy.ts
index 943ee24bfff..fc31831899c 100644
--- a/apps/desktop/src/lib/update-copy.ts
+++ b/apps/desktop/src/lib/update-copy.ts
@@ -4,6 +4,8 @@
* Names the update target (client vs the connected backend in remote mode) and
* degrades honestly when there's no commit changelog to show (e.g. a pip /
* non-git backend where `git log` yields nothing) instead of generic filler.
+ * On a release-feed channel it names the release tag instead of commit
+ * vocabulary, because a release feed carries no commit rows by construction.
*
* Extracted from updates-overlay.tsx so the wording logic is unit-testable.
*/
@@ -16,12 +18,29 @@ export interface UpdateCopyStrings {
availableTitleBackend: string
availableBodyBackend: string
availableBodyNoChangelog: string
+ /** Stable channel: names the release instead of describing commits. */
+ availableBodyRelease: (tag: string) => string
+ /** App-installer mechanism: the OS owns the apply, so the body says so. */
+ availableBodyAppInstaller: string
}
export interface ResolveUpdateCopyInput {
target: UpdateTarget
/** Number of commit rows actually shown in the changelog. 0 → no notes. */
shownItems: number
+ /**
+ * 'stable': the update is a release, so the body names its tag and the
+ * commit-changelog wording never appears (a release feed carries no
+ * commit rows anyway). 'main' or absent: commit vocabulary as before.
+ */
+ channel?: 'stable' | 'main'
+ /** Stable channel: the release tag the update moves to, when known. */
+ latestTag?: null | string
+ /**
+ * 'app-installer': the OS App Installer owns the apply (out-of-store MSIX)
+ * — the body names Windows as the finisher, never commit vocabulary.
+ */
+ mechanism?: 'app-installer' | 'external' | 'windows-handoff' | 'posix-handoff' | 'manual'
copy: UpdateCopyStrings
}
@@ -30,9 +49,29 @@ export interface UpdateCopyResult {
body: string
}
-export function resolveUpdateCopy({ target, shownItems, copy }: ResolveUpdateCopyInput): UpdateCopyResult {
+export function resolveUpdateCopy({
+ target,
+ shownItems,
+ channel = 'main',
+ latestTag = null,
+ mechanism,
+ copy
+}: ResolveUpdateCopyInput): UpdateCopyResult {
const title = target === 'backend' ? copy.availableTitleBackend : copy.availableTitle
+ // App-installer: the OS owns the apply, and there is no commit list by
+ // construction (the OS checker answers yes/no). Name Windows as the
+ // finisher; the tag is named when known.
+ if (mechanism === 'app-installer') {
+ return { title, body: latestTag ? copy.availableBodyRelease(latestTag) : copy.availableBodyAppInstaller }
+ }
+
+ if (channel === 'stable') {
+ // No-changelog copy would be wrong here: the absence of commit rows is
+ // structural on a release feed, not a degraded install type.
+ return { title, body: latestTag ? copy.availableBodyRelease(latestTag) : copy.availableBody }
+ }
+
const body =
shownItems === 0
? copy.availableBodyNoChangelog
diff --git a/apps/desktop/src/lib/version-status.test.ts b/apps/desktop/src/lib/version-status.test.ts
index 0ea94080399..735f16c8d16 100644
--- a/apps/desktop/src/lib/version-status.test.ts
+++ b/apps/desktop/src/lib/version-status.test.ts
@@ -94,4 +94,22 @@ describe('resolveVersionStatus', () => {
it('hides a backend row that has no version at all', () => {
expect(backend().unknown).toBe(true)
})
+
+ it('stable channel: releases use the update word, never a commit count', () => {
+ const label = client({ behind: 4, updateAvailable: true, channel: 'stable', version: '0.4.2' }).label
+ expect(label).toBe('v0.4.2 (update)')
+ })
+
+ it('stable channel tooltip names the release tag', () => {
+ const tooltip = client({ behind: 1, channel: 'stable', latestTag: 'v0.18.0', version: '0.4.2' }).tooltip
+ expect(tooltip).toContain(`${copy.releaseAvailable('v0.18.0')}`)
+ })
+
+ it('stable channel never names a branch (a stable checkout sits on a tag)', () => {
+ const tooltip = client({ behind: 1, branch: 'main', channel: 'stable', latestTag: 'v0.18.0', version: '0.4.2' })
+ .tooltip
+
+ expect(tooltip).not.toContain('main')
+ expect(tooltip).toContain(`${copy.releaseAvailable('v0.18.0')}`)
+ })
})
diff --git a/apps/desktop/src/lib/version-status.ts b/apps/desktop/src/lib/version-status.ts
index 0b292c9f31d..fb6d4e922bd 100644
--- a/apps/desktop/src/lib/version-status.ts
+++ b/apps/desktop/src/lib/version-status.ts
@@ -18,6 +18,8 @@ export interface VersionStatusCopy {
commit: (sha: string) => string
commitsBehind: (count: number, branch: string) => string
desktopVersion: (version: string) => string
+ /** Stable channel: a newer release exists ("v0.21.0 is available"). */
+ releaseAvailable: (tag: string) => string
restart: string
unknown: string
update: string
@@ -31,7 +33,17 @@ export interface VersionStatusInput {
applyMessage?: string
behind?: number
branch?: string
+ /**
+ * The update channel of the target. 'main' (the default) speaks in
+ * commits behind a branch. 'stable' speaks in releases: the label hint
+ * is the update word, never a commit count, and the tooltip names the
+ * newer release tag. The channel changes the vocabulary only — the
+ * apply mechanism is the caller's concern.
+ */
+ channel?: 'stable' | 'main'
copy: VersionStatusCopy
+ /** Stable channel: the newest release tag, when the check found one. */
+ latestTag?: null | string
/** Remote mode: the client is one of two versions on screen, so it says so. */
remote: boolean
/** The apply reached the restart stage — labels `restart`, not `update`. */
@@ -60,7 +72,9 @@ export function resolveVersionStatus({
applying,
behind = 0,
branch,
+ channel = 'main',
copy,
+ latestTag = null,
remote,
restarting,
sha = null,
@@ -75,6 +89,7 @@ export function resolveVersionStatus({
// SSH-official presence-only checks, and pip installs. It applies to BOTH
// targets — the client statusbar item is how a shallow desktop install
// learns it's stale at all.
+ const stable = channel === 'stable'
const available = behind > 0 || !!updateAvailable
// A client with no version still identifies itself by sha; a backend can't.
@@ -86,17 +101,22 @@ export function resolveVersionStatus({
? copy.clientLabel(named)
: (version && `v${version}`) || named
- // Commits behind is the precise diff; `(update)` is the fallback for a
- // backend that knows it's stale but can't count (pip, non-git checkout).
- const hint = busy ? '' : behind > 0 ? ` (+${behind})` : available ? ` (${copy.update})` : ''
+ // Main channel: commits behind is the precise diff. Stable channel: a
+ // count of commits is the wrong vocabulary — a release is one step, so
+ // the hint is always the update word. `(update)` also covers a backend
+ // that knows it's stale but can't count (pip, non-git checkout).
+ const hint = busy ? '' : !stable && behind > 0 ? ` (+${behind})` : available ? ` (${copy.update})` : ''
const tooltip = [
busy && (applyMessage || copy.updateInProgress),
- !busy && behind > 0 && copy.commitsBehind(behind, (client ? branch : 'main') || '...'),
- !busy && behind <= 0 && available && copy.update,
+ !busy && available && stable && latestTag && copy.releaseAvailable(latestTag),
+ !busy && !stable && behind > 0 && copy.commitsBehind(behind, (client ? branch : 'main') || '...'),
+ !busy && available && (stable ? !latestTag : behind <= 0) && copy.update,
version && (client ? copy.desktopVersion(version) : copy.backendVersion(version)),
client && sha && copy.commit(sha),
- client && branch && copy.branch(branch)
+ // The branch line is main-channel vocabulary; a stable checkout sits on
+ // a tag, and naming a branch would contradict the release line.
+ client && !stable && branch && copy.branch(branch)
]
.filter(Boolean)
.join(' · ')
diff --git a/apps/desktop/src/store/notifications.test.ts b/apps/desktop/src/store/notifications.test.ts
index e11ed82b4ca..69ad268916d 100644
--- a/apps/desktop/src/store/notifications.test.ts
+++ b/apps/desktop/src/store/notifications.test.ts
@@ -1,4 +1,4 @@
-import { beforeEach, expect, test } from 'vitest'
+import { beforeEach, expect, test, vi } from 'vitest'
import { $notifications, clearNotifications, isDiskFullErrorMessage, notifyError } from './notifications'
@@ -55,3 +55,29 @@ test('session storage write failure is treated as disk-full class', () => {
expect(lastMessage()).toMatch(/Disk full/i)
})
+
+test('notifyError posts the full error to desktop.log, not the summary', () => {
+ const logLine = vi.fn()
+
+ const previous = (window as unknown as { hermesDesktop?: unknown }).hermesDesktop
+
+ ;(window as unknown as { hermesDesktop: { logLine: typeof logLine } }).hermesDesktop = { logLine }
+
+ try {
+ const error = new Error('sqlite3.OperationalError: database is locked')
+ error.stack = 'Error: sqlite3.OperationalError: database is locked\n at saveSession (session.ts:12)'
+
+ notifyError(error, 'Prompt failed')
+
+ expect(logLine).toHaveBeenCalledTimes(1)
+ expect(logLine.mock.calls[0][0]).toContain('Prompt failed')
+ expect(logLine.mock.calls[0][0]).toContain('database is locked')
+ expect(logLine.mock.calls[0][0]).toContain('session.ts:12')
+ } finally {
+ if (previous === undefined) {
+ delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop
+ } else {
+ ;(window as unknown as { hermesDesktop: unknown }).hermesDesktop = previous
+ }
+ }
+})
diff --git a/apps/desktop/src/store/notifications.ts b/apps/desktop/src/store/notifications.ts
index 50b3f36b546..098dc822c40 100644
--- a/apps/desktop/src/store/notifications.ts
+++ b/apps/desktop/src/store/notifications.ts
@@ -189,8 +189,24 @@ export function notify(input: NotificationInput): string {
return id
}
+// The toast only ever shows the summarized copy (possibly a fallback at 180
+// chars). desktop.log gets the FULL error — message and stack — so a bug
+// report carries the actual failure, not the summary. Fire-and-forget: the
+// toast must never depend on this round-trip.
+function logErrorToDesktopLog(error: unknown, fallback: string) {
+ try {
+ const label = new URLSearchParams(window.location.search).get('win') ?? 'main'
+ const raw = error instanceof Error ? (error.stack ?? error.message) : typeof error === 'string' ? error : fallback
+
+ window.hermesDesktop?.logLine?.(`[renderer error:${label}] ${fallback}: ${raw}`)
+ } catch {
+ // Logging must never break the toast.
+ }
+}
+
export function notifyError(error: unknown, fallback: string): string {
const readable = readableError(error, fallback)
+ logErrorToDesktopLog(error, fallback)
return notify({
kind: 'error',
diff --git a/apps/desktop/src/store/updates.ts b/apps/desktop/src/store/updates.ts
index f6e977f9757..e317c234e35 100644
--- a/apps/desktop/src/store/updates.ts
+++ b/apps/desktop/src/store/updates.ts
@@ -207,14 +207,14 @@ export function reportInstallMethodWarning(message: string | undefined): void {
* on every new commit. The snooze is persisted, so it survives relaunches too.
*/
export function maybeNotifyUpdateAvailable(status: DesktopUpdateStatus | null) {
- if (!status || status.supported === false || status.error || !status.targetSha) {
+ // Either signal means "update ready": behind > 0 (git checkout) or
+ // updateAvailable (app-installer, shallow clone).
+ if (!status || status.supported === false || status.error) {
return
}
const behind = typeof status.behind === 'number' ? status.behind : null
- // behind === null means "update available, exact count unknown" (shallow
- // clone). That still deserves the toast — just with count-free copy.
if ((behind ?? 0) <= 0 && !status.updateAvailable) {
return
}
@@ -240,9 +240,11 @@ export function maybeNotifyUpdateAvailable(status: DesktopUpdateStatus | null) {
id: UPDATE_TOAST_ID,
kind: 'info',
message:
- behind !== null && behind > 0
- ? translateNow('notifications.updateReadyMessage', behind)
- : translateNow('notifications.updateReadyMessageUnknown'),
+ status.mechanism === 'app-installer'
+ ? translateNow('notifications.updateReadyMessageAppInstaller')
+ : behind !== null && behind > 0
+ ? translateNow('notifications.updateReadyMessage', behind)
+ : translateNow('notifications.updateReadyMessageUnknown'),
onDismiss: () => snoozeUpdateToast(),
title: translateNow('notifications.updateReadyTitle')
})
diff --git a/apps/desktop/tsconfig.electron.json b/apps/desktop/tsconfig.electron.json
index 058f132dea4..54d6b3f0845 100644
--- a/apps/desktop/tsconfig.electron.json
+++ b/apps/desktop/tsconfig.electron.json
@@ -16,6 +16,6 @@
"rootDir": "..",
"outDir": "build/electron-types"
},
- "include": ["electron", "../shared/src/data-url-read-max.ts", "../shared/src/translucency.ts"],
+ "include": ["electron", "product-identity.cjs", "product-identity.d.cts", "../shared/src/data-url-read-max.ts", "../shared/src/translucency.ts"],
"exclude": ["src", "electron/**/*.e2e.mts"]
}
diff --git a/gateway/slash_commands.py b/gateway/slash_commands.py
index 88078335f7a..478c59ac01e 100644
--- a/gateway/slash_commands.py
+++ b/gateway/slash_commands.py
@@ -6089,6 +6089,25 @@ class GatewaySlashCommandsMixin:
return f"✗ {format_managed_message('update Hermes Agent')}"
project_root = Path(__file__).parent.parent.resolve()
+
+ # Not a git-managed install (docker/nix/desktop-app/source): refuse
+ # with the steward's own update mechanism instead of git-pulling a
+ # tree `hermes update` does not own.
+ try:
+ from hermes_cli.config import (
+ detect_install_method,
+ recommended_update_command_for_method,
+ )
+
+ method = detect_install_method(project_root)
+ if method not in {"git", "unknown"}:
+ return (
+ f"✗ `hermes update` does not apply to this install ({method}).\n"
+ f"Update with: {recommended_update_command_for_method(method)}"
+ )
+ except Exception:
+ pass # config unreadable — fall through to the .git check below
+
git_dir = project_root / '.git'
if not git_dir.exists():
diff --git a/gateway/status.py b/gateway/status.py
index 9f2d984f294..26eaf991dc7 100644
--- a/gateway/status.py
+++ b/gateway/status.py
@@ -91,7 +91,7 @@ def record_start_and_check_storm(
existing: list[float] = []
if path.exists():
- for line in path.read_text(encoding="utf-8").splitlines():
+ for line in path.read_text(encoding="utf-8-sig").splitlines():
line = line.strip()
if not line:
continue
@@ -364,7 +364,7 @@ def _get_process_start_time(pid: int) -> Optional[int]:
stat_path = Path(f"/proc/{pid}/stat")
try:
# Field 22 in /proc/<pid>/stat is process start time (clock ticks).
- return int(stat_path.read_text(encoding="utf-8").split()[21])
+ return int(stat_path.read_text(encoding="utf-8").split()[21]) # windows-footgun: ok (/proc is BOM-free)
except (FileNotFoundError, IndexError, PermissionError, ValueError, OSError):
pass
@@ -650,7 +650,7 @@ def _get_code_identity_fields() -> dict[str, Any]:
Never raises; degrades to absent fields.
"""
try:
- from hermes_cli.build_info import get_code_identity
+ from hermes_cli.version_info import get_code_identity
identity = get_code_identity()
return {
@@ -680,7 +680,7 @@ def _read_json_file(path: Path) -> Optional[dict[str, Any]]:
if not path.exists():
return None
try:
- raw = path.read_text(encoding="utf-8").strip()
+ raw = path.read_text(encoding="utf-8-sig").strip()
except (OSError, UnicodeDecodeError):
# OSError: file vanished or permission flipped between exists() and
# read. UnicodeDecodeError: file holds non-UTF-8 / binary garbage
@@ -705,7 +705,7 @@ def _read_pid_record(pid_path: Optional[Path] = None) -> Optional[dict]:
return None
try:
- raw = pid_path.read_text(encoding="utf-8").strip()
+ raw = pid_path.read_text(encoding="utf-8-sig").strip()
except (OSError, UnicodeDecodeError):
# File was deleted between exists() and read_text(), permission
# flipped, or it holds non-UTF-8 / binary garbage.
@@ -905,7 +905,7 @@ def _pid_exists(pid: int) -> bool:
# ``--replace`` would wait on a dead PID and abort with exit 1.
try:
stat_fields = (
- Path(f"/proc/{int(pid)}/stat").read_text(encoding="utf-8").split()
+ Path(f"/proc/{int(pid)}/stat").read_text(encoding="utf-8").split() # windows-footgun: ok (/proc is BOM-free)
)
if len(stat_fields) > 2 and stat_fields[2] == "Z":
return False
@@ -1629,7 +1629,7 @@ def acquire_scoped_lock(scope: str, identity: str, metadata: Optional[dict[str,
try:
_proc_status = Path(f"/proc/{existing_pid}/status")
if _proc_status.exists():
- for _line in _proc_status.read_text(encoding="utf-8").splitlines():
+ for _line in _proc_status.read_text(encoding="utf-8").splitlines(): # windows-footgun: ok (/proc is BOM-free)
if _line.startswith("State:"):
_state = _line.split()[1]
if _state in {"T", "t"}: # stopped or tracing stop
diff --git a/hermes_cli/boot_bootstrap.py b/hermes_cli/boot_bootstrap.py
new file mode 100644
index 00000000000..e79f1fe27e5
--- /dev/null
+++ b/hermes_cli/boot_bootstrap.py
@@ -0,0 +1,538 @@
+"""Boot-time post-update bootstrap.
+
+Every install kind (git checkout, desktop bundled payload, docker, nix)
+compares two per-install facts at boot:
+
+* current identity — the commit this install IS: ``install-stamp.json``
+ for sealed trees, git HEAD for checkouts. Reading it is a couple of
+ file reads (plus one rev-parse for checkouts).
+* last-known identity — the commit this install last bootstrapped,
+ recorded under ``installs/<sha16>/bootstrap/`` keyed by the canonical
+ install root.
+
+Equal → nothing happens (the fast path, ~2 ms). Different → run the
+idempotent post-update steps from ``hermes_cli.post_update`` under a
+single-flight lock, then record the new identity.
+
+Two records, one per step scope:
+
+* home record — ``bootstrap/<profile>.json``. Gates home-scoped steps.
+ HERMES_HOME moves per profile, so each profile bootstraps its own
+ state once per code change.
+* machine record — ``bootstrap/machine.json``. Every profile resolves
+ the same file, so machine-global steps run once per machine per code
+ change and the record's lock serializes concurrent profile boots.
+
+The records are an optimization, never the correctness layer: every step
+is idempotent and self-gating, so a deleted record costs one redundant
+slow path, nothing more.
+
+Ported from the restack branch's boot_bootstrap, rewritten onto this
+branch's vocabulary: stamps via ``hermes_cli.steward``, managed tools via
+``pm`` (facts.json ledger) instead of the retired ``installation`` package.
+"""
+from __future__ import annotations
+
+import hashlib
+import json
+import logging
+import os
+import subprocess
+import sys
+import time
+from pathlib import Path
+
+logger = logging.getLogger(__name__)
+
+RECORD_SCHEMA_VERSION = 1
+LOCK_STALE_SECONDS = 600
+
+
+def default_project_root() -> Path:
+ """The tree this code runs from: HERMES_INSTALL_ROOT for sealed
+ artifacts whose stamp lives outside the package dir (the override
+ hermes_cli.version_info honours), the code root otherwise."""
+ env = os.environ.get("HERMES_INSTALL_ROOT")
+ if env:
+ return Path(env)
+ return Path(__file__).resolve().parents[1]
+
+
+# ---------------------------------------------------------------------------
+# current identity
+# ---------------------------------------------------------------------------
+
+def read_git_head(root: Path) -> str | None:
+ """The commit SHA of the checkout at ``root``.
+
+ Asks git, rather than reimplementing it: parsing ``.git`` by hand
+ (worktree gitfiles, symbolic HEAD, packed-refs, commondir) is a
+ reimplementation of ``git rev-parse HEAD`` that reftable breaks
+ wholesale. The managed git comes first, a PATH git second; with
+ neither, the answer is None and boot carries on — fail-open.
+
+ Cost: one ~10ms subprocess. Only checkouts pay it — a sealed tree
+ reads its stamp and never gets here — and it happens once per boot.
+ """
+ git = _git_binary()
+ if git is None:
+ return None
+ try:
+ out = subprocess.run(
+ [git, "-C", str(root), "rev-parse", "HEAD"],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ check=False,
+ )
+ except (OSError, subprocess.SubprocessError):
+ return None
+ if out.returncode != 0:
+ return None
+ sha = out.stdout.strip()
+ return sha if len(sha) >= 7 else None
+
+
+def _git_binary() -> str | None:
+ """The git to run, or None when this machine has no usable one.
+
+ pm's pinned git first (the win32 Git-for-Windows package — where it
+ is installed, it is the one whose bash contract the rest of the tree
+ already trusts), then a PATH git. The imports are local: this module
+ is loaded early enough that a module-level import would widen the
+ boot import graph for a lookup most platforms answer from PATH.
+ """
+ try:
+ from pm.ensure import _facts, _store
+ from pm.registry import get_package
+ from pm.store import current_target
+
+ fact = _facts().get("git")
+ if fact is not None:
+ binary = get_package("git").binary(
+ _store().entry(fact["entry"]), current_target()
+ )
+ if binary is not None and binary.is_file():
+ return str(binary)
+ except Exception as exc: # noqa: BLE001 — boot must not die on a lookup
+ logger.debug("pm git lookup failed: %s", exc)
+ import shutil
+
+ return shutil.which("git")
+
+
+def current_install_identity(project_root: Path) -> str | None:
+ """What code this install is: stamp commit for sealed trees, git HEAD
+ for checkouts, None for broken trees (never bootstrap, never write)."""
+ from hermes_cli.steward import read_install_stamp
+
+ root = Path(project_root)
+ if (root / ".git").exists():
+ return read_git_head(root)
+ stamp = read_install_stamp(root)
+ commit = stamp.get("commit")
+ if isinstance(commit, str) and len(commit) >= 7:
+ return commit
+ # A tagless/commitless stamp is a broken artifact; the tag alone is
+ # accepted as a weaker identity (bundled artifacts always carry one).
+ tag = stamp.get("tag")
+ return tag if isinstance(tag, str) and tag else None
+
+
+# ---------------------------------------------------------------------------
+# the per-install state folder: installs/<SHA16>/ under the DEFAULT home
+# ---------------------------------------------------------------------------
+
+def _install_key(project_root: Path) -> str:
+ try:
+ canonical = str(Path(project_root).resolve())
+ except OSError:
+ canonical = str(project_root)
+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:16]
+
+
+INSTALLS_DIR_NAME = "installs"
+
+
+def installs_root() -> Path:
+ """The parent of every per-install state folder.
+
+ Anchored to the DEFAULT home, not the active profile home: profiles
+ share one folder per install, with per-profile bootstrap records as
+ files INSIDE it (bootstrap/<profile>.json) rather than per-profile
+ folders. That keeps profile semantics while collapsing the anchor
+ count to one.
+ """
+ from hermes_cli.profiles import _get_default_hermes_home
+
+ return _get_default_hermes_home() / INSTALLS_DIR_NAME
+
+
+def install_state_dir(project_root: Path) -> Path:
+ """``installs/<SHA16>/`` for this install. Derivation only — no I/O."""
+ return installs_root() / _install_key(project_root)
+
+
+def ensure_install_dir(project_root: Path) -> Path:
+ """The state folder, created with its identity record on first touch.
+
+ install.json is the REVERSE map (sha16 → canonical root) that makes
+ orphan GC possible: `hermes doctor` enumerates installs/*/install.json
+ and flags entries whose recorded root no longer exists. Written once,
+ under the same single-flight lock the records use; the steward comes
+ from hermes_cli.steward so the record says who owns the tree, not who
+ touched it first.
+ """
+ state = install_state_dir(project_root)
+ marker = state / "install.json"
+ if marker.is_file():
+ return state
+ state.mkdir(parents=True, exist_ok=True)
+ lock = _RecordLock(state / ".install-json.lock")
+ if not lock.acquire():
+ return state # someone else is writing it right now — theirs wins
+ try:
+ if not marker.is_file():
+ from datetime import datetime, timezone
+
+ from hermes_cli.steward import sealed_steward
+
+ steward = sealed_steward(Path(project_root))
+ payload = {
+ "root": str(Path(project_root).resolve()),
+ "steward": steward if steward is not None else "checkout",
+ "firstSeen": datetime.now(timezone.utc).isoformat(),
+ }
+ tmp = marker.with_suffix(".json.tmp")
+ tmp.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
+ os.replace(tmp, marker)
+ finally:
+ lock.release()
+ return state
+
+
+def orphaned_installs() -> list[tuple[Path, str]]:
+ """State folders whose recorded root no longer exists.
+
+ ``(folder, recorded_root)`` pairs for `hermes doctor`'s sweep. A
+ folder without a readable install.json is orphaned by definition —
+ nothing can ever claim it again, because claiming goes through
+ ensure_install_dir which writes the record first.
+ """
+ root = installs_root()
+ if not root.is_dir():
+ return []
+ orphans: list[tuple[Path, str]] = []
+ for entry in sorted(root.iterdir()):
+ if not entry.is_dir():
+ continue
+ try:
+ recorded = json.loads(
+ (entry / "install.json").read_text(encoding="utf-8-sig")
+ ).get("root", "")
+ except (OSError, ValueError):
+ orphans.append((entry, "<unreadable install.json>"))
+ continue
+ if not recorded or not Path(recorded).exists():
+ orphans.append((entry, recorded or "<empty>"))
+ return orphans
+
+
+def orphaned_store_entries() -> list[tuple[Path, int]]:
+ """Tool-store entries the installed-state ledger no longer references.
+
+ ``(entry_dir, size_bytes)`` pairs for `hermes doctor`'s sweep. pm's
+ facts.json is the only authority consulted — the same ledger
+ ``pm.ensure`` resolves by, so this can never flag an entry pm would
+ still hand out. An entry is REFERENCED when facts records it (tool
+ entries) or when it is a ``fetch-*`` archive cache entry backing a
+ referenced install. Everything else is bytes no lookup can ever
+ return: superseded versions left behind by pin bumps.
+
+ Doubt errs toward KEEP: a facts file that exists but cannot be read
+ aborts the whole sweep (empty result), because its references are
+ unknowable and any entry might be one of them. No facts file at all
+ means pm never installed anything — nothing is referenced, but there
+ is also nothing to GC against, so the sweep reports nothing.
+ """
+ from pm import paths as pm_paths
+ from pm.lock import Facts
+
+ store = pm_paths.store_root()
+ if not store.is_dir():
+ return []
+ facts_file = pm_paths.facts_path()
+ if not facts_file.is_file():
+ return []
+ try:
+ raw = json.loads(facts_file.read_text(encoding="utf-8-sig"))
+ if not isinstance(raw, dict):
+ return []
+ except (OSError, ValueError):
+ # Unreadable ledger: references unknowable — keep everything.
+ return []
+ referenced = Facts(facts_file).entries_in_use()
+
+ orphans: list[tuple[Path, int]] = []
+ for entry in sorted(store.iterdir()):
+ # Scratch dirs (.staging-*), the ledger itself, and stray files
+ # are pm's own cleanup problem, never GC candidates. fetch-*
+ # archive cache entries are content-addressed and cheap to keep;
+ # skip them too (re-fetch avoidance is their whole point).
+ if not entry.is_dir() or entry.name.startswith("."):
+ continue
+ if entry.name.startswith("fetch-"):
+ continue
+ if entry.name in referenced:
+ continue
+ size = 0
+ for f in entry.rglob("*"):
+ try:
+ if f.is_file() and not f.is_symlink():
+ size += f.stat().st_size
+ except OSError:
+ continue
+ orphans.append((entry, size))
+ return orphans
+
+
+def record_path(project_root: Path, scope: str) -> Path:
+ """Where the last-known record for ``project_root`` lives.
+
+ Both scopes live INSIDE the per-install state folder:
+ ``bootstrap/machine.json`` for machine scope, ``bootstrap/<profile>.json``
+ for home scope — the per-profile semantics ride the FILENAME, not a
+ per-profile anchor directory.
+ """
+ if scope == "home":
+ from hermes_cli.profiles import get_active_profile_name
+
+ name = get_active_profile_name() or "default"
+ filename = f"{name}.json"
+ elif scope == "machine":
+ filename = "machine.json"
+ else:
+ raise ValueError(f"unknown record scope: {scope!r}")
+ return install_state_dir(project_root) / "bootstrap" / filename
+
+
+def read_last_known(path: Path) -> dict:
+ try:
+ data = json.loads(Path(path).read_text(encoding="utf-8-sig"))
+ except (OSError, ValueError):
+ return {}
+ return data if isinstance(data, dict) else {}
+
+
+def _write_record(path: Path, identity: str, results: dict) -> None:
+ payload = {
+ "schemaVersion": RECORD_SCHEMA_VERSION,
+ "identity": identity,
+ "bootstrappedAt": time.strftime("%Y-%m-%dT%H:%M:%S%z"),
+ "results": results,
+ }
+ path.parent.mkdir(parents=True, exist_ok=True)
+ tmp = path.with_name(path.name + ".tmp")
+ tmp.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
+ os.replace(tmp, path)
+
+
+def write_record(project_root: Path, scope: str, identity: str, results: dict | None = None) -> None:
+ """Record ``identity`` as bootstrapped. Also used by the update phase
+ after it runs the steps itself, so the next boot skips."""
+ _write_record(record_path(project_root, scope), identity, results or {})
+
+
+def needs_bootstrap(project_root: Path, scope: str) -> str | None:
+ """The new identity when this install changed since its last bootstrap,
+ else None. None identity (broken tree) never bootstraps."""
+ identity = current_install_identity(project_root)
+ if not identity:
+ return None
+ known = read_last_known(record_path(project_root, scope))
+ if known.get("identity") == identity:
+ return None
+ return identity
+
+
+# ---------------------------------------------------------------------------
+# single-flight lock
+# ---------------------------------------------------------------------------
+
+class _RecordLock:
+ """O_CREAT|O_EXCL existence-as-mutex next to a record file.
+
+ Losers skip (boot never waits on another process's bootstrap; the steps
+ are idempotent, so a botched winner only costs redundant work later).
+ A stale lock — older than LOCK_STALE_SECONDS — is broken and re-tried
+ once: a crashed winner died before its record write, so re-running is
+ correct.
+ """
+
+ def __init__(self, record: Path):
+ self.path = record.with_name(record.name + ".lock")
+ self.acquired = False
+
+ def _try_create(self) -> bool:
+ try:
+ self.path.parent.mkdir(parents=True, exist_ok=True)
+ fd = os.open(self.path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
+ except FileExistsError:
+ return False
+ except OSError:
+ return False
+ try:
+ os.write(fd, json.dumps({"pid": os.getpid(), "startedAt": time.time()}).encode("utf-8"))
+ finally:
+ os.close(fd)
+ return True
+
+ def _is_stale(self) -> bool:
+ try:
+ body = json.loads(self.path.read_text(encoding="utf-8-sig"))
+ started = float(body.get("startedAt", 0))
+ except (OSError, ValueError):
+ # Unreadable lock: age it by mtime instead.
+ try:
+ started = self.path.stat().st_mtime
+ except OSError:
+ return False
+ return (time.time() - started) > LOCK_STALE_SECONDS
+
+ def acquire(self) -> bool:
+ if self._try_create():
+ self.acquired = True
+ return True
+ if self._is_stale():
+ try:
+ self.path.unlink()
+ except OSError:
+ return False
+ if self._try_create():
+ self.acquired = True
+ return True
+ return False
+
+ def release(self) -> None:
+ if not self.acquired:
+ return
+ try:
+ self.path.unlink()
+ except OSError:
+ pass
+ self.acquired = False
+
+
+# ---------------------------------------------------------------------------
+# the boot entry point
+# ---------------------------------------------------------------------------
+
+def _report_sealed_runtime_drift(project_root: Path) -> str | None:
+ """Check a SEALED tree's managed tools against pm's lockfile, loudly.
+
+ pm's artifact-time gates (bundle staging, docker build, nix check)
+ are the wall; this is the boot-time backstop for artifacts assembled
+ around them: every boot of a drifted sealed tree prints the problem
+ list to stderr, so the drift is impossible to not-know about.
+
+ Report, not refusal: this runs inside the never-raises boot path, and
+ a sealed gateway that boots on stale tools is degraded — but a
+ gateway that refuses to boot over a tool version is DOWN, remotely,
+ with the fix (rebuild the artifact) out of the machine's own reach.
+
+ Returns the message when drift was found (for the boot summary), None
+ otherwise. Checkouts return None without reading anything — they
+ provision on demand and drift is their normal, self-healing state.
+ """
+ root = Path(project_root)
+ if (root / ".git").exists():
+ return None
+ try:
+ from hermes_cli.steward import sealed_steward
+
+ steward = sealed_steward(root)
+ if steward is None:
+ return None
+ import pm
+
+ problems = pm.check()
+ except Exception as exc: # noqa: BLE001 — a backstop must not become a gate
+ logger.debug("sealed runtime drift check failed: %s", exc)
+ return None
+ if not problems:
+ return None
+ message = (
+ f"this {steward}-managed install's tools drifted from its pin table: "
+ + "; ".join(problems)
+ + " — rebuild the artifact to fix"
+ )
+ print(f"\n✗ {message}\n", file=sys.stderr)
+ return message
+
+
+def run_boot_bootstrap(project_root: Path) -> dict:
+ """Run due home- and machine-scoped steps for this install. Returns a
+ summary dict (for tests/logs); use maybe_run_boot_bootstrap at call
+ sites."""
+ from hermes_cli import post_update
+
+ summary: dict = {"home": "skipped", "machine": "skipped"}
+
+ drift_message = _report_sealed_runtime_drift(Path(project_root))
+ if drift_message:
+ summary["sealed_runtime_drift"] = drift_message
+
+ for scope, steps, deferred in (
+ ("home", post_update.HOME_STEPS, False),
+ ("machine", post_update.MACHINE_STEPS, True),
+ ):
+ identity = needs_bootstrap(project_root, scope)
+ if not identity:
+ continue
+ record = record_path(project_root, scope)
+ lock = _RecordLock(record)
+ if not lock.acquire():
+ summary[scope] = "lost-race"
+ continue
+ try:
+ # Double-check under the lock: the previous holder may have
+ # finished between our read and our acquire.
+ if read_last_known(record).get("identity") == identity:
+ summary[scope] = "done-by-other"
+ continue
+ logger.info(
+ "post-update bootstrap (%s scope): code changed to %s, running steps",
+ scope, identity[:12],
+ )
+ if deferred:
+ # Slow machine steps (network installers) must not block
+ # boot readiness: record first, then run detached. A crash
+ # mid-step leaves the record written — intended: the record
+ # gates "did we trigger for this identity", and the steps
+ # re-gate themselves (pm.check stamp comparisons) next change.
+ _write_record(record, identity, {"deferred": True})
+ import threading
+
+ threading.Thread(
+ target=post_update.run_steps,
+ args=(steps,),
+ name=f"hermes-bootstrap-{scope}",
+ daemon=True,
+ ).start()
+ summary[scope] = "deferred"
+ else:
+ results = post_update.run_steps(steps)
+ _write_record(record, identity, results)
+ summary[scope] = results
+ finally:
+ lock.release()
+ return summary
+
+
+def maybe_run_boot_bootstrap(project_root: Path) -> None:
+ """The one call boot paths use. Never raises: a bootstrap problem must
+ not stop the gateway/serve/CLI from starting."""
+ try:
+ run_boot_bootstrap(Path(project_root))
+ except Exception as exc:
+ logger.warning("boot bootstrap failed (continuing boot): %s", exc)
diff --git a/hermes_cli/build_info.py b/hermes_cli/build_info.py
deleted file mode 100644
index e2ae06ba73e..00000000000
--- a/hermes_cli/build_info.py
+++ /dev/null
@@ -1,168 +0,0 @@
-"""
-Baked-in build metadata for Hermes Agent.
-
-Source installs report their git revision live via ``git rev-parse`` (see
-``hermes_cli/dump.py`` and ``hermes_cli/banner.py``). That doesn't work inside
-the published Docker image because ``.dockerignore`` excludes ``.git``, so
-those callsites fall back to ``"(unknown)"`` / drop the banner suffix entirely.
-
-To make ``hermes dump`` and the startup banner identify the exact commit the
-image was built from, the Docker build writes the build-time ``$HERMES_GIT_SHA``
-arg into ``<project_root>/.hermes_build_sha``. This module is the single
-read-side helper consumed by both callsites — keeping the lookup in one place
-so the file path and missing-file behaviour stay consistent.
-
-Behaviour:
-
-- Returns ``None`` when the file is absent. Source installs and dev images
- built without the ``HERMES_GIT_SHA`` build-arg fall through to live-git
- resolution in the caller, so non-Docker installs are unaffected.
-- Returns ``None`` on any IO / decoding error. The build-sha is a nice-to-have
- for support triage; nothing in the CLI is allowed to crash because of it.
-- Truncates to ``short`` characters (default 8) to match the format used by
- ``git rev-parse --short=8`` throughout the codebase.
-"""
-
-from __future__ import annotations
-
-from pathlib import Path
-from typing import Optional
-
-# Path is resolved relative to this module so it works regardless of cwd —
-# matches the pattern used by ``banner._resolve_repo_dir``.
-_BUILD_SHA_FILE = Path(__file__).parent.parent / ".hermes_build_sha"
-
-
-_code_identity_cache: Optional[dict] = None
-
-
-def _resolve_git_head_sha(project_root: Path) -> Optional[str]:
- """Resolve the checkout's HEAD commit sha by reading .git directly.
-
- Deliberately NOT ``git rev-parse`` in a subprocess: this helper runs
- inside library paths (gateway runtime-status writes, update receipts)
- where spawning processes is both slow and hostile to tests that mock
- ``subprocess.run`` tightly (call-count asserts, sequenced side effects).
- Handles regular checkouts, worktrees/submodules (``.git`` file with a
- ``gitdir:`` pointer + ``commondir``), loose refs, and packed-refs.
- Returns None on any failure.
- """
- try:
- git_path = project_root / ".git"
- if git_path.is_file():
- # Worktree/submodule: ".git" is a pointer file.
- pointer = git_path.read_text(encoding="utf-8", errors="replace").strip()
- if not pointer.startswith("gitdir:"):
- return None
- git_dir = Path(pointer[len("gitdir:"):].strip())
- if not git_dir.is_absolute():
- git_dir = (project_root / git_dir).resolve()
- elif git_path.is_dir():
- git_dir = git_path
- else:
- return None
-
- # Refs live in the COMMON git dir for worktrees.
- common_dir = git_dir
- commondir_file = git_dir / "commondir"
- if commondir_file.is_file():
- rel = commondir_file.read_text(encoding="utf-8", errors="replace").strip()
- common = Path(rel)
- if not common.is_absolute():
- common = (git_dir / common).resolve()
- common_dir = common
-
- head = (git_dir / "HEAD").read_text(encoding="utf-8", errors="replace").strip()
- if not head.startswith("ref:"):
- # Detached HEAD: the file holds the sha itself.
- return head if len(head) == 40 else None
- ref_name = head[len("ref:"):].strip()
-
- loose = common_dir / ref_name
- if loose.is_file():
- sha = loose.read_text(encoding="utf-8", errors="replace").strip()
- return sha if len(sha) == 40 else None
-
- packed = common_dir / "packed-refs"
- if packed.is_file():
- for line in packed.read_text(encoding="utf-8", errors="replace").splitlines():
- line = line.strip()
- if not line or line.startswith(("#", "^")):
- continue
- parts = line.split(" ", 1)
- if len(parts) == 2 and parts[1].strip() == ref_name:
- sha = parts[0].strip()
- return sha if len(sha) == 40 else None
- except Exception:
- return None
- return None
-
-
-def get_code_identity(refresh: bool = False) -> dict:
- """Return the running checkout's code identity as a dict.
-
- Shape: ``{"sha": full-or-short sha | None, "short_sha": str | None,
- "version": pyproject version | None, "source": "git" | "build-file" |
- "unknown"}``.
-
- Resolution order mirrors the banner/dump callsites: live ``git
- rev-parse`` for source installs, the baked ``.hermes_build_sha`` for
- Docker images (no ``.git`` inside the published image), else unknown.
-
- Cached per process — code identity cannot change while a process is
- running (an updated checkout requires a restart to take effect, which
- is exactly the property the fleet version verification relies on).
- Never raises; every field degrades to ``None`` independently.
- """
- global _code_identity_cache
- if _code_identity_cache is not None and not refresh:
- return dict(_code_identity_cache)
-
- sha: Optional[str] = None
- source = "unknown"
- project_root = Path(__file__).parent.parent
- resolved = _resolve_git_head_sha(project_root)
- if resolved:
- sha = resolved
- source = "git"
- if sha is None:
- baked = get_build_sha(short=0)
- if baked:
- sha = baked
- source = "build-file"
-
- version: Optional[str] = None
- try:
- import tomllib
-
- with open(project_root / "pyproject.toml", "rb") as fh: # windows-footgun: ok — binary mode, tomllib requires bytes
- raw_version = tomllib.load(fh).get("project", {}).get("version")
- version = str(raw_version) if raw_version else None
- except Exception:
- version = None
-
- _code_identity_cache = {
- "sha": sha,
- "short_sha": sha[:8] if sha else None,
- "version": version,
- "source": source,
- }
- return dict(_code_identity_cache)
-
-
-def get_build_sha(short: int = 8) -> Optional[str]:
- """Return the baked-in build SHA, truncated to ``short`` chars, or None.
-
- Reads ``<project_root>/.hermes_build_sha`` if present. The file is
- written by the Dockerfile's ``HERMES_GIT_SHA`` build-arg and contains
- the full 40-character commit hash on a single line.
- """
- try:
- if not _BUILD_SHA_FILE.is_file():
- return None
- sha = _BUILD_SHA_FILE.read_text(encoding="utf-8").strip()
- except Exception:
- return None
- if not sha:
- return None
- return sha[:short] if short and short > 0 else sha
diff --git a/hermes_cli/bundled_app.py b/hermes_cli/bundled_app.py
new file mode 100644
index 00000000000..8a3a26c7e8d
--- /dev/null
+++ b/hermes_cli/bundled_app.py
@@ -0,0 +1,179 @@
+"""Where the running BUNDLED desktop app lives, and how to start it.
+
+A bundled artifact runs its agent out of ``<app>/resources/agent-payload``,
+so a Python process inside that payload sits at a known offset from the app
+the user double-clicks. This module turns that offset into the launcher path
+and starts it — the two things every in-bundle caller needs and each one
+used to work out for itself.
+
+The shape authority is the build stamp (``payload: bundled``, read through
+:func:`hermes_cli.steward.is_bundled_payload`), never a filesystem probe: a
+probe answers "is this artifact intact?", not "which shape am I?". Callers
+gate on the stamp, then ask here WHERE the app is. A stamp that says bundled
+over a tree that is not one is damage, and :func:`resolve_bundle_layout`
+says so instead of degrading to a checkout.
+
+Two consumers today: ``hermes desktop`` (start the app this CLI ships
+inside) and the sealed self-updater (stop the app, then relaunch it).
+"""
+
+from __future__ import annotations
+
+import os
+import subprocess
+import sys
+from dataclasses import dataclass
+from pathlib import Path
+
+__all__ = [
+ "BundleLayout",
+ "NotBundledApp",
+ "PAYLOAD_DIR_NAME",
+ "launch_detached",
+ "resolve_bundle_layout",
+]
+
+#: The resources-resident payload directory every bundled artifact ships.
+PAYLOAD_DIR_NAME = "agent-payload"
+
+#: Executables that sit beside a Linux Electron launcher without being one.
+#: AppRun is the AppImage entry stub, which re-execs the launcher below.
+_LINUX_NON_LAUNCHERS = frozenset({"AppRun", "chrome-sandbox", "chrome_crashpad_handler"})
+
+
+class NotBundledApp(Exception):
+ """Raised when a tree is not a bundled desktop payload."""
+
+
+@dataclass(frozen=True)
+class BundleLayout:
+ """The three directories and the launcher of a bundled desktop app.
+
+ ``launcher`` is None when the app directory holds no single obvious
+ executable. That is a real state on a damaged or unusual install, and
+ both callers would rather report it than act on a guess.
+ """
+
+ app_root: Path
+ resources: Path
+ payload: Path
+ launcher: Path | None
+
+
+def resolve_bundle_layout(
+ project_root: Path | str, *, platform: str | None = None
+) -> BundleLayout:
+ """Locate the desktop app that contains the payload at *project_root*.
+
+ *project_root* is the payload's ``repo/`` tree — the install root a
+ bundled backend runs from. The app sits two directories above the
+ payload on Windows and Linux, and four above it on macOS, where the
+ payload lands in ``Hermes.app/Contents/Resources``.
+
+ The macOS offset is detected from the directory names themselves
+ rather than from *platform*, so a layout can be resolved for any host
+ from any host. *platform* (default :data:`sys.platform`) only decides
+ the launcher-naming rule.
+
+ Raises :class:`NotBundledApp` when the tree is not a bundled payload —
+ a source checkout, or the docker/nix sealed shape, which has no app.
+ """
+ repo = Path(project_root).resolve()
+ payload = repo.parent
+ if payload.name != PAYLOAD_DIR_NAME:
+ raise NotBundledApp(
+ f"{repo} is not inside a {PAYLOAD_DIR_NAME}/ payload — no desktop app contains it"
+ )
+
+ resources = payload.parent
+ app_root = resources.parent
+ # macOS: .../Hermes.app/Contents/Resources/agent-payload/repo
+ if (
+ resources.name == "Resources"
+ and app_root.name == "Contents"
+ and app_root.parent.suffix == ".app"
+ ):
+ app_root = app_root.parent
+
+ if not app_root.is_dir():
+ raise NotBundledApp(f"no app directory above the payload at {payload}")
+
+ return BundleLayout(
+ app_root=app_root,
+ resources=resources,
+ payload=payload,
+ launcher=_resolve_launcher(app_root, platform or sys.platform),
+ )
+
+
+def _resolve_launcher(app_root: Path, platform: str) -> Path | None:
+ """The executable that starts the app, or None when it is ambiguous.
+
+ One rule per platform, each one "the single launcher among files that
+ are not launchers":
+
+ * macOS — the one file in ``Contents/MacOS``.
+ * Windows — the one top-level ``.exe`` that is not the uninstaller.
+ * Linux — the one top-level executable that is not an Electron helper
+ or a shared library.
+ """
+ if platform == "darwin":
+ return _only(_files(app_root / "Contents" / "MacOS"))
+
+ if platform == "win32":
+ return _only(
+ [
+ p
+ for p in _files(app_root)
+ if p.suffix.lower() == ".exe"
+ and not p.name.lower().startswith("uninstall")
+ ]
+ )
+
+ return _only(
+ [
+ p
+ for p in _files(app_root)
+ if p.name not in _LINUX_NON_LAUNCHERS
+ and ".so" not in p.name
+ and os.access(p, os.X_OK)
+ ]
+ )
+
+
+def _files(directory: Path) -> list[Path]:
+ """Regular files directly in *directory*; empty when it is unreadable."""
+ try:
+ return sorted(p for p in directory.iterdir() if p.is_file())
+ except OSError:
+ return []
+
+
+def _only(candidates: list[Path]) -> Path | None:
+ return candidates[0] if len(candidates) == 1 else None
+
+
+def launch_detached(
+ argv: list[str], *, env: dict[str, str] | None = None, cwd: Path | str | None = None
+) -> int:
+ """Start *argv* as its own process and return its pid.
+
+ The child outlives this process: it leads a new session on POSIX, and
+ on Windows it gets the detach creation flags (new process group, own
+ hidden console, breakaway from any job object). Its stdio goes to the
+ null device, because the terminal that ran ``hermes desktop`` is free
+ to close the moment this call returns.
+ """
+ from hermes_cli._subprocess_compat import windows_detach_popen_kwargs
+
+ child = subprocess.Popen(
+ argv,
+ cwd=str(cwd) if cwd is not None else None,
+ env=env,
+ stdin=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ close_fds=True,
+ **windows_detach_popen_kwargs(),
+ )
+ return child.pid
diff --git a/hermes_cli/doctor.py b/hermes_cli/doctor.py
index 25a7b2a1f48..ca447e87495 100644
--- a/hermes_cli/doctor.py
+++ b/hermes_cli/doctor.py
@@ -69,17 +69,11 @@ _PROVIDER_ENV_HINTS = (
"TOKENHUB_API_KEY",
)
-
-from hermes_constants import is_termux as _is_termux
-
-
def _python_install_cmd() -> str:
- return "python -m pip install" if _is_termux() else "uv pip install"
+ return "uv pip install"
def _system_package_install_cmd(pkg: str) -> str:
- if _is_termux():
- return f"pkg install {pkg}"
if sys.platform == "darwin":
return f"brew install {pkg}"
return f"sudo apt install {pkg}"
@@ -241,26 +235,6 @@ def _safe_which(cmd: str) -> str | None:
return None
-def _termux_browser_setup_steps(node_installed: bool) -> list[str]:
- steps: list[str] = []
- step = 1
- if not node_installed:
- steps.append(f"{step}) pkg install nodejs")
- step += 1
- steps.append(f"{step}) npm install -g agent-browser")
- steps.append(f"{step + 1}) agent-browser install")
- return steps
-
-
-def _termux_install_all_fallback_notes() -> list[str]:
- return [
- "Termux install profile: use .[termux-all] for broad compatibility (installer default on Termux).",
- "Matrix E2EE extra is excluded on Termux (python-olm currently fails to build).",
- "Local faster-whisper extra is excluded on Termux (ctranslate2/av build path unavailable).",
- "STT fallback: use Groq Whisper (set GROQ_API_KEY) or OpenAI Whisper (set VOICE_TOOLS_OPENAI_KEY).",
- ]
-
-
def _has_provider_env_config(content: str) -> bool:
"""Return True when ~/.hermes/.env contains provider auth/base URL settings."""
return any(key in content for key in _PROVIDER_ENV_HINTS)
@@ -2240,14 +2214,8 @@ def run_doctor(args):
break
# Determine the expected command link directory (mirrors install.sh logic)
- _prefix = os.environ.get("PREFIX", "")
- _is_termux_env = bool(os.environ.get("TERMUX_VERSION")) or "com.termux/files/usr" in _prefix
- if _is_termux_env and _prefix:
- _cmd_link_dir = Path(_prefix) / "bin"
- _cmd_link_display = "$PREFIX/bin"
- else:
- _cmd_link_dir = Path.home() / ".local" / "bin"
- _cmd_link_display = "~/.local/bin"
+ _cmd_link_dir = Path.home() / ".local" / "bin"
+ _cmd_link_display = "~/.local/bin"
_cmd_link = _cmd_link_dir / "hermes"
if _venv_bin is None:
@@ -2360,8 +2328,6 @@ def run_doctor(args):
)
elif _safe_which("docker"):
check_ok("docker", "(optional)")
- elif _is_termux():
- check_info("Docker backend is not available inside Termux (expected on Android)")
elif running_in_container:
pass # already explained above
else:
@@ -2556,12 +2522,6 @@ def run_doctor(args):
"agent-browser found but not runnable",
f"(broken symlink at {_resolved_ab}? run: npx agent-browser --version)",
)
- elif _is_termux():
- check_info("agent-browser is not installed (expected in the tested Termux path)")
- check_info("Install it manually later with: npm install -g agent-browser && agent-browser install")
- check_info("Termux browser setup:")
- for step in _termux_browser_setup_steps(node_installed=True):
- check_info(step)
else:
check_warn("agent-browser not installed", "(requires npm/npx on PATH)")
@@ -2569,9 +2529,8 @@ def run_doctor(args):
# agent-browser is found but no Playwright-managed Chromium is on disk
# (tools/browser_tool.py::check_browser_requirements filters them out
# before the agent ever sees them). Reuse the exact predicate it uses
- # so the two checks cannot diverge. Skip on Termux (not a tested
- # path).
- if agent_browser_ok and not _is_termux():
+ # so the two checks cannot diverge.
+ if agent_browser_ok:
try:
# Lazy import: browser_tool is a ~150KB module we don't want
# to eagerly load in every `hermes doctor` invocation.
@@ -2614,12 +2573,6 @@ def run_doctor(args):
f"Install with: cd {PROJECT_ROOT} && "
"npx playwright install --with-deps chromium"
)
- elif _is_termux():
- check_info("Node.js not found (browser tools are optional in the tested Termux path)")
- check_info("Install Node.js on Termux with: pkg install nodejs")
- check_info("Termux browser setup:")
- for step in _termux_browser_setup_steps(node_installed=False):
- check_info(step)
else:
check_warn("Node.js not found", "(optional, needed for browser tools)")
@@ -2722,11 +2675,6 @@ def run_doctor(args):
except Exception:
pass
- if _is_termux():
- check_info("Termux compatibility fallbacks:")
- for note in _termux_install_all_fallback_notes():
- check_info(note)
-
_section("API Connectivity")
# Refactor: every connectivity probe below is HTTP-bound and fully
# independent. Running them in series spent ~5s wall on a typical
diff --git a/hermes_cli/dump.py b/hermes_cli/dump.py
index e29675ce130..0d034bb2184 100644
--- a/hermes_cli/dump.py
+++ b/hermes_cli/dump.py
@@ -32,7 +32,7 @@ def _dotenv_key_names() -> set[str]:
"""
try:
env_path = get_env_path()
- text = env_path.read_text(encoding="utf-8", errors="ignore")
+ text = env_path.read_text(encoding="utf-8-sig", errors="ignore")
except (OSError, UnicodeError):
return set()
@@ -54,61 +54,38 @@ def _dotenv_key_names() -> set[str]:
def _get_git_commit(project_root: Path) -> str:
"""Return short git commit hash, or '(unknown)'.
- Source installs and dev images resolve this live via ``git rev-parse``.
- The published Docker image excludes ``.git`` from the build context, so
- that lookup always fails — we fall back to the baked-in build SHA written
- to ``<project_root>/.hermes_build_sha`` by the Dockerfile's
- ``HERMES_GIT_SHA`` build-arg (see ``hermes_cli/build_info.py``).
- The output format is identical regardless of source.
+ Uses ``version_info.get_version_info()`` which reads the install stamp
+ first (Docker/Nix), then falls back to live ``git rev-parse`` for source
+ installs.
"""
try:
- result = subprocess.run(
- ["git", "rev-parse", "--short=8", "HEAD"],
- capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=5,
- cwd=str(project_root),
- )
- if result.returncode == 0:
- value = result.stdout.strip()
- if value:
- return value
- except Exception:
- pass
+ from hermes_cli.version_info import get_version_info
- # Fall back to the build-time baked SHA (populated in published Docker
- # images, absent otherwise). Defers the import so the dump module
- # stays cheap on non-dump code paths.
- try:
- from hermes_cli.build_info import get_build_sha
- baked = get_build_sha(short=8)
- if baked:
- return baked
+ info = get_version_info()
+ if info.commit:
+ return info.commit[:8]
except Exception:
pass
-
return "(unknown)"
def _get_git_commit_date(project_root: Path) -> str:
"""Return the date the HEAD commit was authored (YYYY-MM-DD), or ''.
- Resolves live via ``git log`` on source installs. The published Docker
- image excludes ``.git``, so this returns '' there — the dump line simply
- drops the date suffix in that case (the baked SHA still identifies the
- build).
+ Uses ``version_info.get_version_info()`` which carries the commit date
+ as a Unix timestamp from the install stamp (Docker/Nix) or live git
+ (source installs). Formats as YYYY-MM-DD for display.
"""
try:
- result = subprocess.run(
- ["git", "log", "-1", "--format=%cd", "--date=short", "HEAD"],
- capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=5,
- cwd=str(project_root),
- )
- if result.returncode == 0:
- value = result.stdout.strip()
- if value:
- return value
+ from hermes_cli.version_info import get_version_info
+
+ info = get_version_info()
+ if info.commit_date:
+ from datetime import datetime, timezone
+
+ return datetime.fromtimestamp(info.commit_date, tz=timezone.utc).strftime("%Y-%m-%d")
except Exception:
pass
-
return ""
diff --git a/hermes_cli/gui_uninstall.py b/hermes_cli/gui_uninstall.py
index aa587d655f0..3049fb10d9f 100644
--- a/hermes_cli/gui_uninstall.py
+++ b/hermes_cli/gui_uninstall.py
@@ -199,6 +199,13 @@ def gui_install_summary(hermes_home: "Path | None" = None) -> dict:
packaged = [p for p in packaged_gui_app_paths() if p.exists()]
userdata = desktop_userdata_dir()
+ # Steward facts, so the UI can gate its destructive options on the same
+ # ladder the CLI uninstaller uses: only a git checkout may have its code
+ # removed; sealed trees (nix / desktop-app / docker) get data-only.
+ from hermes_cli import steward as steward_mod
+
+ steward, code_removal_allowed = steward_mod.classify_install(_agent_root(home))
+
return {
"hermes_home": str(home),
"agent_installed": agent_is_installed(home),
@@ -208,6 +215,8 @@ def gui_install_summary(hermes_home: "Path | None" = None) -> dict:
"userdata_dir": str(userdata),
"userdata_exists": userdata.exists(),
"platform": sys.platform,
+ "steward": steward,
+ "code_removal_allowed": code_removal_allowed,
}
diff --git a/hermes_cli/macos_tcc_anchor.py b/hermes_cli/macos_tcc_anchor.py
index 9b7b324468d..40382929ca2 100644
--- a/hermes_cli/macos_tcc_anchor.py
+++ b/hermes_cli/macos_tcc_anchor.py
@@ -50,7 +50,7 @@ import tempfile
from pathlib import Path
from hermes_constants import venv_python_path
-from hermes_cli.managed_uv import _RUNTIME_DIR_NAME
+from hermes_cli.runtime_repair import _RUNTIME_DIR_NAME
from utils import atomic_write_text
logger = logging.getLogger(__name__)
@@ -58,7 +58,7 @@ logger = logging.getLogger(__name__)
_MARKER_NAME = ".tcc-anchor-source"
_STORE_COMMON_MARKERS = ("cpython-", "-macos-")
-# The runtime-store marker is derived from managed_uv so a rename of the
+# The runtime-store marker is derived from runtime_repair so a rename of the
# repair-generation directory cannot silently stop the anchor from matching.
_STORE_ROOT_MARKERS = ("/uv/python/", f"/{_RUNTIME_DIR_NAME}/python/")
@@ -334,7 +334,7 @@ def _install_anchor(venv_dir: Path, source_file: Path) -> None:
shutil.copy2(source_file, tmp_path)
os.chmod(tmp_path, source_file.stat().st_mode | 0o111)
try:
- from hermes_cli.managed_uv import _macos_sign_managed_python
+ from hermes_cli.runtime_repair import _macos_sign_managed_python
_macos_sign_managed_python(tmp_path)
except Exception: # pragma: no cover - never block the anchor
diff --git a/hermes_cli/memory_setup.py b/hermes_cli/memory_setup.py
index 59620b20ee8..7931c8912a7 100644
--- a/hermes_cli/memory_setup.py
+++ b/hermes_cli/memory_setup.py
@@ -8,9 +8,9 @@ the provider's config schema. Writes config to config.yaml + .env.
from __future__ import annotations
import os
-import re
import sys
import shlex
+from pathlib import Path
from hermes_constants import get_hermes_home
from hermes_cli.secret_prompt import masked_secret_prompt
@@ -18,30 +18,21 @@ from hermes_cli.secret_prompt import masked_secret_prompt
_CANCELLED = -1
-def _provider_pip_dependencies(provider_name: str, declared: list) -> list:
- """Return the pip deps a provider actually needs on THIS install.
+def _provider_extras(provider_name: str, manifest: dict) -> list[str]:
+ """The pyproject extras a provider needs on THIS install.
- ``plugin.yaml`` declares the provider's baseline bridge packages, but
- some providers install mode-dependent extras at setup time that the
- manifest can't express. Hindsight's ``local_embedded`` mode installs
- ``hindsight-all`` (daemon + embedder + client) during
- ``hermes memory setup`` — if the update-time refresh only reinstalled
- the declared ``hindsight-client``, the embedded daemon would stay
- broken after a venv rebuild stripped ``hindsight-embed`` (#70636).
- """
- deps = list(declared or [])
- if provider_name == "hindsight":
- try:
- import json
- cfg_path = get_hermes_home() / "hindsight" / "config.json"
- cfg = json.loads(cfg_path.read_text(encoding="utf-8")) if cfg_path.exists() else {}
- mode = cfg.get("mode", "")
- # "local" is a legacy alias for "local_embedded"
- if mode in {"local", "local_embedded"}:
- deps.append("hindsight-all")
- except Exception:
- pass
- return deps
+ ``plugin.yaml``'s ``extra:`` names the baseline. Hindsight's
+ ``local_embedded`` mode needs the daemon+embedder wheel on top
+ (hindsight-local, #70636) — mode lives in its config file, which the
+ manifest can't express."""
+ extras = []
+ declared = manifest.get("extra")
+ if isinstance(declared, str) and declared:
+ extras.append(declared)
+ # hindsight local_embedded needs hindsight-all, whose protobuf floor
+ # conflicts with mem0/modal — it cannot be a venv extra. It stays a
+ # provider-owned install until plugin side-venvs land (plan step 5).
+ return extras
# ---------------------------------------------------------------------------
@@ -125,64 +116,28 @@ def _install_dependencies(provider_name: str, *, force: bool = False) -> None:
try:
import yaml
- with open(yaml_path, encoding="utf-8") as f:
+ with open(yaml_path, encoding="utf-8-sig") as f:
meta = yaml.safe_load(f) or {}
except Exception:
return
- pip_deps = _provider_pip_dependencies(provider_name, meta.get("pip_dependencies", []))
- if not pip_deps:
+ extras = _provider_extras(provider_name, meta)
+ if not extras:
return
- # pip name → import name mapping for packages where they differ
- _IMPORT_NAMES = {
- "honcho-ai": "honcho",
- "mem0ai": "mem0",
- "hindsight-client": "hindsight_client",
- "hindsight-all": "hindsight",
- }
-
- # Check which packages need installation.
- missing = []
- for dep in pip_deps:
- if force:
- missing.append(dep)
- continue
- dep_name = re.match(r"^[A-Za-z0-9_][A-Za-z0-9_.\-]*", dep)
- base = dep_name.group(0) if dep_name else dep
- import_name = _IMPORT_NAMES.get(base, base.replace("-", "_").split("[")[0])
- try:
- __import__(import_name)
- except ImportError:
- missing.append(dep)
+ import pm
+ missing = [e for e in extras if force or not pm.available(e)]
if not missing:
return
print(f"\n Installing dependencies: {', '.join(missing)}")
-
- # Environment-aware install: on immutable hosted images the agent venv
- # is sealed read-only and installs must go to the durable target on the
- # data volume (HERMES_LAZY_INSTALL_TARGET). install_specs handles the
- # routing/gating; on normal installs it is venv-scoped as before (NS-605).
- from tools.lazy_deps import install_specs
-
- manual_cmd = f"uv pip install {' '.join(missing)}"
try:
- outcome = install_specs(missing, timeout=120)
- if outcome.ok:
- print(f" ✓ Installed {', '.join(missing)}")
- elif outcome.blocked:
- print(f" ⚠ Cannot install {', '.join(missing)}: {outcome.reason}")
- else:
- print(f" ⚠ Failed to install {', '.join(missing)}")
- stderr = (outcome.stderr or "")[:200]
- if stderr:
- print(f" {stderr}")
- print(f" Run manually: {manual_cmd}")
+ pm.sync_venv(missing, explicit=True)
+ print(f" ✓ Installed {', '.join(missing)}")
except Exception as e:
print(f" ⚠ Install failed: {e}")
- print(f" Run manually: {manual_cmd}")
+ print(" Run manually: hermes pm install")
# Also show external dependencies (non-pip) if any
ext_deps = meta.get("external_dependencies", [])
@@ -334,6 +289,7 @@ def cmd_setup(args) -> None:
if not isinstance(provider_config, dict):
provider_config = {}
+ env_path = get_hermes_home() / ".env"
env_writes = {}
if schema:
@@ -434,13 +390,7 @@ def _write_env_vars(
the ``_ENV_VAR_NAME_RE`` regex (no malformed identifiers), the
``_ENV_VAR_NAME_DENYLIST`` (no ``LD_PRELOAD`` / ``PYTHONPATH`` /
``HERMES_HOME`` / etc.), CR/LF stripping on the value, and the atomic
- 0o600-from-creation write (no TOCTOU permission window). This function
- previously wrote via ``Path.write_text`` directly, bypassing all of
- that: a memory-provider plugin schema declaring ``env_var: "LD_PRELOAD"``
- would land in ``.env`` verbatim and load via the ``env_loader.py``
- ``.env`` -> ``os.environ`` chain on the next Hermes startup, and the
- file existed at the default umask between the write and the later
- ``chmod`` regardless of key legitimacy.
+ 0o600-from-creation write (no TOCTOU permission window).
Validation failures (``ValueError`` from ``save_env_value`` — a
denylisted name or an identifier rejected by ``_ENV_VAR_NAME_RE``) are
diff --git a/hermes_cli/post_update.py b/hermes_cli/post_update.py
new file mode 100644
index 00000000000..a787e2d8782
--- /dev/null
+++ b/hermes_cli/post_update.py
@@ -0,0 +1,651 @@
+"""Post-update maintenance steps shared by ``hermes update`` and boot bootstrap.
+
+Each step operates on user state (config.yaml, skills, state.db) or machine
+state (managed tools), never on the install tree. Every step is idempotent
+and self-gating: running it twice, or from two installs that share one
+HERMES_HOME, converges. The caller (boot_bootstrap, update_cmd) decides WHEN
+steps run; this module owns WHAT they do.
+
+Steps declare a scope:
+
+* ``home`` — mutates the active HERMES_HOME (per profile).
+* ``machine`` — machine-global state shared by every profile.
+
+The scopes must match the record that gates them in ``boot_bootstrap``
+(home record vs machine record).
+
+Ported from the restack branch's post_update module, rewritten onto this
+branch's vocabulary: install identity via ``hermes_cli.steward`` (stamp +
+.git), managed tools via ``pm`` (facts.json ledger) instead of the retired
+``installation`` package.
+"""
+from __future__ import annotations
+
+import logging
+import os
+import shutil
+import subprocess
+import sys
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Iterable
+
+logger = logging.getLogger(__name__)
+
+
+def _install_root() -> Path:
+ """The tree this code runs from: HERMES_INSTALL_ROOT for sealed
+ artifacts whose stamp lives outside the package dir (the same
+ override hermes_cli.version_info honours), the code root otherwise."""
+ env = os.environ.get("HERMES_INSTALL_ROOT")
+ if env:
+ return Path(env)
+ return Path(__file__).resolve().parents[1]
+
+
+# ---------------------------------------------------------------------------
+# config migration (backup / migrate / verify / restore)
+# ---------------------------------------------------------------------------
+
+def _backup_path(path: Path, stamp: str) -> Path:
+ base = path.with_name(f"{path.name}.bak-{stamp}")
+ if not base.exists():
+ return base
+ for index in range(1, 1000):
+ candidate = path.with_name(f"{path.name}.bak-{stamp}.{index}")
+ if not candidate.exists():
+ return candidate
+ raise RuntimeError(f"could not choose a backup path for {path}")
+
+
+def _backup_existing(paths: Iterable[Path]) -> dict:
+ stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
+ backups: dict = {}
+ for path in paths:
+ if not path.is_file():
+ continue
+ dest = _backup_path(path, stamp)
+ shutil.copy2(path, dest)
+ backups[path] = dest
+ return backups
+
+
+def _restore_backups(backups: dict) -> list:
+ restored = []
+ for original, backup in backups.items():
+ if not backup.is_file():
+ continue
+ shutil.copy2(backup, original)
+ restored.append(original)
+ return restored
+
+
+def step_migrate_config() -> dict:
+ """Migrate config.yaml to the current schema, non-interactively.
+
+ Same shape as scripts/docker_config_migrate.py: back up config + .env,
+ migrate, verify the version advanced, restore the backups on failure.
+ No-op when the on-disk version is current (the 99% case).
+ """
+ from hermes_cli.config import (
+ check_config_version,
+ get_config_path,
+ get_env_path,
+ migrate_config,
+ )
+ from hermes_cli.config_migrations import (
+ SUPPORT_FLOOR_VERSION,
+ support_floor_message,
+ )
+
+ current_ver, latest_ver = check_config_version()
+ if current_ver >= latest_ver:
+ return {"ok": True, "skipped": "up-to-date"}
+ if current_ver < SUPPORT_FLOOR_VERSION:
+ # migrate_config() refuses sub-floor configs and leaves the file
+ # untouched; warn instead of failing the boot.
+ logger.warning("config migration skipped: %s", support_floor_message())
+ return {"ok": True, "skipped": "below-support-floor"}
+
+ backups = _backup_existing((get_config_path(), get_env_path()))
+ try:
+ migrate_config(interactive=False, quiet=True)
+ except Exception:
+ _restore_backups(backups)
+ raise
+ post_ver, _ = check_config_version()
+ if post_ver < latest_ver:
+ restored = _restore_backups(backups)
+ raise RuntimeError(
+ f"migration did not advance config version to {latest_ver} "
+ f"(still {post_ver}); restored: "
+ + (", ".join(str(p) for p in restored) if restored else "none")
+ )
+ return {"ok": True, "migrated": f"{current_ver}->{latest_ver}"}
+
+
+# ---------------------------------------------------------------------------
+# skills sync (this home only — profiles self-serve on their own boot)
+# ---------------------------------------------------------------------------
+
+def step_sync_skills() -> dict:
+ """Sync bundled skills into the active home. Content-diffed, respects
+ user modifications and deletions; converges on repeat runs."""
+ from tools.skills_sync import sync_skills
+
+ result = sync_skills(quiet=True) or {}
+ return {
+ "ok": True,
+ "copied": len(result.get("copied") or []),
+ "updated": len(result.get("updated") or []),
+ }
+
+
+# ---------------------------------------------------------------------------
+# state.db integrity guard (#68474 — check-only variant)
+# ---------------------------------------------------------------------------
+
+def step_state_db_guard() -> dict:
+ """Verify the active home's state.db is intact.
+
+ Boot bootstrap has no pre-update snapshot to restore from (that pairing
+ lives in ``hermes update``), so this is detection: a corrupt db is
+ surfaced loudly in the log instead of the user silently losing session
+ search. Read-only, idempotent.
+ """
+ from hermes_constants import get_hermes_home
+ from hermes_cli.backup import verify_sqlite_integrity
+
+ state_path = get_hermes_home() / "state.db"
+ if not state_path.exists():
+ return {"ok": True, "skipped": "no-state-db"}
+ result = verify_sqlite_integrity(state_path, check_header=True, run_pragma=True)
+ if result.get("valid"):
+ return {"ok": True}
+ message = result.get("message", "unknown error")
+ logger.error(
+ "state.db failed integrity check after a code update: %s — "
+ "restore a backup with `hermes backup` tooling or contact support",
+ message,
+ )
+ return {"ok": False, "error": message}
+
+
+def step_adopt_blessed_checkout() -> dict:
+ """One-time adoption of shipped stampless installs (birth certificate).
+
+ Main-era curl|sh / Setup installs created a ``.git`` checkout at a
+ blessed managed root but never wrote a stamp — under the stamp-pure
+ ladder they would all classify as "somebody's working tree" and
+ `hermes update` would refuse them. This step writes the missing fact
+ exactly once: blessed root + ``.git`` + no stamp → a minimal stamp
+ with ``updateMechanism: self``.
+
+ The blessed-root table lives HERE and only here — it is a one-time
+ birth certificate for shipped installs, not a classification rung
+ (hermes_cli.steward never path-matches). Once pre-stamp installs
+ are extinct this step and the table can be deleted.
+
+ * ``.git`` anywhere else → never adopted.
+ * An existing stamp (any content) → untouched.
+ * nix/docker/sealed populations are excluded by construction: their
+ update mechanisms replace the tree wholesale with a
+ build-time-stamped one, and sealed payloads always ship stamps.
+ * Read-only tree (nix-like) → soft skip with a debug log, no crash.
+ """
+ import json
+ import tempfile
+
+ from hermes_constants import get_hermes_home
+
+ root = _install_root()
+
+ # The blessed roots: the canonical locations installers create.
+ blessed = (
+ get_hermes_home() / "hermes-agent",
+ Path("/usr/local/lib/hermes-agent"),
+ )
+
+ if not (root / ".git").exists():
+ return {"ok": True, "skipped": "not-a-checkout"}
+ stamp_path = root / "install-stamp.json"
+ if stamp_path.exists():
+ return {"ok": True, "skipped": "already-stamped"}
+
+ resolved_root = None
+ try:
+ resolved_root = root.resolve()
+ except OSError:
+ return {"ok": True, "skipped": "unresolvable-root"}
+ is_blessed = False
+ for candidate in blessed:
+ try:
+ if resolved_root == candidate.resolve():
+ is_blessed = True
+ break
+ except OSError:
+ continue
+ if not is_blessed:
+ return {"ok": True, "skipped": "not-a-blessed-root"}
+
+ stamp = {
+ "schemaVersion": 2,
+ "updateMechanism": "self",
+ "source": "adoption",
+ "adoptedAt": datetime.now(timezone.utc).isoformat(),
+ }
+ try:
+ fd, tmp_name = tempfile.mkstemp(
+ dir=str(root), prefix=".install-stamp.", suffix=".tmp"
+ )
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
+ handle.write(json.dumps(stamp, indent=2) + "\n")
+ os.replace(tmp_name, stamp_path)
+ except OSError as exc:
+ # A read-only tree (nix-like layouts without their own stamp)
+ # must not crash the boot — it just stays unadopted.
+ logger.debug("blessed-checkout adoption skipped (unwritable): %s", exc)
+ return {"ok": True, "skipped": f"unwritable: {exc}"}
+ logger.info("adopted blessed checkout at %s (updateMechanism: self)", root)
+ return {"ok": True, "adopted": str(root)}
+
+
+def step_provision_runtimes() -> dict:
+ """Refresh managed tools (node, uv, git, gh, ripgrep, the venv) against
+ pm's lockfile after a code change.
+
+ ``pm.check()`` is the cheap verdict: stamp comparisons of the
+ installed-state ledger against pm/lock.json, no network. Anything it
+ names is re-ensured through the same ``pm.ensure``/``pm.sync_venv``
+ calls every other install path uses — pm stays the single authority
+ on tool versions (a pin bump rides in exactly like node or ripgrep;
+ cua-driver gets no bespoke refresh step for the same reason).
+
+ ``explicit=True`` because reaching this step IS the deliberate remedy
+ (the code just changed under this install — the same trust `hermes
+ update` carries); the lazy-install policy still gates the whole sweep
+ so a policy-locked machine skips instead of installing.
+ """
+ import pm
+ from pm.ensure import lazy_installs_allowed, sealed
+
+ problems = pm.check()
+ if not problems:
+ return {"ok": True, "skipped": "current"}
+ if sealed():
+ # A sealed payload's tools ship with the artifact; drift here is
+ # a packaging bug boot_bootstrap reports, not something to fix.
+ return {"ok": True, "skipped": "sealed"}
+ if not lazy_installs_allowed():
+ return {"ok": True, "skipped": "lazy-installs-disabled"}
+
+ refreshed: list[str] = []
+ errors: list[str] = []
+ for problem in problems:
+ name = problem.split(":", 1)[0].strip()
+ try:
+ if name == "venv":
+ pm.sync_venv(explicit=True)
+ else:
+ pm.ensure(name, explicit=True)
+ refreshed.append(name)
+ except Exception as exc: # noqa: BLE001 — one tool must not stop the rest
+ logger.warning("provision_runtimes: %s failed: %s", name, exc)
+ errors.append(f"{name}: {exc}")
+ if errors:
+ return {"ok": False, "error": "; ".join(errors), "refreshed": refreshed}
+ return {"ok": True, "refreshed": refreshed}
+
+
+def step_expose_cli() -> dict:
+ """Keep the user-facing ``hermes`` launchers alive across updates.
+
+ The installers write POSIX wrapper scripts into the link dir
+ (``~/.local/bin`` and friends) exactly once, at install time — so a
+ moved checkout, a recreated venv, or a user's stray ``rm`` leaves
+ stale or missing launchers that nothing repairs until a full
+ reinstall. This step makes the POST-UPDATE side own the recurring
+ maintenance: rewrite the three wrappers (hermes, hermes-agent,
+ hermes-acp) whenever their recorded shape drifts from what this
+ tree would write today. First-time PATH bootstrapping (shell-rc
+ edits, Windows registry) stays installer-side on purpose — a
+ boot-time step must not edit rc files on every update.
+
+ Config-gated by ``cli.expose_on_path`` (default true). Windows is a
+ no-op: venv Scripts are already User-PATH-persisted by the installer.
+ """
+ if sys.platform == "win32":
+ return {"ok": True, "skipped": "windows-installer-owned"}
+
+ try:
+ from hermes_cli.config import load_config
+
+ cli_cfg = (load_config() or {}).get("cli", {})
+ if isinstance(cli_cfg, dict) and not bool(cli_cfg.get("expose_on_path", True)):
+ return {"ok": True, "skipped": "config-disabled"}
+ except Exception as exc: # noqa: BLE001 — config trouble must not kill the step
+ logger.debug("Could not read cli.expose_on_path: %s", exc)
+
+ root = _install_root()
+
+ # Shape FIRST, capability second. The stamp is the shape authority: a
+ # bundled desktop payload never gets installer-written wrappers — its
+ # launchers SHIP in agent-payload/bin as prebuilt signed shims. macOS
+ # is the one platform where nothing at install time can expose them
+ # (a dragged .app runs no installer), so there — and only there —
+ # link the user's bin dir at the bundle's own shims. A Linux AppImage
+ # mounts at a transient path a symlink to which would dangle the
+ # moment the app exits.
+ if _is_bundled_payload(root):
+ if sys.platform == "darwin":
+ return _symlink_sealed_launchers(root.parent / "bin")
+ return {"ok": True, "skipped": "bundle-owns-launchers"}
+
+ # Capability probe for the checkout shape: the wrapper bodies bake
+ # these two paths into text, so both must exist to have anything to
+ # point at. A checkout with a nuked venv lands here — skip; the
+ # installer/bootstrap owns venv repair, not this step.
+ venv_python = root / "venv" / "bin" / "python"
+ entrypoint = root / "hermes"
+ if not venv_python.is_file() or not entrypoint.is_file():
+ return {"ok": True, "skipped": "no-venv-layout"}
+
+ link_dir = Path.home() / ".local" / "bin"
+ wrappers = {
+ "hermes": f'exec "{venv_python}" "{entrypoint}" "$@"',
+ "hermes-agent": f'exec "{venv_python}" "{root / "run_agent.py"}" "$@"',
+ "hermes-acp": f'exec "{venv_python}" "{entrypoint}" acp "$@"',
+ }
+
+ written: list[str] = []
+ try:
+ link_dir.mkdir(parents=True, exist_ok=True)
+ for name, exec_line in wrappers.items():
+ target = link_dir / name
+ body = (
+ "#!/usr/bin/env bash\n"
+ "unset PYTHONPATH\n"
+ "unset PYTHONHOME\n"
+ f"{exec_line}\n"
+ )
+ try:
+ existing = target.read_text(encoding="utf-8-sig")
+ except (FileNotFoundError, UnicodeDecodeError, OSError):
+ existing = None
+ if existing == body:
+ continue # current — do not churn mtimes every boot
+ # A launcher pointing at ANOTHER install is the user's own
+ # arrangement (two checkouts, one link dir) — leave it alone.
+ # Ours means: mentions this root in its text, OR is a symlink
+ # resolving into this root (the pre-#21454 install shape,
+ # where the link dir pointed straight at the venv console
+ # script — reading THROUGH it shows no path at all).
+ is_symlink_into_root = (
+ target.is_symlink()
+ and str(target.resolve()).startswith(str(root) + os.sep)
+ )
+ if (
+ existing is not None
+ and existing.strip()
+ and str(root) not in existing
+ and not is_symlink_into_root
+ ):
+ continue
+ # The installers' #21454 lesson: clear first, so writing can
+ # never follow an old symlink into the venv and clobber a
+ # console script.
+ target.unlink(missing_ok=True)
+ target.write_text(body, encoding="utf-8")
+ target.chmod(0o755)
+ written.append(name)
+ except OSError as exc:
+ return {"ok": False, "error": str(exc)}
+ return {"ok": True, "written": written}
+
+
+def _is_bundled_payload(root: Path) -> bool:
+ """Is ``root`` a desktop bundle's agent payload? The stamp is the
+ authority (payload marker / desktop-app distribution), never a
+ sibling-directory sniff; a .git tree is a dev checkout regardless."""
+ if (root / ".git").exists():
+ return False
+ from hermes_cli.steward import STEWARD_DESKTOP, read_install_stamp
+
+ stamp = read_install_stamp(root)
+ if not stamp:
+ return False
+ return bool(stamp.get("payload")) or stamp.get("distribution") == STEWARD_DESKTOP
+
+
+def _symlink_sealed_launchers(payload_bin) -> dict:
+ """Link ~/.local/bin/{hermes,hermes-agent,hermes-acp} at a sealed
+ bundle's own prebuilt shims (macOS only).
+
+ Symlinks, not copies: the shims are signed as part of the app bundle,
+ and a copy would both orphan the signature's context and go stale on
+ every app update — a symlink into the .app follows the bundle's
+ content wherever Squirrel.Mac swaps it.
+
+ Ownership guard mirrors step_expose_cli's wrapper logic: an existing
+ entry is replaced only when it is ours — a symlink into THIS app
+ bundle's payload — or missing/broken. A user's own `hermes` (pipx,
+ another checkout's wrapper) is never touched.
+ """
+ link_dir = Path.home() / ".local" / "bin"
+ payload_root = payload_bin.parent
+ written: list[str] = []
+ try:
+ link_dir.mkdir(parents=True, exist_ok=True)
+ for name in ("hermes", "hermes-agent", "hermes-acp"):
+ source = payload_bin / name
+ if not source.is_file():
+ continue
+ target = link_dir / name
+ if target.is_symlink():
+ current = os.readlink(target)
+ if current == str(source):
+ continue # already ours and current
+ # Ours if it points into this payload (stale app path from
+ # a previous version counts — resolve() of a dangling link
+ # still yields the old path text) — or dangling entirely.
+ points_into_payload = str(Path(current)).startswith(str(payload_root) + os.sep)
+ if not points_into_payload and target.exists():
+ continue # a live foreign link — user's arrangement
+ elif target.exists():
+ continue # a real file we did not write — never clobber
+ target.unlink(missing_ok=True)
+ target.symlink_to(source)
+ written.append(name)
+ except OSError as exc:
+ return {"ok": False, "error": str(exc)}
+ return {"ok": True, "written": written, "mode": "sealed-symlinks"}
+
+
+# ---------------------------------------------------------------------------
+# step registries — boot_bootstrap gates each list with the matching record
+# ---------------------------------------------------------------------------
+
+HOME_STEPS: tuple = (
+ ("adopt_blessed_checkout", step_adopt_blessed_checkout),
+ ("migrate_config", step_migrate_config),
+ ("sync_skills", step_sync_skills),
+ ("state_db_guard", step_state_db_guard),
+ ("expose_cli", step_expose_cli),
+)
+
+# Machine steps may be slow (network installers); boot bootstrap runs them
+# AFTER writing the machine record, detached from boot readiness.
+#
+# There is no separate cua-driver refresh step: pinned managed tools ride
+# provision_runtimes' pm sweep — one authority on every tool's version.
+MACHINE_STEPS: tuple = (
+ ("provision_runtimes", step_provision_runtimes),
+)
+
+
+def run_steps(steps: Iterable) -> dict:
+ """Run steps in order; one failure never stops the rest.
+
+ Returns ``{name: result_dict}``. A raising step records
+ ``{"ok": False, "error": str}`` — the caller still writes its record so
+ a broken step cannot retrigger the slow path on every boot.
+ """
+ results: dict = {}
+ for name, func in steps:
+ try:
+ results[name] = func()
+ except Exception as exc:
+ logger.warning("post-update step %s failed: %s", name, exc)
+ results[name] = {"ok": False, "error": str(exc)}
+ return results
+
+
+def resync_and_reexec(args) -> int | None:
+ """Phase 1 of the update-phase: own the venv sync, then hand off.
+
+ Runs in whatever interpreter called us — usually the venv python the
+ tree swap just invalidated — so it touches as little as possible:
+ ``venv_sync`` (stdlib-only at import by contract) decides from the
+ lockfile digest whether the venv is stale, syncs it via pm when it
+ is, and then this process REPLACES ITSELF with a fresh interpreter
+ that has never mapped a pre-sync module.
+
+ Returns None to mean "you are already the fresh process — run phase
+ 2", or an exit code to propagate.
+
+ The boundary is double-guarded:
+
+ * the ``--resumed-after-sync`` argv flag is the loop-proofing — the
+ exec'd child must not sync again even if another writer moves the
+ stamp between exec and check, because a flag in argv cannot race;
+ * the venv_sync stamp is the idempotence — a re-run of the whole
+ update sees a fresh stamp and skips the sync entirely.
+
+ POSIX uses ``os.execv``: same pid, so an update-lock marker's owner
+ stays literally correct. Windows has no true exec — spawn + wait +
+ propagate, and the child passes any lock by process ancestry.
+ """
+ if args.resumed_after_sync:
+ return None
+
+ from hermes_cli import venv_sync
+
+ result = venv_sync.sync()
+ state = result.get("state")
+ if state == "failed":
+ print(f" ✗ venv sync failed: {result.get('detail')}")
+ return 1
+ if state in ("sealed", "current"):
+ # Nothing changed under us — this interpreter is as good as a
+ # fresh one, and an exec would only cost startup time.
+ return None
+
+ print(" ✓ venv synced — handing off to a fresh interpreter")
+ argv = [sys.executable, "-m", "hermes_cli.post_update", "--update-phase",
+ "--resumed-after-sync"]
+ if args.gateway_mode:
+ argv.append("--gateway-mode")
+ if args.assume_yes:
+ argv.append("--assume-yes")
+ if args.pre_update_snapshot_id:
+ argv.extend(["--pre-update-snapshot-id", str(args.pre_update_snapshot_id)])
+
+ if os.name == "posix":
+ sys.stdout.flush()
+ sys.stderr.flush()
+ os.execv(sys.executable, argv)
+ # unreachable: execv only returns by raising
+
+ completed = subprocess.run(argv)
+ return completed.returncode
+
+
+def _run_update_phase(args) -> int:
+ """Phase 2: the full post-update step list in a fresh interpreter,
+ then record the new identity so the next boot's bootstrap skips.
+
+ ``hermes update`` and boot bootstrap share ONE registry: this runner
+ executes exactly HOME_STEPS + MACHINE_STEPS (machine steps inline —
+ an update invocation is interactive, deferring would hide failures),
+ and writes both boot records via ``boot_bootstrap.write_record``.
+
+ TODO(update-collapse): route hermes_cli.update_cmd's inline
+ post-update phase through ``python -m hermes_cli.post_update
+ --update-phase`` (spawn with inherited stdio) so the updater stops
+ reloading modules by hand. The restack branch delegated to
+ ``update_cmd._run_update_phase_inline`` here; that helper does not
+ exist on this branch yet, so the shared-registry runner IS the
+ update phase for now.
+ """
+ from hermes_cli import boot_bootstrap
+
+ steps = (*HOME_STEPS, *MACHINE_STEPS)
+ results = run_steps(steps)
+ failed = [name for name, res in results.items() if not res.get("ok")]
+ for name, res in results.items():
+ state = "ok" if res.get("ok") else f"FAILED ({res.get('error')})"
+ skipped = res.get("skipped")
+ print(f" post-update {name}: {f'skipped ({skipped})' if skipped else state}")
+
+ root = boot_bootstrap.default_project_root()
+ identity = boot_bootstrap.current_install_identity(root)
+ if identity:
+ try:
+ boot_bootstrap.write_record(root, "home", identity, results)
+ boot_bootstrap.write_record(root, "machine", identity, results)
+ except OSError as exc:
+ logger.warning("could not record post-update identity: %s", exc)
+ return 1 if failed else 0
+
+
+def main(argv: list | None = None) -> int:
+ """``python -m hermes_cli.post_update`` — run in a FRESH interpreter
+ so every step imports post-pull code (no reload lists).
+
+ Two modes:
+
+ * default / ``--scope``: the boot-bootstrap step registries.
+ * ``--update-phase``: phase 1 (``resync_and_reexec``) syncs the venv
+ and re-execs, so phase 2 (the full step list + boot-record write)
+ always runs on the synced world.
+ """
+ import argparse
+
+ parser = argparse.ArgumentParser(prog="hermes_cli.post_update")
+ parser.add_argument("--scope", choices=("home", "machine", "all"), default="all")
+ parser.add_argument("--update-phase", action="store_true")
+ parser.add_argument("--gateway-mode", action="store_true")
+ parser.add_argument("--assume-yes", action="store_true")
+ parser.add_argument("--pre-update-snapshot-id", default=None)
+ parser.add_argument("--pre-update-version", default=None)
+ parser.add_argument(
+ "--resumed-after-sync",
+ action="store_true",
+ help="internal: this process IS the post-sync interpreter; never sync again",
+ )
+ args = parser.parse_args(argv)
+
+ logging.basicConfig(level=logging.INFO, format="%(message)s")
+
+ if args.update_phase:
+ handoff = resync_and_reexec(args)
+ if handoff is not None:
+ return handoff
+ return _run_update_phase(args)
+
+ selected: list = []
+ if args.scope in ("home", "all"):
+ selected.extend(HOME_STEPS)
+ if args.scope in ("machine", "all"):
+ selected.extend(MACHINE_STEPS)
+ results = run_steps(selected)
+ failed = [name for name, res in results.items() if not res.get("ok")]
+ for name, res in results.items():
+ state = "ok" if res.get("ok") else f"FAILED ({res.get('error')})"
+ skipped = res.get("skipped")
+ print(f" post-update {name}: {f'skipped ({skipped})' if skipped else state}")
+ return 1 if failed else 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/hermes_cli/profile_distribution.py b/hermes_cli/profile_distribution.py
index a4049bafc33..9dd53b38fc0 100644
--- a/hermes_cli/profile_distribution.py
+++ b/hermes_cli/profile_distribution.py
@@ -249,7 +249,7 @@ def read_manifest(profile_dir: Path) -> Optional[DistributionManifest]:
if not mf_path.is_file():
return None
try:
- data = _load_yaml(mf_path.read_text(encoding="utf-8"))
+ data = _load_yaml(mf_path.read_text(encoding="utf-8-sig"))
except Exception as exc:
raise DistributionError(f"Failed to parse {mf_path}: {exc}") from exc
return DistributionManifest.from_dict(data or {})
diff --git a/hermes_cli/profiles.py b/hermes_cli/profiles.py
index 3df3e5dc191..957413368bf 100644
--- a/hermes_cli/profiles.py
+++ b/hermes_cli/profiles.py
@@ -108,6 +108,10 @@ _CLONE_ALL_DEFAULT_EXCLUDE_ROOT: frozenset[str] = frozenset({
"profiles",
"bin",
"node_modules",
+ # Managed runtime trees — install artifacts, never profile state
+ # (install/profile bucket split; see test_install_bucket_separation).
+ ".hermes-runtime",
+ "node",
})
# Per-profile history artifacts excluded from --clone-all regardless of the
@@ -221,6 +225,8 @@ _DEFAULT_EXPORT_EXCLUDE_ROOT = DEFAULT_EXPORT_EXCLUDE_ROOT = frozenset({
"profiles", # other profiles — never recursive-export
"bin", # installed binaries (tirith, etc.)
"node_modules", # npm packages
+ ".hermes-runtime", # managed runtime tree (install artifact)
+ "node", # legacy pre-split managed Node tree
# Databases & runtime state
"state.db", "state.db-shm", "state.db-wal",
"hermes_state.db",
@@ -483,7 +489,7 @@ def check_alias_collision(name: str) -> Optional[str]:
expected = wrapper_dir / (f"{canon}.bat" if is_windows else canon)
if existing_path == str(expected):
try:
- content = expected.read_text(encoding="utf-8")
+ content = expected.read_text(encoding="utf-8-sig")
if "hermes -p" in content:
return None # it's our wrapper, safe to overwrite
except Exception:
@@ -565,7 +571,7 @@ def remove_wrapper_script(name: str) -> bool:
if wrapper_path.exists():
try:
# Verify it's our wrapper before removing
- content = wrapper_path.read_text(encoding="utf-8")
+ content = wrapper_path.read_text(encoding="utf-8-sig")
if "hermes -p" in content:
wrapper_path.unlink()
return True
@@ -660,7 +666,7 @@ def build_alias_map() -> dict[str, str]:
if not is_windows and entry.suffix:
continue
try:
- with open(entry, "r", encoding="utf-8", errors="strict") as f:
+ with open(entry, "r", encoding="utf-8-sig", errors="strict") as f:
content = f.read(_WRAPPER_READ_LIMIT)
except (OSError, UnicodeDecodeError):
# UnicodeDecodeError = a binary on PATH (ffmpeg etc.) — not a wrapper.
@@ -736,7 +742,7 @@ def _read_distribution_meta(profile_dir: Path) -> tuple:
return None, None, None
try:
import yaml
- with open(mf_path, "r", encoding="utf-8") as f:
+ with open(mf_path, "r", encoding="utf-8-sig") as f:
data = yaml.safe_load(f) or {}
if not isinstance(data, dict):
return None, None, None
@@ -934,7 +940,7 @@ def read_profile_meta(profile_dir: Path) -> dict:
return empty
try:
import yaml
- with open(path, "r", encoding="utf-8") as f:
+ with open(path, "r", encoding="utf-8-sig") as f:
data = yaml.safe_load(f) or {}
except Exception:
return empty
@@ -967,7 +973,7 @@ def write_profile_meta(
existing: dict = {}
if path.is_file():
try:
- with open(path, "r", encoding="utf-8") as f:
+ with open(path, "r", encoding="utf-8-sig") as f:
loaded = yaml.safe_load(f) or {}
if isinstance(loaded, dict):
existing = loaded
@@ -1996,7 +2002,7 @@ def _stop_gateway_process(profile_dir: Path) -> None:
return
try:
- raw = pid_file.read_text(encoding="utf-8").strip()
+ raw = pid_file.read_text(encoding="utf-8-sig").strip()
data = json.loads(raw) if raw.startswith("{") else {"pid": int(raw)}
pid = int(data["pid"])
# Route through terminate_pid so Windows uses the appropriate
@@ -2037,7 +2043,7 @@ def get_active_profile() -> str:
"""
path = _get_active_profile_path()
try:
- name = path.read_text(encoding="utf-8").strip()
+ name = path.read_text(encoding="utf-8-sig").strip()
if not name:
return "default"
return name
@@ -2216,7 +2222,7 @@ def _scrub_export_secrets(staged: Path) -> None:
continue
try:
- text = path.read_text(encoding="utf-8")
+ text = path.read_text(encoding="utf-8-sig")
except (UnicodeDecodeError, OSError):
continue
@@ -2459,7 +2465,7 @@ def _migrate_honcho_profile_host(old_name: str, new_name: str, new_dir: Path) ->
seen.add(resolved)
try:
- raw = json.loads(path.read_text(encoding="utf-8"))
+ raw = json.loads(path.read_text(encoding="utf-8-sig"))
except (OSError, json.JSONDecodeError):
continue
diff --git a/hermes_cli/managed_uv.py b/hermes_cli/runtime_repair.py
similarity index 68%
rename from hermes_cli/managed_uv.py
rename to hermes_cli/runtime_repair.py
index 8317b96ad8e..d0d104092d6 100644
--- a/hermes_cli/managed_uv.py
+++ b/hermes_cli/runtime_repair.py
@@ -1,20 +1,21 @@
-"""Hermes-managed uv and Python runtime repair.
-
-Hermes owns its own uv binary at ``$HERMES_HOME/bin/uv`` (or ``uv.exe`` on
-Windows). Every code path that needs uv resolves it from that single location.
-If the binary is missing, ``ensure_uv()`` bootstraps it via the official
-standalone installer with ``UV_UNMANAGED_INSTALL`` / ``UV_INSTALL_DIR`` pointed
-at ``$HERMES_HOME/bin`` so the installer writes directly there — no PATH
-probing, no conda guards, no multi-location resolution chains.
-
-The Python backing the install is different: it is shared by every Hermes
-profile because the checkout's ``venv`` is shared. Runtime repair therefore
-uses an install-scoped store under ``<checkout>/.hermes-runtime/python``. A
-vulnerable interpreter is never reinstalled in place. We provision a new
-immutable Python generation, build and smoke-test a relocatable sibling venv,
-then cut over with same-filesystem renames. The old venv remains available for
-synchronous rollback and is parked for cleanup after the updating process
-releases it.
+"""Managed Python runtime repair (checkout venv surgery).
+
+The Python backing a CHECKOUT install is shared by every Hermes profile
+because the checkout's ``venv`` is shared. A vulnerable interpreter is
+never reinstalled in place: we provision a new immutable Python generation
+into the install's runtime dir, build and smoke-test a relocatable sibling
+venv, then cut over with same-filesystem renames. The old venv remains
+available for synchronous rollback and is parked for cleanup after the
+updating process releases it.
+
+Sealed trees never reach this module — their interpreter is a build
+artifact (pm's ``sealed()`` payloads ship a staged python and refuse
+runtime installs).
+
+uv itself is NOT this module's business: the pinned uv is realized through
+``pm`` (``pm/lock.json`` + the pm store), like every other managed tool.
+This module was previously ``hermes_cli.managed_uv`` and carried its own
+uv acquisition; that half predated the package manager and is retired.
"""
from __future__ import annotations
@@ -27,58 +28,41 @@ import platform
import shutil
import subprocess
import sys
-import tempfile
import time
import uuid
from dataclasses import dataclass
from pathlib import Path
-from typing import Callable, Optional
-from hermes_constants import get_hermes_home
from hermes_cli.sqlite_runtime import SQLiteRuntimeInfo, probe_sqlite_runtime
logger = logging.getLogger(__name__)
_PROJECT_ROOT = Path(__file__).resolve().parents[1]
-_RUNTIME_DIR_NAME = ".hermes-runtime"
_VENV_NAME = "venv"
_ALT_VENV_NAME = ".venv"
-_REPAIR_LOCK_NAME = "runtime-repair.lock"
+_RUNTIME_DIR_NAME = ".hermes-runtime"
_MACOS_MANAGED_PYTHON_IDENTIFIER = "com.nousresearch.hermes.managed-python"
+_REPAIR_LOCK_NAME = "runtime-repair.lock"
# ---------------------------------------------------------------------------
# Public helpers
# ---------------------------------------------------------------------------
-def managed_uv_path() -> Path:
- """Return the path where Hermes keeps *its* uv binary.
+def _runtime_dir(project_root: Path) -> Path:
+ """The checkout-scoped scratch dir for repair artifacts.
- ``$HERMES_HOME/bin/uv`` on POSIX, ``$HERMES_HOME\\bin\\uv.exe`` on
- Windows. The directory may not exist yet — callers should use
- ``ensure_uv()`` to bootstrap it.
+ Deliberately NOT the pm store: the pm store is machine-wide and holds
+ immutable published entries, while generations, candidate venvs, and
+ the repair lock are private to one checkout and its cutover.
"""
- home = get_hermes_home()
- if platform.system() == "Windows":
- return home / "bin" / "uv.exe"
- return home / "bin" / "uv"
-
-
-def resolve_uv() -> Optional[str]:
- """Return the managed uv path if it exists, else ``None``.
-
- No side effects — pure lookup.
- """
- p = managed_uv_path()
- if p.is_file() and os.access(p, os.X_OK):
- return str(p)
- return None
+ return Path(project_root) / _RUNTIME_DIR_NAME
def managed_python_install_dir(project_root: Path | None = None) -> Path:
"""Return the checkout-scoped Python store shared by all profiles."""
root = Path(project_root) if project_root is not None else _PROJECT_ROOT
- return root / _RUNTIME_DIR_NAME / "python"
+ return _runtime_dir(root) / "python"
def managed_python_env(
@@ -87,22 +71,23 @@ def managed_python_env(
install_dir: Path | None = None,
base_env: dict[str, str] | None = None,
) -> dict[str, str]:
- """Return a sanitized environment for Hermes-private uv Python commands."""
+ """Return a sanitized environment for Hermes-private uv Python commands.
+
+ Builds on pm's ``uv_env`` sanitization (which strips every ``UV_*``
+ override and active-venv leakage — the interpreter-hijack class), then
+ pins uv's managed-Python behavior to the private install dir.
+ """
+ from pm.packages import uv_env
+
target = (
Path(install_dir)
if install_dir is not None
else managed_python_install_dir(project_root)
)
- env = dict(os.environ if base_env is None else base_env)
+ env = uv_env(dict(os.environ if base_env is None else base_env))
for key in (
"CONDA_DEFAULT_ENV",
"CONDA_PREFIX",
- "UV_PROJECT_ENVIRONMENT",
- "UV_NO_MANAGED_PYTHON",
- "UV_PYTHON",
- "UV_PYTHON_DOWNLOADS",
- "UV_SYSTEM_PYTHON",
- "VIRTUAL_ENV",
"PYTHONHOME",
"PYTHONPATH",
):
@@ -117,6 +102,43 @@ def managed_python_env(
return env
+@dataclass(frozen=True)
+class RuntimeRepairResult:
+ """Outcome of a managed-runtime repair attempt."""
+
+ status: str
+ detail: str = ""
+ sqlite_before: str = ""
+ sqlite_after: str = ""
+ backup_venv: Path | None = None
+
+ @property
+ def repaired(self) -> bool:
+ return self.status == "repaired"
+
+
+@dataclass(frozen=True)
+class _RepairLock:
+ path: Path
+ fd: int
+
+
+def _report_runtime_repair_failure(repair: RuntimeRepairResult) -> None:
+ if repair.backup_venv is None:
+ print(
+ " ℹ Managed Python runtime was not replaced; "
+ f"the existing venv is unchanged ({repair.detail})."
+ )
+ print(
+ " Sessions stay protected meanwhile: Hermes keeps databases "
+ "out of WAL mode on this SQLite build. The next `hermes update` "
+ "will retry."
+ )
+ return
+ print(f" ✗ Managed Python runtime cutover needs manual recovery: {repair.detail}")
+ print(f" Previous venv: {repair.backup_venv}")
+
+
def _macos_sign_managed_python(python: Path) -> bool:
"""Give a newly downloaded managed Python a stable macOS code identity.
@@ -190,269 +212,6 @@ def _macos_sign_managed_python(python: Path) -> bool:
return False
-@dataclass(frozen=True)
-class RuntimeRepairResult:
- """Outcome of a managed-runtime repair attempt."""
-
- status: str
- detail: str = ""
- sqlite_before: str = ""
- sqlite_after: str = ""
- backup_venv: Path | None = None
-
- @property
- def repaired(self) -> bool:
- return self.status == "repaired"
-
-
-@dataclass(frozen=True)
-class _RepairLock:
- path: Path
- fd: int
-
-
-def _report_runtime_repair_failure(repair: RuntimeRepairResult) -> None:
- if repair.backup_venv is None:
- print(
- " ℹ Managed Python runtime was not replaced; "
- f"the existing venv is unchanged ({repair.detail})."
- )
- print(
- " Sessions stay protected meanwhile: Hermes keeps databases "
- "out of WAL mode on this SQLite build. The next `hermes update` "
- "will retry."
- )
- return
- print(f" ✗ Managed Python runtime cutover needs manual recovery: {repair.detail}")
- print(f" Previous venv: {repair.backup_venv}")
-
-
-class _UvResult(str):
- """``ensure_uv()`` return value that survives an update boundary.
-
- ``ensure_uv()``'s arity has flipped between a single path string and a
- ``(path, fresh_bootstrap)`` tuple across releases. ``hermes update`` runs
- the call site from the *old*, already-imported ``hermes_cli.main`` against
- this *freshly pulled* module, so the two can disagree on how many values
- ``ensure_uv()`` returns. An install parked on a 2-tuple release runs
- ``uv_bin, fresh_bootstrap = ensure_uv()`` against the single-value module
- and crashes the first update: the returned path is a plain ``str``, which is
- itself iterable, so the 2-target unpack walks its characters and raises
- ``ValueError: too many values to unpack (expected 2)`` (and on the failure
- path the ``None`` return raises ``TypeError: cannot unpack non-iterable
- NoneType``). This wrapper answers to both conventions:
-
- uv_bin = ensure_uv() # behaves as the path str ("" when absent)
- uv_bin, fresh = ensure_uv() # unpacks as (path|None, fresh_bootstrap)
-
- Missing uv is the empty string (falsy) instead of ``None`` so legacy
- 2-target call sites can still unpack a failure without raising, while
- ``if not uv_bin`` keeps working for single-value callers.
-
- POSIX only. This wrapper is **never** returned on Windows — see
- ``ensure_uv()`` for why the ``__iter__`` override is unsafe there.
- """
-
- fresh_bootstrap: bool
-
- def __new__(cls, path: Optional[str], fresh: bool = False) -> "_UvResult":
- self = super().__new__(cls, path or "")
- self.fresh_bootstrap = fresh
- return self
-
- def __iter__(self):
- # Tuple-unpacking hook for legacy ``uv_bin, fresh = ensure_uv()`` sites.
- # First element mirrors the historical contract: the path string, or
- # ``None`` when uv is unavailable.
- return iter(((str(self) or None), self.fresh_bootstrap))
-
-
-def _ensure_uv_path(
- *,
- repair_observer: Callable[[RuntimeRepairResult], None] | None = None,
-) -> Optional[str]:
- """Resolve the managed uv path, installing it if necessary (plain ``str``/``None``)."""
- existing = resolve_uv()
- if existing:
- return existing
-
- target = managed_uv_path()
- target.parent.mkdir(parents=True, exist_ok=True)
-
- print(f" → Installing managed uv into {target.parent} ...")
-
- try:
- _install_uv(target)
- except Exception as exc:
- logger.warning("Managed uv install failed: %s", exc)
- print(f" ✗ Failed to install managed uv: {exc}")
- return None
-
- # Verify
- result = resolve_uv()
- if result:
- version = subprocess.run(
- [result, "--version"],
- capture_output=True,
- text=True, encoding='utf-8', errors='replace',
- check=False,
- ).stdout.strip()
- print(f" ✓ Managed uv installed ({version})")
- # Compatibility boundary: an older, already-imported updater calls the
- # freshly pulled ``ensure_uv()`` after bootstrapping uv. Repair here so
- # that first update can migrate a vulnerable runtime without requiring
- # a second ``hermes update``.
- try:
- repair = repair_vulnerable_runtime(result)
- if repair_observer is not None:
- repair_observer(repair)
- if repair.status == "failed":
- _report_runtime_repair_failure(repair)
- except Exception as exc:
- logger.warning("Managed Python runtime repair failed: %s", exc)
- else:
- print(" ✗ Managed uv install appeared to succeed but binary not found")
- return result
-
-
-def ensure_uv(
- *,
- repair_observer: Callable[[RuntimeRepairResult], None] | None = None,
-):
- """Return the managed uv path, installing it first if necessary.
-
- On **POSIX** the result is a :class:`_UvResult` (a ``str`` subclass) that is
- both usable directly as the path *and* unpackable as
- ``(path, fresh_bootstrap)`` for older call sites parked on a 2-tuple
- release — see :class:`_UvResult` for the update-boundary rationale.
-
- On **Windows** we deliberately return a plain ``str``/``None`` instead.
- ``subprocess`` there serializes the argv via ``subprocess.list2cmdline``,
- which iterates every entry *as a string* (``for c in arg``). The dependency
- installer passes uv straight into the command list (``[uv_bin, "pip", ...]``),
- so a ``_UvResult`` — whose ``__iter__`` yields ``(path, fresh_bootstrap)``
- rather than characters — would inject the bool into the command line and
- crash the install with ``TypeError: sequence item 1: expected str instance,
- bool found``. A plain ``str`` matches the historical Windows contract and is
- subprocess-safe. (A single value cannot satisfy both 2-target unpacking and
- Windows char-iteration: both use the iterator protocol, with contradictory
- results.)
-
- On failure the result is falsy — never raises — so callers can fall back to
- pip gracefully. ``repair_observer``, when provided, receives the runtime
- repair result produced after a fresh uv bootstrap.
- """
- result = _ensure_uv_path(repair_observer=repair_observer)
- if platform.system() == "Windows":
- # See docstring: a str subclass with an overridden __iter__ is unsafe as
- # a Windows subprocess argument. Hand back the plain path (or None).
- return result
- return _UvResult(result)
-
-
-def _uv_self_update_is_fresh(now: float | None = None) -> bool:
- """Return True when ``uv self update`` ran recently enough to skip.
-
- uv releases roughly weekly while many users run ``hermes update`` daily;
- re-running a blocking network self-update on every invocation is waste
- and, offline, an unbounded hang risk. A stamp file under HERMES_HOME
- caches the last successful self-update time.
- """
- try:
- from hermes_constants import get_hermes_home
-
- stamp = get_hermes_home() / "cache" / ".uv_self_update_stamp"
- age = (now if now is not None else time.time()) - stamp.stat().st_mtime
- return 0 <= age < UV_SELF_UPDATE_INTERVAL_SECONDS
- except Exception:
- return False
-
-
-def _touch_uv_self_update_stamp() -> None:
- try:
- from hermes_constants import get_hermes_home
-
- stamp = get_hermes_home() / "cache" / ".uv_self_update_stamp"
- stamp.parent.mkdir(parents=True, exist_ok=True)
- stamp.touch()
- except OSError:
- pass
-
-
-# uv ships releases ~weekly; refresh the managed binary at most this often.
-UV_SELF_UPDATE_INTERVAL_SECONDS = 7 * 24 * 3600
-# `uv self update` is a network call; unbounded it can hang forever on a
-# blackholed connection (no default timeout in uv's downloader path).
-UV_SELF_UPDATE_TIMEOUT_SECONDS = 60
-
-
-def update_managed_uv(
- *,
- repair_observer: Callable[[RuntimeRepairResult], None] | None = None,
- force: bool = False,
-) -> Optional[str]:
- """Run ``uv self update`` on the managed uv binary.
-
- Call this during ``hermes update`` so the managed copy stays current.
- Returns the managed path when uv is available and ``None`` otherwise.
- A self-update failure is non-fatal because the old version still works.
- ``repair_observer``, when provided, receives the runtime repair result.
-
- The network self-update is skipped when it succeeded within the last
- ``UV_SELF_UPDATE_INTERVAL_SECONDS`` (7 days) unless ``force=True``; the
- vulnerable-runtime repair probe below ALWAYS runs — CVE-driven runtime
- repair must never be gated behind the freshness stamp.
- """
- existing = resolve_uv()
- if not existing:
- # Not installed yet — ensure_uv() will handle that elsewhere.
- return None
-
- if force or not _uv_self_update_is_fresh():
- try:
- result = subprocess.run(
- [existing, "self", "update"],
- capture_output=True,
- text=True, encoding='utf-8', errors='replace',
- check=False,
- timeout=UV_SELF_UPDATE_TIMEOUT_SECONDS,
- )
- except subprocess.TimeoutExpired:
- logger.debug("uv self update timed out after %ss", UV_SELF_UPDATE_TIMEOUT_SECONDS)
- result = None
- if result is not None and result.returncode == 0:
- _touch_uv_self_update_stamp()
- version = subprocess.run(
- [existing, "--version"],
- capture_output=True,
- text=True, encoding='utf-8', errors='replace',
- check=False,
- ).stdout.strip()
- print(f" ✓ Managed uv updated ({version})")
- elif result is not None:
- # Non-fatal — old uv still works fine.
- logger.debug(
- "uv self update failed (rc=%d): %s", result.returncode, result.stderr
- )
-
- # Keep this hook inside the long-standing API. During an update, main.py is
- # already imported from the old checkout, then ``git pull`` replaces this
- # module on disk before the updater imports it. Calling the repair here is
- # what makes the migration happen on that first update.
- try:
- repair = repair_vulnerable_runtime(existing)
- if repair_observer is not None:
- repair_observer(repair)
- if repair.status == "failed":
- _report_runtime_repair_failure(repair)
- except Exception as exc:
- # Runtime refresh is deliberately non-fatal. The live venv was not
- # touched unless a fully prepared candidate reached cutover.
- logger.warning("Managed Python runtime repair failed: %s", exc)
- print(f" ⚠ Managed Python runtime repair skipped: {exc}")
- return existing
-
-
# ---------------------------------------------------------------------------
# Managed Python runtime repair
# ---------------------------------------------------------------------------
@@ -472,8 +231,7 @@ def _reload_hermes_constants():
(~/.hermes/hermes-agent/hermes_constants.py)
Reloading picks up the definitions actually on disk, so callers keep using
- the shared helper instead of hand-rolling a second copy of its logic. Same
- update-boundary class as the ``ensure_uv()`` arity skew on :class:`_UvResult`.
+ the shared helper instead of hand-rolling a second copy of its logic.
"""
import hermes_constants
@@ -670,12 +428,6 @@ def _attempt_install_generation(
_remove_tree(generation, boundary=python_root)
return None
- # Do this before the candidate is probed or promoted. On macOS, the
- # stable identifier prevents each immutable generation from looking like
- # a new TCC principal. Failure is non-fatal: the SQLite repair must still
- # proceed when codesign is unavailable or rejects a particular artifact.
- _macos_sign_managed_python(python)
-
candidate = probe_sqlite_runtime(python)
if candidate is None:
logger.warning("could not probe candidate Python runtime: %s", python)
@@ -721,7 +473,7 @@ def _install_safe_python_generation(
project_root: Path,
current: SQLiteRuntimeInfo,
) -> tuple[Path, Path, SQLiteRuntimeInfo] | None:
- runtime_root = project_root / _RUNTIME_DIR_NAME
+ runtime_root = _runtime_dir(project_root)
python_root = managed_python_install_dir(project_root)
_make_world_traversable(runtime_root)
_make_world_traversable(python_root)
@@ -729,6 +481,7 @@ def _install_safe_python_generation(
request = _runtime_request(current)
print(f" → Provisioning a private Python {request} runtime with fixed SQLite...")
tried_versions = {current.python_version[:3]}
+
result = _attempt_install_generation(
uv_bin, request, project_root=project_root,
python_root=python_root, current=current,
@@ -880,7 +633,7 @@ def _stage_candidate_venv(
generation: Path,
python: Path,
) -> Path | None:
- runtime_root = project_root / _RUNTIME_DIR_NAME
+ runtime_root = _runtime_dir(project_root)
token = f"{int(time.time())}-{os.getpid()}-{uuid.uuid4().hex[:8]}"
candidate = runtime_root / f"venv-candidate-{token}"
env = managed_python_env(
@@ -978,7 +731,7 @@ def _cut_over_candidate(
live: Path | None = None,
) -> tuple[bool, Path | None, SQLiteRuntimeInfo | None, str]:
live = live if live is not None else project_root / _VENV_NAME
- runtime_root = project_root / _RUNTIME_DIR_NAME
+ runtime_root = _runtime_dir(project_root)
token = f"{int(time.time())}-{os.getpid()}-{uuid.uuid4().hex[:8]}"
backup = live.with_name(f"{live.name}.stale.runtime-{token}")
rejected = runtime_root / f"venv-rejected-{token}"
@@ -1108,64 +861,6 @@ def _windows_runtime_holders() -> tuple[bool, str]:
return False, ""
-def _uv_version_string(uv_bin: str) -> str:
- """Return ``uv --version`` output, or ``""`` when it cannot be read."""
- try:
- result = subprocess.run(
- [uv_bin, "--version"],
- capture_output=True,
- text=True,
- encoding="utf-8",
- errors="replace",
- check=False,
- timeout=15,
- )
- except Exception:
- return ""
- if result.returncode != 0:
- return ""
- return (result.stdout or "").strip()
-
-
-def _refresh_managed_uv_catalog(uv_bin: str) -> bool:
- """Re-bootstrap the managed uv binary to refresh its Python catalog.
-
- The managed uv is installed with ``UV_UNMANAGED_INSTALL``, which disables
- ``uv self update`` by design — so its embedded python-build-standalone
- download catalog stays frozen at bootstrap age. python-build-standalone
- re-releases existing CPython patch versions with newer SQLite (e.g. the
- 3.11.15 build was re-cut with SQLite 3.53.x), so a stale catalog can make
- every provisioning attempt resolve to a vulnerable build even though a
- fixed build of the SAME patch version exists (issue #72093). The
- patch-retry loop cannot recover from that: the fixed build carries no
- newer version number to retry with.
-
- Re-running the official installer is the only supported refresh path for
- unmanaged installs. Only the Hermes-managed binary is ever refreshed;
- a caller-supplied foreign uv path is left alone.
-
- Returns ``True`` when the binary's version actually changed — i.e. a
- provisioning retry can now see a different catalog. ``False`` means a
- retry would resolve identically and is not worth the download cycle.
- """
- managed = managed_uv_path()
- try:
- if Path(uv_bin).resolve() != managed.resolve():
- return False
- except OSError:
- return False
- before = _uv_version_string(uv_bin)
- try:
- _install_uv(managed)
- except Exception as exc:
- logger.warning("managed uv refresh failed: %s", exc)
- return False
- after = _uv_version_string(uv_bin)
- if not after:
- return False
- return after != before
-
-
def _default_live_venv(root: Path) -> Path:
"""Return the venv that runtime repair should target for *root*.
@@ -1231,7 +926,6 @@ def _sweep_stale_runtime_backups(
def repair_vulnerable_runtime(
- uv_bin: str,
*,
project_root: Path | None = None,
venv_dir: Path | None = None,
@@ -1240,6 +934,15 @@ def repair_vulnerable_runtime(
Every failure before cutover leaves the live venv untouched. Rename or
post-cutover smoke failures restore the parked venv synchronously.
+
+ uv is resolved internally — the pinned binary via ``pm`` (its version
+ lives in ``pm/lock.json``; the bytes live in the pm store). There is
+ no foreign-uv path: the lockfile names exactly one uv, and a repair
+ that ran on someone else's uv would provision an interpreter outside
+ the catalog the pin promises. A stale python-build-standalone catalog
+ is fixed by bumping the uv pin — ``hermes update`` pulls the new
+ lockfile before repair runs, so pm has already realized the bumped
+ binary by the time this module asks for it.
"""
root = Path(project_root) if project_root is not None else _PROJECT_ROOT
live = Path(venv_dir) if venv_dir is not None else _default_live_venv(root)
@@ -1247,6 +950,14 @@ def repair_vulnerable_runtime(
if not (root / "pyproject.toml").is_file() or not live_python.is_file():
return RuntimeRepairResult("not-applicable")
+ from pm.ensure import uv as pm_uv
+
+ uv_bin, _uv_env = pm_uv()
+ if not uv_bin:
+ return RuntimeRepairResult(
+ "skipped", "pinned uv unavailable (pm could not realize it)"
+ )
+
current = probe_sqlite_runtime(live_python)
if current is None:
return RuntimeRepairResult(
@@ -1276,7 +987,7 @@ def repair_vulnerable_runtime(
sqlite_before=current.sqlite_version_string,
)
- runtime_root = root / _RUNTIME_DIR_NAME
+ runtime_root = _runtime_dir(root)
lock = _acquire_repair_lock(runtime_root)
if lock is None:
detail = "another runtime repair is already in progress"
@@ -1311,19 +1022,6 @@ def repair_vulnerable_runtime(
project_root=root,
current=current,
)
- if provisioned is None:
- # Likely a stale managed-uv catalog: python-build-standalone
- # re-releases the same patch versions with fixed SQLite, but a
- # frozen catalog keeps resolving the old vulnerable build and the
- # patch-retry loop has no newer number to try (issue #72093).
- # Refresh the managed binary and retry once.
- if _refresh_managed_uv_catalog(uv_bin):
- print(" → Managed uv refreshed; retrying provisioning...")
- provisioned = _install_safe_python_generation(
- uv_bin,
- project_root=root,
- current=current,
- )
if provisioned is None:
return RuntimeRepairResult(
"failed",
@@ -1388,67 +1086,9 @@ def repair_vulnerable_runtime(
# ---------------------------------------------------------------------------
-# Installer internals
+# Legacy stub
# ---------------------------------------------------------------------------
-def _install_uv(target: Path) -> None:
- """Bootstrap uv into *target* using the official standalone installer.
-
- Uses ``UV_UNMANAGED_INSTALL`` (POSIX) or ``UV_INSTALL_DIR`` (Windows)
- so the astral installer writes the binary directly into
- ``$HERMES_HOME/bin/`` instead of ``~/.local/bin/``.
- """
- system = platform.system()
- env = {
- **os.environ,
- # Tell the astral installer to drop the binary in our dir, not
- # ~/.local/bin. UV_UNMANAGED_INSTALL is the POSIX env var; Windows
- # uses UV_INSTALL_DIR.
- "UV_UNMANAGED_INSTALL": str(target.parent),
- "UV_INSTALL_DIR": str(target.parent),
- }
-
- if system == "Windows":
- _install_uv_windows(env)
- else:
- _install_uv_posix(env)
-
-
-def _install_uv_posix(env: dict[str, str]) -> None:
- """Download + sh the POSIX installer (two-stage to avoid curl|sh pitfalls)."""
- with tempfile.NamedTemporaryFile(suffix=".sh", delete=False) as f:
- installer_path = f.name
-
- try:
- subprocess.run(
- ["curl", "-LsSf", "https://astral.sh/uv/install.sh", "-o", installer_path],
- check=True,
- capture_output=True,
- )
- subprocess.run(
- ["sh", installer_path],
- env=env,
- check=True,
- capture_output=True,
- )
- finally:
- try:
- os.unlink(installer_path)
- except OSError:
- pass
-
-
-def _install_uv_windows(env: dict[str, str]) -> None:
- """Invoke the PowerShell installer."""
- cmd = "irm https://astral.sh/uv/install.ps1 | iex"
- subprocess.run(
- ["powershell", "-ExecutionPolicy", "Bypass", "-c", cmd],
- env=env,
- check=True,
- capture_output=True,
- )
-
-
def rebuild_venv(uv_bin: str, venv_dir: Path, python_version: str = "3.11") -> bool:
- True # dont remove me. ask ethernet
+ return True # dont remove me. ask ethernet
diff --git a/hermes_cli/steward.py b/hermes_cli/steward.py
new file mode 100644
index 00000000000..68d610acac6
--- /dev/null
+++ b/hermes_cli/steward.py
@@ -0,0 +1,207 @@
+"""Steward classification and refusal text for sealed install trees.
+
+Adapted from the restack branch's ``installation/tree.py``. Our branch has
+no ``installation`` package yet — detection here is rewritten onto the two
+facts this branch already ships:
+
+* ``.git`` at the project root says the tree is a checkout the uninstaller
+ / updater may mutate.
+* The build stamp (``install-stamp.json``, written by
+ ``scripts/write_install_stamp.py``) names the steward in
+ ``distribution`` (``desktop-app``, ``docker``, ``nix``, or a future
+ package manager) for sealed trees.
+
+A sealed tree (no ``.git``) belongs to a steward: only the steward removes
+or replaces its code. The refusal messages below always leave the user a
+working next step for their data (``hermes uninstall --data`` / the
+desktop app's Settings -> About page).
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+from pathlib import Path
+from typing import Optional
+
+BUILD_INFO_NAME = "install-stamp.json"
+
+STEWARD_DESKTOP = "desktop-app"
+STEWARD_DOCKER = "docker"
+STEWARD_NIX = "nix"
+
+# What `hermes update` says in a sealed tree, per steward — the refusal
+# table shared by the update admission gate. The fallback covers stewards
+# this build does not know (a newer package-manager value read by older
+# code).
+STEWARD_UPDATE_MESSAGES = {
+ STEWARD_DESKTOP: (
+ "✗ This Hermes runs from inside the desktop app bundle.\n"
+ "\n"
+ "Manage updates from within the desktop app.\n"
+ "Prefer a self-managed source install? See:\n"
+ " https://hermes-agent.nousresearch.com/docs/user-guide/switching-to-source"
+ ),
+ STEWARD_NIX: (
+ "✗ This Hermes runs from the Nix store.\n"
+ "\n"
+ "The store path is immutable. Update through your flake:\n"
+ " nix flake update && rebuild your profile or system"
+ ),
+}
+
+_STEWARD_UPDATE_FALLBACK = (
+ "✗ This Hermes install is managed by {steward}.\n"
+ "\n"
+ "The tree has no git checkout, so `hermes update` cannot update it.\n"
+ "Update it with the tool that installed it."
+)
+
+# What the uninstaller says when it refuses to remove code from a sealed
+# tree. The steward put the code there; the steward removes it. The
+# desktop-app message is per-OS because each OS owns app removal
+# differently.
+_STEWARD_DELETE_DATA_PREAMBLE = "To delete your Hermes data (chats, configuration, etc),\n"
+_STEWARD_DELETE_DATA_CLI = "run:\n$ hermes uninstall --data\n"
+_STEWARD_DELETE_DATA_DESKTOP = "Open Hermes Desktop, go to Settings -> About, and delete your data from there.\n"
+
+_STEWARD_UNINSTALL_MESSAGES = {
+ STEWARD_DOCKER: (
+ "✗ This Hermes runs from a Docker image.\n"
+ "\n"
+ "There is no code to uninstall — remove the container and image:\n"
+ " docker rm <container> && docker rmi nousresearch/hermes-agent\n"
+ "\n" +
+ _STEWARD_DELETE_DATA_PREAMBLE +
+ _STEWARD_DELETE_DATA_CLI
+ ),
+ STEWARD_NIX: (
+ "✗ This Hermes was installed by Nix.\n"
+ "\n"
+ "The store path is immutable — uninstall it the same way you\n"
+ "installed it: remove hermes-agent from your flake / profile\n"
+ "(e.g. `nix profile remove`), then rebuild.\n"
+ "\n" +
+ _STEWARD_DELETE_DATA_PREAMBLE +
+ _STEWARD_DELETE_DATA_CLI
+ ),
+}
+
+_STEWARD_MANAGED_BY_DESKTOP = "✗ Hermes is managed by the desktop app.\n"
+
+_STEWARD_DESKTOP_UNINSTALL_BY_PLATFORM = {
+ "win32": (
+ _STEWARD_MANAGED_BY_DESKTOP +
+ "\n"
+ "Remove the app from Windows Settings → Apps → Installed apps.\n" +
+ _STEWARD_DELETE_DATA_PREAMBLE +
+ _STEWARD_DELETE_DATA_DESKTOP
+ ),
+ "darwin": (
+ _STEWARD_MANAGED_BY_DESKTOP +
+ "\n"
+ "Quit the app and drag Hermes.app from Applications to the Trash.\n" +
+ _STEWARD_DELETE_DATA_PREAMBLE +
+ _STEWARD_DELETE_DATA_DESKTOP
+ ),
+}
+
+_STEWARD_DESKTOP_UNINSTALL_DEFAULT = (
+ _STEWARD_MANAGED_BY_DESKTOP +
+ "\n"
+ "Delete the Hermes AppImage (or app directory) from wherever you\n"
+ "saved it.\n" +
+ _STEWARD_DELETE_DATA_PREAMBLE +
+ _STEWARD_DELETE_DATA_DESKTOP
+)
+
+_STEWARD_UNINSTALL_FALLBACK = (
+ "✗ Hermes is managed by {steward}.\n"
+ "\n"
+ "The tree has no git checkout, so the uninstaller will not remove it.\n"
+ "Remove it with the tool that installed it.\n"
+ "\n" +
+ # A generic package-manager steward has no desktop app, and this
+ # refusal prints in a CLI context — point at the CLI data path.
+ _STEWARD_DELETE_DATA_PREAMBLE +
+ _STEWARD_DELETE_DATA_CLI
+)
+
+
+def steward_update_message(steward: str) -> str:
+ """The `hermes update` refusal text for a sealed tree."""
+ message = STEWARD_UPDATE_MESSAGES.get(steward)
+ if message is not None:
+ return message
+ return _STEWARD_UPDATE_FALLBACK.format(steward=steward)
+
+
+def steward_uninstall_message(steward: str, platform: "str | None" = None) -> str:
+ """The uninstall refusal text for a sealed tree."""
+ if steward == STEWARD_DESKTOP:
+ key = platform if platform is not None else sys.platform
+ return _STEWARD_DESKTOP_UNINSTALL_BY_PLATFORM.get(key, _STEWARD_DESKTOP_UNINSTALL_DEFAULT)
+ message = _STEWARD_UNINSTALL_MESSAGES.get(steward)
+ if message is not None:
+ return message
+ return _STEWARD_UNINSTALL_FALLBACK.format(steward=steward)
+
+
+def read_install_stamp(project_root: Path) -> dict:
+ """The build stamp of ``project_root``, or ``{}``.
+
+ Tolerant by design: steward classification must not crash a refusal
+ path on a malformed stamp — a tree we cannot prove is ours still
+ refuses (see :func:`sealed_steward`), so garbage degrades safely.
+ """
+ try:
+ data = json.loads(
+ (Path(project_root) / BUILD_INFO_NAME).read_text(encoding="utf-8-sig")
+ )
+ except (OSError, ValueError):
+ return {}
+ return data if isinstance(data, dict) else {}
+
+
+def is_bundled_payload(project_root: Path) -> bool:
+ """True when ``project_root`` is a bundled desktop payload's ``repo/``.
+
+ THE shape predicate for the sealed-bundle branch, and a mirror of the
+ Electron shell's ``installShape() === 'bundled'``: the build stamp is
+ the authority, so filesystem coincidences (a sibling ``bin/``, a
+ surviving ``apps/desktop/package.json``) can never promote a checkout
+ into it. A missing, foreign, or unreadable stamp means NOT bundled.
+ """
+ try:
+ return read_install_stamp(Path(project_root)).get("payload") == "bundled"
+ except Exception: # noqa: BLE001 — a bad stamp must not take a caller down
+ return False
+
+
+def sealed_steward(project_root: Path) -> Optional[str]:
+ """The steward owning the sealed tree at ``project_root``, or ``None``.
+
+ ``None`` means the tree is a git checkout (``.git`` present — a
+ directory, or a worktree/submodule gitfile) and is ours to mutate.
+ Everything else is sealed: the stamp's ``distribution`` names the
+ steward, and a missing or unreadable stamp gives ``"unknown"`` —
+ a tree we cannot prove is ours is not ours to remove.
+ """
+ root = Path(project_root)
+ if (root / ".git").exists():
+ return None
+ distribution = read_install_stamp(root).get("distribution")
+ return distribution if isinstance(distribution, str) and distribution else "unknown"
+
+
+def classify_install(project_root: Path) -> "tuple[str, bool]":
+ """(steward, code_removal_allowed) for the tree at ``project_root``.
+
+ A git checkout reports ``("git", True)``; a sealed tree reports its
+ steward and ``False``. Used by ``gui_install_summary`` so the desktop
+ UI can gate its destructive options on the same ladder the CLI uses.
+ """
+ steward = sealed_steward(project_root)
+ if steward is None:
+ return ("git", True)
+ return (steward, False)
diff --git a/hermes_cli/subcommands/uninstall.py b/hermes_cli/subcommands/uninstall.py
index f746a8906a6..45271ca96f1 100644
--- a/hermes_cli/subcommands/uninstall.py
+++ b/hermes_cli/subcommands/uninstall.py
@@ -29,6 +29,12 @@ def build_uninstall_parser(subparsers, *, cmd_uninstall: Callable) -> None:
action="store_true",
help="Uninstall only the desktop Chat GUI, leaving the agent intact",
)
+ uninstall_parser.add_argument(
+ "--data",
+ action="store_true",
+ help="Remove only Hermes user data (~/.hermes), leaving installed code "
+ "intact — the one mode that works on Nix / bundled-app / Docker installs",
+ )
uninstall_parser.add_argument(
"--gui-summary",
action="store_true",
diff --git a/hermes_cli/subcommands/update.py b/hermes_cli/subcommands/update.py
index 58c37e1d8bc..4f8f2fa06dd 100644
--- a/hermes_cli/subcommands/update.py
+++ b/hermes_cli/subcommands/update.py
@@ -111,4 +111,38 @@ def build_update_parser(subparsers, *, cmd_update: Callable) -> None:
default=False,
help="Windows: mutate the venv even while other processes are running from its interpreter (desktop backend, gateway, terminals). Those processes keep native .pyd files locked, so the dependency sync will likely fail partway and strand the install half-updated. Use only if you know the detected holders are false positives.",
)
+ update_parser.add_argument(
+ "--set-channel",
+ default=None,
+ choices=("main", "stable", "nightly"),
+ metavar="CHANNEL",
+ help=(
+ "Persist the update channel for THIS install (recorded per "
+ "install in config.yaml under update.installs). 'stable' tracks "
+ "tagged releases, 'main' the git main branch, 'nightly' the "
+ "nightly prereleases (desktop bundles only; source installs "
+ "normalize nightly to main). Installs whose updates an external "
+ "steward owns (nix, docker, app stores) have no channel."
+ ),
+ )
+ update_parser.add_argument(
+ "--install-id",
+ action="store_true",
+ default=False,
+ help=(
+ "Print this install's id and path (the id keys its per-install "
+ "channel record in config.yaml) and exit."
+ ),
+ )
+ update_parser.add_argument(
+ "--channel",
+ default=None,
+ choices=("stable", "main", "nightly"),
+ metavar="CHANNEL",
+ help=(
+ "Track CHANNEL for this run only (transient override; "
+ "--set-channel persists). 'stable' updates to the newest tagged "
+ "release, 'main' to the branch tip."
+ ),
+ )
update_parser.set_defaults(func=cmd_update)
diff --git a/hermes_cli/update_channel.py b/hermes_cli/update_channel.py
new file mode 100644
index 00000000000..1c8375e2d43
--- /dev/null
+++ b/hermes_cli/update_channel.py
@@ -0,0 +1,305 @@
+"""Per-install update-channel records.
+
+Channel storage — per install, never home-global::
+
+ update:
+ installs:
+ a4f3b2c1d0e9f8a7: # install id (sha16 of the
+ path: /home/u/.hermes/hermes-agent # canonical install root)
+ channel: nightly
+
+One config.yaml serves many installs (host + docker gateway + desktop all
+bind-mount one ``~/.hermes``), so a home-global ``update.channel`` key is
+UNSAFE and does not exist: setting nightly for a dev checkout must not
+flip the desktop app's feed. The id is sha16 of the canonical
+install-root PATH — the same key that names the ``installs/<sha16>/``
+state folder (``boot_bootstrap._install_key``; a byte-identical helper is
+inlined below until that module lands). Path-derived on purpose: an
+electron-updater update replaces the artifact (new stamp bytes) at the
+same path, and the channel opt-in must survive that.
+
+* Written by ``hermes update --set-channel <x>`` from inside an install
+ (it knows its own id — the user never types a sha).
+* Shown by ``hermes update --install-id`` and the desktop About page.
+* Channels are meaningful ONLY where the mechanism is ``self`` (which git
+ ref: main / stable / nightly→main) or ``electron-updater`` (which feed:
+ latest.yml / nightly.yml). ``external`` installs have no channel; the
+ steward owns updates.
+
+Pure-stdlib leaf module (plus hermes-internal imports done lazily): the
+installers and boot paths read it before the full config machinery loads.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import os
+import re
+from pathlib import Path
+from typing import Any, Optional
+
+logger = logging.getLogger(__name__)
+
+CHANNEL_MAIN = "main"
+CHANNEL_STABLE = "stable"
+CHANNEL_NIGHTLY = "nightly"
+VALID_CHANNELS = (CHANNEL_MAIN, CHANNEL_STABLE, CHANNEL_NIGHTLY)
+
+# A nightly release tag: v<major>.<minor>.<patch>-nightly.<YYYYMMDDHHMMSS>,
+# or the legacy date-only shape. THIS is the single authority for the
+# nightly tag shape — scripts/release.py (produces them) and
+# scripts/write_install_stamp.py (validates the feed key) import it rather
+# than re-typing the rule. Nightlies are current-stable patch+1, so any
+# patch is accepted here.
+_NIGHTLY_TAG_RE = re.compile(r"^v(?:0|[1-9]\d{0,2})\.\d+\.\d+-nightly\.20\d{6}(?:\d{6})?$")
+
+
+def is_nightly_tag(tag: Any) -> bool:
+ """True when ``tag`` is a nightly release tag."""
+ return isinstance(tag, str) and bool(_NIGHTLY_TAG_RE.match(tag.strip()))
+
+
+def nightly_tag_for_date(version: str, date_utc: str) -> str:
+ """The nightly tag name for a UTC timestamp: next PATCH over ``version``
+ (the newest stable's patch + 1), second-precision UTC suffix —
+ v0.27.5-nightly.20260818103000 when stable is v0.27.4. A nightly
+ outversions every stable at or below its patch and loses to the next
+ stable patch, which is exactly the channel-switch upgrade path
+ (nightly→stable = wait for that patch bump to ship as stable).
+ """
+ parts = version.lstrip("v").split(".")
+ major, minor = int(parts[0]), int(parts[1])
+ patch = int(parts[2]) if len(parts) >= 3 else 0
+ return f"v{major}.{minor}.{patch + 1}-nightly.{date_utc}"
+
+
+def _install_key_sha16(project_root: Path) -> str:
+ """sha16 of the canonical install-root PATH.
+
+ NOTE: dedupe with ``boot_bootstrap._install_key`` at assembly — this
+ is a byte-identical inline copy (sha256 of the resolved root, first 16
+ hex chars). Lane w2a ports boot_bootstrap in parallel; this module must
+ not import from it until both land.
+ """
+ try:
+ canonical = str(Path(project_root).resolve())
+ except OSError:
+ canonical = str(project_root)
+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:16]
+
+
+def _installs_root() -> Path:
+ """The parent of every per-install state folder.
+
+ NOTE: dedupe with ``boot_bootstrap.installs_root`` at assembly —
+ anchored to the DEFAULT home (profiles share one folder per install).
+ """
+ from hermes_cli.profiles import _get_default_hermes_home
+
+ return _get_default_hermes_home() / "installs"
+
+
+def _default_root() -> Path:
+ """This process's install root.
+
+ Mirrors version_info's stamp resolution: HERMES_INSTALL_ROOT when the
+ steward wrapper sets it (Nix points it at the sealed tree), else the
+ code root of the executing checkout.
+ """
+ root = os.environ.get("HERMES_INSTALL_ROOT")
+ return Path(root) if root else Path(__file__).parent.parent.resolve()
+
+
+def install_id(project_root: Optional[Path] = None) -> str:
+ """The sha16 id of the install at ``project_root`` (default: this one).
+
+ Same identity as the ``installs/<sha16>/`` state folder key.
+ """
+ if project_root is None:
+ project_root = _default_root()
+ return _install_key_sha16(Path(project_root))
+
+
+def _read_stamp(root: Path) -> dict:
+ """The install stamp of ``root``, or ``{}`` (tolerant, like steward.py)."""
+ from hermes_cli.steward import read_install_stamp
+
+ return read_install_stamp(root)
+
+
+def _install_records(config: Optional[dict]) -> dict:
+ if not isinstance(config, dict):
+ return {}
+ update_cfg = config.get("update")
+ if not isinstance(update_cfg, dict):
+ return {}
+ installs = update_cfg.get("installs")
+ return installs if isinstance(installs, dict) else {}
+
+
+def channel_record(config: Optional[dict], project_root: Optional[Path] = None) -> dict:
+ """This install's ``{path, channel}`` record from config, or ``{}``."""
+ record = _install_records(config).get(install_id(project_root))
+ return record if isinstance(record, dict) else {}
+
+
+def default_channel(project_root: Optional[Path] = None) -> str:
+ """The channel an unconfigured install tracks.
+
+ ``self`` source installs follow main (historical behavior).
+ ``electron-updater`` bundles follow the channel their own artifact was
+ published to: a nightly artifact tracks nightly, every other bundle
+ tracks stable. The stamp's ``tag`` is the authority, the same fact
+ apps/desktop/product-identity.cjs keys the published feed name on — so
+ the feed a nightly artifact asks for and the feed it was published to
+ can never disagree. Deriving stable here instead would send a fresh
+ nightly install to look for its ``nightly.yml`` feed file under the
+ newest STABLE release, where that file does not exist (404), leaving
+ the install unable to update at all.
+ """
+ root = Path(project_root) if project_root is not None else _default_root()
+ stamp = _read_stamp(root)
+ if stamp.get("updateMechanism") != "electron-updater":
+ return CHANNEL_MAIN
+ return CHANNEL_NIGHTLY if is_nightly_tag(stamp.get("tag")) else CHANNEL_STABLE
+
+
+def resolve_update_channel(
+ config: Optional[dict] = None,
+ project_root: Optional[Path] = None,
+) -> str:
+ """The effective update channel for this install.
+
+ Resolution: the per-install record (``update.installs.<sha16>.channel``)
+ when valid; otherwise the mechanism default (main for self-source,
+ stable/nightly for electron-updater bundles by artifact tag). Source
+ installs asking for nightly normalize to main — nightly builds are
+ release artifacts, and a git checkout tracks branches; callers print
+ the note.
+ """
+ configured: Any = channel_record(config, project_root).get("channel")
+ if isinstance(configured, str) and configured.strip().lower() in VALID_CHANNELS:
+ channel = configured.strip().lower()
+ else:
+ channel = default_channel(project_root)
+
+ if channel == CHANNEL_NIGHTLY:
+ root = Path(project_root) if project_root is not None else _default_root()
+ if _read_stamp(root).get("updateMechanism") != "electron-updater":
+ # nightly→main normalization for source installs.
+ return CHANNEL_MAIN
+ return channel
+
+
+def nightly_normalized_note() -> str:
+ """The one-line note callers print when nightly normalizes to main."""
+ return (
+ "→ Channel 'nightly' on a source install tracks main "
+ "(nightly builds are desktop release artifacts)."
+ )
+
+
+def set_install_channel(
+ channel: str,
+ project_root: Optional[Path] = None,
+) -> str:
+ """Persist ``channel`` for THIS install in config.yaml. Returns the id.
+
+ Refuses on ``external`` mechanism — those installs have no channel;
+ the steward owns updates. Raises ``ValueError`` for both bad channel
+ values and external installs; the CLI surfaces the message.
+ """
+ channel = (channel or "").strip().lower()
+ if channel not in VALID_CHANNELS:
+ raise ValueError(
+ f"unknown channel {channel!r} (one of {', '.join(VALID_CHANNELS)})"
+ )
+
+ root = Path(project_root) if project_root is not None else _default_root()
+ stamp = _read_stamp(root)
+ if stamp.get("updateMechanism") == "external":
+ distribution = stamp.get("distribution") or "an external steward"
+ raise ValueError(
+ f"channels don't apply here; updates are owned by {distribution}"
+ )
+
+ sha16 = install_id(root)
+ _write_channel_record(sha16, str(root), channel)
+ return sha16
+
+
+def _write_channel_record(sha16: str, path: str, channel: str) -> None:
+ """Write ``update.installs.<sha16>`` into config.yaml, preserving the rest."""
+ import yaml
+
+ from hermes_cli.config import get_config_path
+
+ config_path = get_config_path()
+ try:
+ raw = yaml.safe_load(config_path.read_text(encoding="utf-8-sig")) or {}
+ except FileNotFoundError:
+ raw = {}
+ if not isinstance(raw, dict):
+ raise ValueError(f"config at {config_path} is not a mapping")
+
+ update_cfg = raw.setdefault("update", {})
+ if not isinstance(update_cfg, dict):
+ raise ValueError("config key 'update' is not a mapping")
+ installs = update_cfg.setdefault("installs", {})
+ if not isinstance(installs, dict):
+ raise ValueError("config key 'update.installs' is not a mapping")
+ record = installs.setdefault(sha16, {})
+ if not isinstance(record, dict):
+ record = {}
+ installs[sha16] = record
+ record["path"] = path # DATA, for humans + doctor GC
+ record["channel"] = channel
+
+ config_path.parent.mkdir(parents=True, exist_ok=True)
+ tmp = config_path.with_suffix(config_path.suffix + ".tmp")
+ tmp.write_text(
+ yaml.safe_dump(raw, sort_keys=False, allow_unicode=True), encoding="utf-8"
+ )
+ tmp.replace(config_path)
+
+
+def stale_channel_records(config: Optional[dict]) -> list[tuple[str, dict, str]]:
+ """Doctor's staleness triad over ``update.installs``.
+
+ Returns ``(sha16, record, reason)`` where reason is one of:
+
+ * ``"replaced"`` — the recorded path exists but the install there keys
+ to a DIFFERENT sha16 (the tree moved / was recreated elsewhere and a
+ new record claimed it; this one is a leftover).
+ * ``"missing"`` — nothing at the recorded path: offer GC (keep-on-doubt).
+ * ``"unclaimed"`` — the sha16 matches no live install record
+ (``installs/<sha16>/install.json``): offer GC.
+ """
+ stale: list[tuple[str, dict, str]] = []
+ for sha16, record in _install_records(config).items():
+ if not isinstance(record, dict):
+ continue
+ recorded_path = record.get("path")
+ if not isinstance(recorded_path, str) or not recorded_path:
+ # No path fact — fall through to the live-record check only.
+ recorded_path = None
+
+ if recorded_path is not None:
+ path = Path(recorded_path)
+ if not path.exists():
+ stale.append((sha16, record, "missing"))
+ continue
+ if _install_key_sha16(path) != sha16:
+ stale.append((sha16, record, "replaced"))
+ continue
+
+ # Cross-check against the live install-state records: a channel
+ # record whose sha16 has no installs/<sha16>/install.json was
+ # either hand-written or its install never booted post-record.
+ try:
+ if not (_installs_root() / sha16 / "install.json").is_file():
+ stale.append((sha16, record, "unclaimed"))
+ except Exception as exc: # noqa: BLE001 — doctor sweep must not raise
+ logger.debug("installs root unavailable: %s", exc)
+ return stale
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py
index dc5da42d472..000c1f03699 100644
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@ -27,6 +27,7 @@ import hashlib
import json
import logging
import os
+import re
import shlex
import shutil
import subprocess
@@ -58,7 +59,7 @@ def _m():
_UPDATE_RUNTIME_RELOAD_MODULES = (
"hermes_constants",
"tools.environments.local",
- "tools.lazy_deps",
+ "pm.extras",
)
#: Package prefixes whose cached modules become stale the moment the checkout
@@ -559,45 +560,6 @@ _INSTALL_DEFINING_FILES = (
"uv.lock",
)
-def _editable_install_is_current(git_cmd, cwd, pre_pull_sha: str | None) -> bool:
- """True when the pulled commits cannot have invalidated the editable install.
-
- ``uv pip install -e .`` never audits an editable target — it reinstalls on
- every invocation, and every reinstall rewrites the console-script shims.
- On Windows that rewrite is the only reason the running ``hermes.exe`` has
- to be quarantined, and a quarantine that loses its race is the whole
- ``os error 32`` family. Not reinstalling when the reinstall provably
- cannot change anything removes that risk outright for the common update,
- rather than trying to make the rename win more often.
-
- Skipping is safe because Hermes pins its editable finder to a *static*
- module list (``[tool.setuptools] py-modules`` plus
- ``packages.find.include``). The one source-only change that would stale
- that finder is a new top-level module or package, and it cannot land
- without a ``pyproject.toml`` diff. Dependencies and ``[project.scripts]``
- live there too. New submodules inside an already-mapped package resolve
- through the real package directory and need no reinstall.
-
- Fails closed: an unresolvable pre-pull SHA (shallow checkout, ZIP swap)
- or a failed ``git diff`` returns False and the install runs as before.
- """
- if not pre_pull_sha:
- return False
- try:
- result = subprocess.run(
- git_cmd
- + ["diff", "--name-only", f"{pre_pull_sha}..HEAD", "--"]
- + list(_INSTALL_DEFINING_FILES),
- cwd=cwd,
- capture_output=True,
- text=True, encoding="utf-8", errors="replace",
- )
- except OSError:
- return False
- if result.returncode != 0:
- return False
- return not result.stdout.strip()
-
def _validate_critical_files_syntax(root) -> tuple[bool, str | None, str | None]:
"""Compile each file in ``_UPDATE_CRITICAL_FILES`` to catch SyntaxErrors.
@@ -765,7 +727,7 @@ def _gateway_prompt(prompt_text: str, default: str = "", timeout: float = 300.0)
while _time.monotonic() < deadline:
if response_path.exists():
try:
- answer = response_path.read_text(encoding="utf-8").strip()
+ answer = response_path.read_text(encoding="utf-8-sig").strip()
response_path.unlink(missing_ok=True)
prompt_path.unlink(missing_ok=True)
return answer if answer else default
@@ -1666,6 +1628,159 @@ def _is_zip_preserved_entry_status_line(line: str) -> bool:
return True
+# Release tags have the form v1.2.3. A tag can have a pre-release suffix.
+# The stable channel ignores tags with a suffix. Stable means final releases only.
+# The major component is capped at three digits. The historical CalVer tags
+# (for example v2026.7.20) use a four-digit year, and a numeric sort would
+# rank them above every SemVer release. This matches _SEMVER_TAG_RE in
+# scripts/write_install_stamp.py.
+_RELEASE_TAG_RE = re.compile(r"^v(0|[1-9]\d{0,2})\.(\d+)\.(\d+)$")
+
+
+def _parse_release_tag(tag: str):
+ """Parse ``vX.Y.Z`` into a sortable (X, Y, Z) tuple, or return None.
+
+ Tags with a pre-release or build suffix (``v1.2.3-rc1``) return None.
+ Tags that do not have the shape of a final release also return None.
+ The stable channel only moves between final releases.
+ """
+ m = _RELEASE_TAG_RE.match(tag.strip())
+ if not m:
+ return None
+ return tuple(int(g) for g in m.groups())
+
+
+def _latest_release_tag_from_ls_remote(output: str):
+ """Select the newest final-release tag from ``git ls-remote --tags`` output.
+
+ Returns ``(tag, sha)`` or ``(None, None)``. Peeled entries (``^{}``) have
+ priority over the tag-object SHA. Thus annotated tags and lightweight tags
+ both give the commit SHA.
+ """
+ best = None # (version_tuple, tag)
+ shas = {} # tag -> commit sha (peeled wins)
+ for line in output.splitlines():
+ parts = line.split("\t")
+ if len(parts) != 2:
+ continue
+ sha, ref = parts
+ if not ref.startswith("refs/tags/"):
+ continue
+ name = ref[len("refs/tags/"):]
+ peeled = name.endswith("^{}")
+ if peeled:
+ name = name[:-3]
+ version = _parse_release_tag(name)
+ if version is None:
+ continue
+ if peeled or name not in shas:
+ shas[name] = sha.strip()
+ if best is None or version > best[0]:
+ best = (version, name)
+ if best is None:
+ return None, None
+ tag = best[1]
+ return tag, shas.get(tag)
+
+
+def _resolve_latest_release_tag(git_cmd, cwd):
+ """Ask origin for the newest final release tag. Returns (tag, sha) or (None, None)."""
+ try:
+ result = subprocess.run(
+ git_cmd + ["ls-remote", "--tags", "origin", "v*"],
+ cwd=cwd,
+ capture_output=True,
+ text=True, encoding="utf-8", errors="replace",
+ timeout=60,
+ )
+ except (subprocess.TimeoutExpired, OSError) as exc:
+ logger.warning("Could not list release tags from origin: %s", exc)
+ return None, None
+ if result.returncode != 0:
+ logger.warning(
+ "git ls-remote --tags failed: %s",
+ (result.stderr or "").strip().splitlines()[:1],
+ )
+ return None, None
+ return _latest_release_tag_from_ls_remote(result.stdout)
+
+
+def _stable_channel_active(args) -> bool:
+ """Return True when this update must track tagged releases, not a branch.
+
+ ``args`` is the update argparse namespace, or None when the caller has no
+ flags to honor. An explicit ``--branch`` always wins (the user names the
+ exact update target; a tag silently overriding it would resurrect the bug
+ class --branch prevents). An explicit ``--channel`` is the transient
+ per-invocation override (``--set-channel`` is the persistent one). In all
+ other cases the effective channel comes from the per-install record
+ (see hermes_cli.update_channel.resolve_update_channel).
+ """
+ if getattr(args, "branch", None):
+ return False
+ transient = getattr(args, "channel", None)
+ if transient:
+ from hermes_cli.update_channel import CHANNEL_STABLE
+
+ # nightly on a source tree normalizes to main (not stable).
+ return transient == CHANNEL_STABLE
+ try:
+ from hermes_cli.config import load_config
+ from hermes_cli.update_channel import CHANNEL_STABLE, resolve_update_channel
+
+ config = None
+ try:
+ config = load_config()
+ except Exception as exc:
+ logger.debug("Could not load config for channel resolution: %s", exc)
+ return resolve_update_channel(config, _m().PROJECT_ROOT) == CHANNEL_STABLE
+ except Exception as exc:
+ logger.warning("Channel resolution failed; defaulting to main: %s", exc)
+ return False
+
+
+def _github_latest_release_tag():
+ """Resolve the newest final-release tag with the GitHub API (no git necessary).
+
+ The ZIP-fallback path uses this function. That path exists because git
+ file I/O is broken. The function tries /releases/latest first, because that
+ endpoint obeys the draft and prerelease curation. If that fails, it lists
+ the tags and selects the maximum final release.
+ Returns the tag name or None.
+ """
+ import urllib.error
+ import urllib.request
+
+ def _get_json(url):
+ req = urllib.request.Request(
+ url, headers={"Accept": "application/vnd.github+json",
+ "User-Agent": "hermes-update"}
+ )
+ with urllib.request.urlopen(req, timeout=30) as resp:
+ return json.loads(resp.read().decode("utf-8"))
+
+ base = "https://api.github.com/repos/NousResearch/hermes-agent"
+ try:
+ data = _get_json(f"{base}/releases/latest")
+ tag = data.get("tag_name")
+ if isinstance(tag, str) and _parse_release_tag(tag) is not None:
+ return tag
+ except (urllib.error.URLError, OSError, ValueError) as exc:
+ logger.debug("GitHub /releases/latest unavailable: %s", exc)
+ try:
+ tags = _get_json(f"{base}/tags?per_page=100")
+ best = None
+ for entry in tags if isinstance(tags, list) else []:
+ name = entry.get("name") if isinstance(entry, dict) else None
+ version = _parse_release_tag(name) if isinstance(name, str) else None
+ if version is not None and (best is None or version > best[0]):
+ best = (version, name)
+ return best[1] if best else None
+ except (urllib.error.URLError, OSError, ValueError) as exc:
+ logger.debug("GitHub /tags unavailable: %s", exc)
+ return None
+
+
def _is_zip_staging_artifact_status_line(line: str) -> bool:
"""True when a porcelain status line is our own two-phase-swap artifact."""
payload = line[3:] if len(line) >= 3 else line
@@ -1859,8 +1974,20 @@ def _update_via_zip(args, *, had_desktop_app_before_update: bool = False) -> boo
)
_m().sys.exit(1)
_abort_zip_update_if_dirty_tree()
+ # Stable channel: pull the archive of the release tag, not main. The ZIP
+ # path runs when git file I/O is broken. Thus resolve the tag with the
+ # GitHub API, not with git. No git invocation is necessary.
+ zip_ref = f"refs/heads/{branch}"
+ if _stable_channel_active(args):
+ tag = _github_latest_release_tag()
+ if tag is None:
+ print("✗ Hermes cannot resolve the latest release from the GitHub API.")
+ print(" Switch channels with: hermes update --set-channel main")
+ _m().sys.exit(1)
+ print(f"→ Update channel: stable. Hermes downloads release {tag}.")
+ zip_ref = f"refs/tags/{tag}"
zip_url = (
- f"https://github.com/NousResearch/hermes-agent/archive/refs/heads/{branch}.zip"
+ f"https://github.com/NousResearch/hermes-agent/archive/{zip_ref}.zip"
)
print("→ Downloading latest version...")
@@ -2042,55 +2169,21 @@ def _update_via_zip(args, *, had_desktop_app_before_update: bool = False) -> boo
_m()._abort_dependency_sync_if_self_locked()
print("→ Updating Python dependencies...")
- from hermes_cli.managed_uv import ensure_uv, update_managed_uv
-
- # Keep managed uv current — runs `uv self update` if we already have one.
- update_managed_uv()
+ import pm
- uv_bin = ensure_uv()
-
- pip_cmd = [_m().sys.executable, "-m", "pip"]
- if not uv_bin:
- uv_bin = _ensure_uv_for_termux(pip_cmd)
- if uv_bin:
- # Same third-party UV-env isolation as the main update path (#83914):
- # a user-level UV_PYTHON_INSTALL_DIR / UV_PYTHON from unrelated
- # software must not steer which interpreter uv resolves here.
- from hermes_cli.managed_uv import managed_python_env
-
- uv_env = managed_python_env()
- uv_env["VIRTUAL_ENV"] = str(_m().PROJECT_ROOT / "venv")
- if _m()._is_termux_env(uv_env):
- uv_env.pop("PYTHONPATH", None)
- uv_env.pop("PYTHONHOME", None)
- try:
- _m()._install_python_dependencies_with_optional_fallback([uv_bin, "pip"], env=uv_env)
- except _shim_quarantine_error_type() as _sqe:
- # #87331: this runs inside the ZIP-fallback error handler, so the
- # boundary except clause in cmd_update cannot catch it — refuse
- # here with the same defer-via-marker contract.
- _refuse_update_for_contended_shims(_sqe)
- else:
- # Use sys.executable to explicitly call the venv's pip module,
- # avoiding PEP 668 'externally-managed-environment' errors on Debian/Ubuntu.
- # Some environments lose pip inside the venv; bootstrap it back with
- # ensurepip before trying the editable install.
- try:
- subprocess.run(
- pip_cmd + ["--version"],
- cwd=_m().PROJECT_ROOT,
- check=True,
- capture_output=True,
- )
- except subprocess.CalledProcessError:
- subprocess.run(
- [_m().sys.executable, "-m", "ensurepip", "--upgrade", "--default-pip"],
- cwd=_m().PROJECT_ROOT,
- check=True,
- )
- _m()._install_python_dependencies_with_optional_fallback(pip_cmd)
+ try:
+ pm.sync_venv(["all"], explicit=True)
+ except _shim_quarantine_error_type() as _sqe:
+ # #87331: this runs inside the ZIP-fallback error handler, so the
+ # boundary except clause in cmd_update cannot catch it — refuse
+ # here with the same defer-via-marker contract.
+ _refuse_update_for_contended_shims(_sqe)
+ except pm.InstallError as _sync_err:
+ print(f" ✗ {_sync_err}")
+ print(" Re-run `hermes update` (or `hermes pm install`) once resolved.")
- install_prefix = [uv_bin, "pip"] if uv_bin else pip_cmd
+ uv_bin, uv_env = pm.uv(venv=_m().PROJECT_ROOT / "venv")
+ install_prefix = [uv_bin, "pip"] if uv_bin else [_m().sys.executable, "-m", "pip"]
install_env = uv_env if uv_bin else None
_m()._restore_active_tool_dependencies(
active_tool_dependencies,
@@ -2946,11 +3039,14 @@ def _clear_fleet_restart_pending_marker() -> None:
def _current_checkout_sha() -> str | None:
"""Current on-disk checkout HEAD, or None if it cannot be resolved."""
try:
- from hermes_cli.build_info import get_code_identity
+ from hermes_cli.version_info import get_code_identity
sha = (get_code_identity(refresh=True) or {}).get("sha")
return str(sha) if sha else None
except Exception:
+ # get_code_identity raises only on a mispackaged stamp (missing
+ # updateMechanism / 'light' payload); a live git checkout is the
+ # correct fallback for dev trees.
return _capture_head_sha(["git"], _m().PROJECT_ROOT)
@@ -3294,34 +3390,15 @@ def _filter_non_gateway_concurrent_instances(
non_gateway.append((pid, name))
return non_gateway
-def _upgrade_pip_before_lazy_refresh(
- install_cmd_prefix: list[str],
- *,
- env: dict[str, str] | None = None,
-) -> None:
- """Upgrade pip before lazy-backend refreshes.
-
- Older pip (e.g. 24.0 on Python 3.11) can fail setuptools-backed source
- builds during lazy installs and leave a partially-written venv (#57828).
- Never raises.
- """
- try:
- _m()._run_package_only_install(
- install_cmd_prefix + ["install", "--upgrade", "pip"],
- env=env,
- )
- except subprocess.CalledProcessError as exc:
- logger.debug("pip upgrade before lazy refresh failed: %s", exc)
-
def _capture_active_lazy_features() -> list[str]:
- """Snapshot active lazy backends before a managed runtime is replaced."""
+ """Snapshot the venv's enabled extras before a managed runtime is replaced."""
try:
- from tools import lazy_deps
+ import pm
- return lazy_deps.active_features()
+ return pm.enabled_extras()
except Exception as exc:
- logger.debug("Could not snapshot active lazy features: %s", exc)
+ logger.debug("Could not snapshot enabled extras: %s", exc)
return []
@@ -3396,7 +3473,7 @@ def _restore_active_tool_dependencies(
failed: list[tuple[str, str]] = []
for name, install_args in missing:
try:
- _m()._run_package_only_install(
+ _m()._run_install_with_heartbeat(
install_cmd_prefix + ["install", *install_args, "--quiet"],
env=env,
)
@@ -3415,116 +3492,23 @@ def _restore_active_tool_dependencies(
print(f" ⚠ {name} failed to restore: {reason}")
-def _refresh_active_lazy_features(
- install_cmd_prefix: list[str] | None = None,
- *,
- env: dict[str, str] | None = None,
- features: list[str] | None = None,
-) -> bool:
- """Refresh lazy-installed backends after a code update.
-
- When pyproject.toml's ``[all]`` extra was slimmed down (May 2026), most
- optional backends moved to ``tools/lazy_deps.py`` and only install on
- first use. ``hermes update`` runs ``uv pip install -e .[all]`` which
- leaves those packages untouched — so if we bump a pin in
- :data:`LAZY_DEPS` (CVE response, transitive bug fix), users who already
- activated the backend keep the stale version forever.
-
- This function asks lazy_deps which features the user has previously
- activated and reinstalls them under the current pins. Features the
- user never enabled stay quiet — no churn for cold backends.
+def _refresh_active_lazy_features(features: list[str] | None = None) -> bool:
+ """Re-sync the venv's enabled extras against the (possibly new) uv.lock.
- Returns True when the venv is safe to use (refresh succeeded, or no
- active lazy backends, or post-failure import repair succeeded). Returns
- False when a failed lazy install left broken core imports that automatic
- repair could not fix (#57828).
-
- Never raises. A failure here must not block the rest of the update.
+ Extras live in the installed-state file and uv.lock owns every pin, so
+ a post-update refresh is one sync_venv() call: it re-installs exactly
+ the locked versions of everything enabled. Never raises.
"""
try:
- from tools import lazy_deps
- except Exception as exc:
- logger.debug("Lazy refresh skipped (import failed): %s", exc)
- return True
-
- if features is None:
- try:
- active = lazy_deps.active_features()
- except Exception as exc:
- logger.debug("Lazy refresh skipped (active_features failed): %s", exc)
- return True
- else:
- active = features
+ from pm.ensure import sync_venv
- if not active:
+ sync_venv(features, explicit=True)
return True
-
- print()
- print(f"→ Refreshing {len(active)} active lazy backend(s)...")
-
- unexpected_failure = False
- try:
- if features is None:
- results = lazy_deps.refresh_active_features(prompt=False)
- else:
- results = lazy_deps.restore_features(active)
except Exception as exc:
- # refresh_active_features is documented as never-raise, but defend
- # the update flow against future regressions.
- print(f" ⚠ Lazy refresh failed unexpectedly: {exc}")
- results = {}
- unexpected_failure = True
-
- refreshed = [f for f, s in results.items() if s in {"refreshed", "restored"}]
- current = [f for f, s in results.items() if s == "current"]
- failed = [(f, s) for f, s in results.items() if s.startswith("failed:")]
- skipped = [(f, s) for f, s in results.items() if s.startswith("skipped:")]
-
- if refreshed:
- print(f" ↑ {len(refreshed)} refreshed: {', '.join(refreshed)}")
- if current:
- print(f" ✓ {len(current)} already current")
- if skipped:
- # Most common reason: security.allow_lazy_installs=false. Show one
- # line so the user knows why; not an error.
- names = ", ".join(f for f, _ in skipped)
- reason = skipped[0][1].split(": ", 1)[-1]
- print(f" · {len(skipped)} skipped ({reason}): {names}")
-
- if not failed and not unexpected_failure:
- return True
-
- for feature, status in failed:
- reason = status.split(": ", 1)[-1]
- # Clip noisy pip stderr to keep update output legible.
- if len(reason) > 200:
- reason = reason[:200] + "..."
- print(f" ⚠ {feature} failed to refresh: {reason}")
-
- if install_cmd_prefix is None:
- print(" ⚠ Lazy refresh failed; rerun `hermes update` once resolved.")
+ print(f" ⚠ Extra re-sync failed: {exc}")
+ print(" Rerun `hermes update` (or `hermes pm install`) once resolved.")
return False
- # Immediate import-based recovery — metadata-only verifiers miss the case
- # where DISTRIBUTION-INFO remains but import files were wiped (#57828).
- # Unavailable probes are indeterminate, not healthy — keep the lazy marker.
- status = _m()._repair_venv_via_import_probes(install_cmd_prefix, env=env)
- if status == "repaired":
- print(
- " Lazy backend(s) keep their previous version until refresh succeeds."
- )
- return True
- if status == "healthy":
- print(
- " Lazy backend(s) keep their previous version; probed packages look intact."
- )
- print(" Rerun `hermes update` once the upstream issue is resolved.")
- return True
- if status == "indeterminate":
- print(
- " ⚠ Leaving `.lazy-refresh-incomplete` until import probes can confirm health."
- )
- return False
def _refresh_active_memory_provider_dependencies() -> None:
"""Refresh pip dependencies for the configured external memory provider.
@@ -3574,80 +3558,6 @@ def _refresh_active_memory_provider_dependencies() -> None:
except Exception as exc:
print(f" ⚠ {provider} dependencies failed to refresh: {exc}")
-def _is_android_python() -> bool:
- return _m().sys.platform == "android"
-
-def _install_psutil_android_compat(
- install_cmd_prefix: list[str],
- *,
- env: dict[str, str] | None = None,
-) -> None:
- """Install psutil on Android by patching upstream platform detection.
-
- psutil's setup currently gates Linux sources behind
- ``sys.platform.startswith('linux')``. On Termux Python reports
- ``sys.platform == 'android'``, so setup aborts with
- "platform android is not supported" despite compiling fine when using the
- Linux source path.
-
- We patch only the extracted build tree used for this install attempt;
- nothing is persisted in the repository.
-
- Stopgap: remove this once https://github.com/giampaolo/psutil/pull/2762
- merges and ships in a release. The standalone installer script uses the
- same shared helper and should be removed together.
- """
- import tempfile
- import urllib.request
- from hermes_cli.psutil_android import PSUTIL_URL, prepare_patched_psutil_sdist
-
- with tempfile.TemporaryDirectory() as tmp:
- tmp_path = Path(tmp)
- archive = tmp_path / "psutil.tar.gz"
- urllib.request.urlretrieve(PSUTIL_URL, archive)
- src_root = prepare_patched_psutil_sdist(archive, tmp_path)
-
- _m()._run_install_with_heartbeat(
- install_cmd_prefix + ["install", "--no-build-isolation", str(src_root)],
- env=env,
- )
-
-def _ensure_uv_for_termux(pip_cmd: list[str]) -> str | None:
- """Best-effort uv bootstrap on Termux for faster update installs.
-
- The normal path (``ensure_uv()`` in managed_uv) installs the managed
- standalone uv into ``$HERMES_HOME/bin/uv``, but on Termux the official
- installer may not work (glibc vs bionic). Prefer a uv already on PATH
- (e.g. ``pkg install uv``); only if there is none do we fall back to a
- wheel-only ``pip install uv`` so we never source-build the Rust crate.
- """
- from hermes_cli.managed_uv import resolve_uv
-
- existing = resolve_uv()
- if existing:
- return existing
- if not _m()._is_termux_env():
- return None
- # A Termux-packaged uv lands on PATH but not in the managed bin dir, so
- # resolve_uv() misses it. Use it before pip, which has no Android wheel and
- # would otherwise build uv from source on a low-memory device.
- system_uv = shutil.which("uv")
- if system_uv:
- return system_uv
- try:
- print(" → Termux detected: trying to install uv for faster dependency updates...")
- result = subprocess.run(
- pip_cmd + ["install", "uv", "--only-binary", ":all:"],
- cwd=_m().PROJECT_ROOT,
- check=False,
- )
- if result.returncode != 0:
- return None
- except Exception:
- pass
- # After pip install, check managed path first, then PATH
- return resolve_uv() or shutil.which("uv")
-
def _npm_manifest_paths() -> tuple[Path, ...]:
"""Manifests whose changes must defeat the update-skip.
@@ -3670,7 +3580,7 @@ def _npm_manifest_paths() -> tuple[Path, ...]:
root_pkg = _m().PROJECT_ROOT / "package.json"
paths = [_m().PROJECT_ROOT / "package-lock.json", root_pkg]
try:
- workspaces = json.loads(root_pkg.read_text(encoding="utf-8")).get(
+ workspaces = json.loads(root_pkg.read_text(encoding="utf-8-sig")).get(
"workspaces", []
)
if isinstance(workspaces, dict): # legacy {"packages": [...]} form
@@ -3723,7 +3633,7 @@ def _npm_lockfile_changed(hermes_root: Path) -> bool:
cache_file = hermes_root / f".npm_lock_hash_{cache_key}"
if not cache_file.exists():
return True
- return cache_file.read_text(encoding="utf-8").strip() != current
+ return cache_file.read_text(encoding="utf-8-sig").strip() != current
except OSError:
return True
@@ -4027,6 +3937,40 @@ def _cmd_update_check(branch: str = "main", *, branch_explicit: bool = False):
if swept:
print(f" (removed {len(swept)} aborted-fetch pack temp file(s))")
+ # Stable channel: if the caller did not ask for a branch, the question is
+ # "is there a newer tagged release?". The question is not "are there new
+ # commits on main?". Compare against the newest release tag and return.
+ if not branch_explicit:
+ if _stable_channel_active(None):
+ print("→ Update channel: stable (tagged releases)")
+ tag, tag_sha = _resolve_latest_release_tag(git_cmd, _m().PROJECT_ROOT)
+ if tag is None:
+ print("✗ No release tags found on origin. A check of the stable channel is not possible.")
+ print(" Switch channels with: hermes update --set-channel main")
+ sys.exit(1)
+ head_sha = _capture_head_sha(git_cmd, _m().PROJECT_ROOT)
+ # Newer releases possibly do not exist locally yet. "At the tag"
+ # is a SHA comparison. The merge-base check tells us whether HEAD
+ # contains the tag (HEAD is ahead of the release or at the release).
+ at_or_past_tag = False
+ if head_sha and tag_sha:
+ if head_sha == tag_sha:
+ at_or_past_tag = True
+ else:
+ contained = subprocess.run(
+ git_cmd + ["merge-base", "--is-ancestor", tag_sha, "HEAD"],
+ cwd=_m().PROJECT_ROOT,
+ capture_output=True,
+ text=True, encoding="utf-8", errors="replace",
+ )
+ at_or_past_tag = contained.returncode == 0
+ if at_or_past_tag:
+ print(f"✓ Up to date with the latest release ({tag}).")
+ else:
+ print(f"→ New release available: {tag}")
+ print(" Run `hermes update` to install it.")
+ return
+
# Fetch only the branch we compare against; prefer upstream as the canonical
# reference. A bare `git fetch <remote>` pulls every ref, and this repo has
# thousands of auto-generated branches, so scope the fetch to <branch>.
@@ -4230,7 +4174,7 @@ def _ensure_fhs_path_guard() -> None:
if not cfg.is_file():
continue
try:
- existing = cfg.read_text(errors="replace", encoding="utf-8")
+ existing = cfg.read_text(errors="replace", encoding="utf-8-sig")
except OSError:
continue
# Idempotency: skip if any uncommented PATH= line already references
@@ -4864,7 +4808,7 @@ def _dependency_sync_would_rewrite(dist_name: str) -> bool | None:
from packaging.version import Version
pyproject = _m().PROJECT_ROOT / "pyproject.toml"
- data = tomllib.loads(pyproject.read_text(encoding="utf-8"))
+ data = tomllib.loads(pyproject.read_text(encoding="utf-8-sig"))
project = data.get("project") or {}
req_strings: list[str] = list(project.get("dependencies") or [])
for extra_reqs in (project.get("optional-dependencies") or {}).values():
@@ -7651,9 +7595,31 @@ def _cmd_update_impl(args, gateway_mode: bool):
if swept:
print(" (removed %d aborted-fetch pack temp file(s))" % len(swept))
+ # target_ref is the reference that we count against, fast-forward to,
+ # and reset to. On the main channel it is origin/<branch>. That is the
+ # historical behavior. On the stable channel it is the commit of the
+ # newest release tag. The current branch pointer fast-forwards to the
+ # release. Thus the checkout keeps its branch shape (no detached HEAD).
+ # The next stable update then fast-forward merges to the next tag.
+ target_ref = f"origin/{branch}"
+ stable_tag = None
+ if _stable_channel_active(args):
+ print("→ Update channel: stable (tagged releases)")
+ stable_tag, _stable_tag_sha = _resolve_latest_release_tag(
+ git_cmd, _m().PROJECT_ROOT
+ )
+ if stable_tag is None:
+ print("✗ No release tags found on origin. An update on the stable channel is not possible.")
+ print(" Switch channels with: hermes update --set-channel main")
+ _m()._resume_windows_gateways_after_update(_windows_gateway_resume)
+ sys.exit(1)
+ print(f"→ Latest release: {stable_tag}")
+ target_ref = stable_tag
+
print("→ Fetching updates...")
+ fetch_target = ["tag", stable_tag] if stable_tag else [branch]
fetch_result = subprocess.run(
- git_cmd + ["fetch", "origin", branch],
+ git_cmd + ["fetch", "origin", *fetch_target],
cwd=_m().PROJECT_ROOT,
capture_output=True,
text=True, encoding="utf-8", errors="replace",
@@ -7701,7 +7667,10 @@ def _cmd_update_impl(args, gateway_mode: bool):
# stale tree.
parked_branch_switched = False
in_place_update = False
- if current_branch != branch and current_branch != "HEAD":
+ # Stable channel: the checkout does NOT switch branches. The current
+ # branch pointer fast-forwards (or merges) to the release tag's
+ # commit, so the parked-branch machinery below is main-channel only.
+ if stable_tag is None and current_branch != branch and current_branch != "HEAD":
switch_safe, switch_block_reason = _m()._assess_parked_branch_switch(
git_cmd, _m().PROJECT_ROOT, current_branch, branch
)
@@ -7769,7 +7738,7 @@ def _cmd_update_impl(args, gateway_mode: bool):
f"(fully merged) — switching back to {branch}..."
)
- if not in_place_update and current_branch != branch:
+ if stable_tag is None and not in_place_update and current_branch != branch:
if current_branch == "HEAD":
print(
f" ⚠ Currently on detached HEAD — switching to {branch} "
@@ -7825,7 +7794,7 @@ def _cmd_update_impl(args, gateway_mode: bool):
# 0), so keep it, but treat the shallow NUMBER as unknown and recover
# the real one via the GitHub compare API when possible.
result = subprocess.run(
- git_cmd + ["rev-list", f"HEAD..origin/{branch}", "--count"],
+ git_cmd + ["rev-list", f"HEAD..{target_ref}", "--count"],
cwd=_m().PROJECT_ROOT,
capture_output=True,
text=True, encoding="utf-8", errors="replace",
@@ -7851,7 +7820,7 @@ def _cmd_update_impl(args, gateway_mode: bool):
text=True, encoding="utf-8", errors="replace",
).stdout.strip()
target_sha = subprocess.run(
- git_cmd + ["rev-parse", f"origin/{branch}"],
+ git_cmd + ["rev-parse", target_ref],
cwd=_m().PROJECT_ROOT, capture_output=True,
text=True, encoding="utf-8", errors="replace",
).stdout.strip()
@@ -7928,19 +7897,16 @@ def _cmd_update_impl(args, gateway_mode: bool):
check=False,
)
- # "No new commits" does not mean the managed interpreter is safe.
- # uv can retain the same CPython patch while python-build-standalone
- # refreshes the embedded SQLite underneath it. Keep the existing
- # update-boundary hook active on this retry path too.
- from hermes_cli.managed_uv import ensure_uv, update_managed_uv
-
- runtime_repairs = []
- update_managed_uv(repair_observer=runtime_repairs.append)
- ensure_uv(repair_observer=runtime_repairs.append)
- runtime_repaired = next(
- (result for result in runtime_repairs if result.repaired),
- None,
- )
+ # "No new commits" does not mean the venv is safe: pm owns the uv
+ # pin now — a pin bump realizes a NEW entry on the next ensure.
+ # The update command is the one caller that must SEE realization
+ # failures, so use the raising API, not the None-swallowing uv().
+ import pm
+
+ try:
+ pm.ensure("uv")
+ except pm.InstallError as e:
+ print(f"⚠ Managed uv unavailable: {e}")
# A current checkout does NOT imply a healthy install: a previous
# dependency sync may have failed partway (classic on Windows,
@@ -7968,9 +7934,9 @@ def _cmd_update_impl(args, gateway_mode: bool):
# too — same mapped-extension hazard as the update sync.
_m()._abort_dependency_sync_if_self_locked(_windows_gateway_resume)
_write_update_incomplete_marker()
- from hermes_cli.managed_uv import ensure_uv
+ import pm
- repair_uv = ensure_uv()
+ repair_uv, repair_env = pm.uv(venv=_m().PROJECT_ROOT / "venv")
# A managed install whose venv is gone entirely (interrupted
# repair after the old venv was moved aside) needs the venv
# recreated before dependencies can be installed into it.
@@ -7986,34 +7952,17 @@ def _cmd_update_impl(args, gateway_mode: bool):
cwd=_m().PROJECT_ROOT,
check=False,
)
+ try:
+ pm.sync_venv(["all"] + list(active_lazy_features or []), explicit=True)
+ except pm.InstallError as _sync_err:
+ print(f" ✗ {_sync_err}")
if repair_uv:
- # Isolated from third-party UV env vars (#83914), same as
- # the main-path and git-path dependency syncs.
- from hermes_cli.managed_uv import managed_python_env
-
- repair_env = managed_python_env()
- repair_env["VIRTUAL_ENV"] = str(_m().PROJECT_ROOT / "venv")
- _m()._install_python_dependencies_with_optional_fallback(
- [repair_uv, "pip"], env=repair_env, group="all"
- )
- _m()._refresh_active_lazy_features(
- [repair_uv, "pip"],
- env=repair_env,
- features=active_lazy_features,
- )
_m()._restore_active_tool_dependencies(
active_tool_dependencies,
[repair_uv, "pip"],
env=repair_env,
)
else:
- _m()._install_python_dependencies_with_optional_fallback(
- [sys.executable, "-m", "pip"], group="all"
- )
- _m()._refresh_active_lazy_features(
- [sys.executable, "-m", "pip"],
- features=active_lazy_features,
- )
_m()._restore_active_tool_dependencies(
active_tool_dependencies,
[sys.executable, "-m", "pip"],
@@ -8043,16 +7992,6 @@ def _cmd_update_impl(args, gateway_mode: bool):
else "✓ Up to date with your fork (official repo not checked)."
),
)
- if runtime_repaired is not None and not _m()._is_windows():
- print()
- print(
- "⚠ Restart required to finish the managed Python runtime repair."
- )
- print(
- " Any running Hermes gateways, Desktop backends, or other "
- "long-lived processes still use the previous runtime."
- )
- print(" Restart each of them to pick up the repaired runtime.")
_m()._resume_windows_gateways_after_update(_windows_gateway_resume)
# Git is current, but a prior pull may still owe the fleet a
# restart (#95294). Catch up even on the "Already up to date"
@@ -8084,7 +8023,7 @@ def _cmd_update_impl(args, gateway_mode: bool):
# `pull --ff-only origin <branch>` given the fresh tracking ref;
# the divergence fallback below is unchanged.
pull_result = subprocess.run(
- git_cmd + ["merge", "--ff-only", f"origin/{branch}"],
+ git_cmd + ["merge", "--ff-only", target_ref],
cwd=_m().PROJECT_ROOT,
capture_output=True,
text=True, encoding="utf-8", errors="replace",
@@ -8342,84 +8281,25 @@ def _cmd_update_impl(args, gateway_mode: bool):
# via ``_recover_from_interrupted_install``. Cleared after the core
# ``.[all]`` install completes — lazy refresh uses a separate marker.
_write_update_incomplete_marker()
- deps_current = _editable_install_is_current(
- git_cmd, _m().PROJECT_ROOT, pre_pull_sha
- )
- if deps_current:
- print("→ Python dependencies unchanged — skipping reinstall")
- else:
- print("→ Updating Python dependencies...")
- from hermes_cli.managed_uv import ensure_uv, update_managed_uv
-
- # Keep managed uv current — runs `uv self update` if we already have one.
- update_managed_uv()
-
- uv_bin = ensure_uv()
+ print("→ Syncing Python dependencies...")
+ import pm
+ try:
+ pm.sync_venv(["all"], explicit=True)
+ deps_synced = True
+ except pm.InstallError as _sync_err:
+ deps_synced = False
+ print(f" ✗ {_sync_err}")
+ print(" Re-run `hermes update` (or `hermes pm install`) once resolved.")
+
+ uv_bin, uv_env = pm.uv(venv=_m().PROJECT_ROOT / "venv")
pip_cmd = [sys.executable, "-m", "pip"]
- if not uv_bin:
- uv_bin = _ensure_uv_for_termux(pip_cmd)
- install_group = "all"
-
- if uv_bin:
- # Use official managed_python_env() isolation so third-party
- # UV_PYTHON_INSTALL_DIR (e.g. WorkBuddy) cannot hijack uv; then
- # point VIRTUAL_ENV at this install's venv.
- from hermes_cli.managed_uv import managed_python_env
-
- uv_env = managed_python_env()
- uv_env["VIRTUAL_ENV"] = str(_m().PROJECT_ROOT / "venv")
- if _m()._is_termux_env(uv_env):
- uv_env.pop("PYTHONPATH", None)
- uv_env.pop("PYTHONHOME", None)
- install_group = "termux-all"
- print(" → Termux detected: using uv + curated termux-all optional profile...")
- if not deps_current:
- if _m()._is_termux_env(uv_env) and _is_android_python():
- print(" → Termux/Android detected: prebuilding psutil with Linux source path compatibility...")
- _install_psutil_android_compat([uv_bin, "pip"], env=uv_env)
- _m()._install_python_dependencies_with_optional_fallback(
- [uv_bin, "pip"], env=uv_env, group=install_group
- )
- else:
- # Use sys.executable to explicitly call the venv's pip module,
- # avoiding PEP 668 'externally-managed-environment' errors on Debian/Ubuntu.
- # Some environments lose pip inside the venv; bootstrap it back with
- # ensurepip before trying the editable install.
- pip_cmd = [sys.executable, "-m", "pip"]
- try:
- subprocess.run(
- pip_cmd + ["--version"],
- cwd=_m().PROJECT_ROOT,
- check=True,
- capture_output=True,
- )
- except subprocess.CalledProcessError:
- subprocess.run(
- [sys.executable, "-m", "ensurepip", "--upgrade", "--default-pip"],
- cwd=_m().PROJECT_ROOT,
- check=True,
- )
- if _m()._is_termux_env():
- install_group = "termux-all"
- print(" → Termux detected: using curated termux-all optional profile...")
- if not deps_current:
- if _m()._is_termux_env() and _is_android_python():
- print(" → Termux/Android detected: prebuilding psutil with Linux source path compatibility...")
- _install_psutil_android_compat(pip_cmd)
- _m()._install_python_dependencies_with_optional_fallback(pip_cmd, group=install_group)
-
install_prefix = [uv_bin, "pip"] if uv_bin else pip_cmd
lazy_env = uv_env if uv_bin else None
- if deps_current:
- # The verification normally runs inside the install we just
- # skipped. Run it here so a wrong skip self-heals into a real
- # install (both verifiers reinstall what they find missing)
- # instead of leaving a venv nobody checked.
- _m()._verify_core_dependencies_installed(
- install_prefix, env=lazy_env, group=install_group
- )
+ if deps_synced:
+ # Console-script shims aren't covered by the sync stamp — verify
+ # them so a venv whose Scripts/ was clobbered self-heals.
_m()._verify_console_scripts_installed(install_prefix, env=lazy_env)
# Core ``.[all]`` install finished. Clear the generic core breadcrumb
@@ -8431,7 +8311,7 @@ def _cmd_update_impl(args, gateway_mode: bool):
# The update process is still the old Python interpreter process. Run
# one final cache/module refresh immediately before lazy backend
# refresh, which imports newly-pulled modules that may depend on fresh
- # symbols in hermes_constants or lazy_deps. The dependency install
+ # symbols in hermes_constants or pm. The dependency install
# above may also have regenerated bytecode from build-cache copies —
# this second sweep catches those stragglers (#60242, #65240).
removed = _m()._clear_bytecode_cache(_m().PROJECT_ROOT)
@@ -8443,18 +8323,8 @@ def _cmd_update_impl(args, gateway_mode: bool):
_m()._refresh_bootstrap_cache_scripts(branch)
_m()._reload_updated_runtime_modules()
- # Upgrade pip before lazy refreshes — stale pip can fail source builds
- # and leave partially-written packages (#57828).
_write_lazy_refresh_incomplete_marker()
- _m()._upgrade_pip_before_lazy_refresh(install_prefix, env=lazy_env)
-
- # Lazy refresh can corrupt the venv when a backend install fails.
- # Clear the lazy marker only when refresh/repair is confirmed healthy.
- lazy_ok = _m()._refresh_active_lazy_features(
- install_prefix,
- env=lazy_env,
- features=active_lazy_features,
- )
+ lazy_ok = _m()._refresh_active_lazy_features(active_lazy_features)
if lazy_ok:
_m()._clear_lazy_refresh_incomplete_marker()
else:
diff --git a/hermes_cli/update_inventory.py b/hermes_cli/update_inventory.py
index 9be2dc81089..88e7ce8aa35 100644
--- a/hermes_cli/update_inventory.py
+++ b/hermes_cli/update_inventory.py
@@ -185,7 +185,7 @@ def collect_runtime_inventory() -> UpdatePlan:
# --- expected code identity (pre-pull) --------------------------------
try:
- from hermes_cli.build_info import get_code_identity
+ from hermes_cli.version_info import get_code_identity
identity = get_code_identity(refresh=True)
plan.expected_sha = identity.get("sha")
diff --git a/hermes_cli/update_receipt.py b/hermes_cli/update_receipt.py
index f3df91da406..8b30c7866f2 100644
--- a/hermes_cli/update_receipt.py
+++ b/hermes_cli/update_receipt.py
@@ -21,9 +21,9 @@ break an update (every public entry point is exception-swallowing):
become a loud, actionable report instead of a latent state.
Deployment-kind awareness (docker/image-managed installs) rides on
-``hermes_cli.build_info.get_code_identity()``: an image build reports
-``source="build-file"`` and the receipt records that the install is not
-in-place updatable.
+``hermes_cli.version_info.get_code_identity()``: a packaged build reports
+its install-stamp provenance (``source="docker"``/``"nix"``/…) and the
+receipt records that the install is not in-place updatable.
"""
from __future__ import annotations
@@ -72,7 +72,7 @@ class UpdateReceipt:
"fleet": [],
}
try:
- from hermes_cli.build_info import get_code_identity
+ from hermes_cli.version_info import get_code_identity
self.data["pre_update"] = get_code_identity()
except Exception:
@@ -139,7 +139,7 @@ class UpdateReceipt:
self.data["outcome"] = outcome
self.data["finished_at"] = _utc_now_iso()
try:
- from hermes_cli.build_info import get_code_identity
+ from hermes_cli.version_info import get_code_identity
self.data["post_update"] = get_code_identity(refresh=True)
except Exception:
@@ -290,7 +290,7 @@ def read_latest_receipt() -> Optional[dict[str, Any]]:
path = _receipt_dir() / "latest.json"
if not path.is_file():
return None
- payload = json.loads(path.read_text(encoding="utf-8"))
+ payload = json.loads(path.read_text(encoding="utf-8-sig"))
return payload if isinstance(payload, dict) else None
except Exception:
return None
@@ -336,7 +336,7 @@ def collect_fleet_versions(
_pre_restart = {int(p) for p in (pre_restart_pids or []) if isinstance(p, int)}
results: list[dict[str, Any]] = []
try:
- from hermes_cli.build_info import get_code_identity
+ from hermes_cli.version_info import get_code_identity
expected_sha = (get_code_identity(refresh=True) or {}).get("sha")
except Exception:
diff --git a/hermes_cli/venv_sync.py b/hermes_cli/venv_sync.py
new file mode 100644
index 00000000000..9f1877cc680
--- /dev/null
+++ b/hermes_cli/venv_sync.py
@@ -0,0 +1,283 @@
+"""Sync the install's Python environment to its tree — and nothing else.
+
+One of the two separately-invocable, stdlib-only-at-import halves of
+"make this install runnable":
+
+* ``pm`` — pinned tools and the venv ledger (facts.json), shape-universal.
+* THIS module — the pre-venv entry point, whose meaning depends on the
+ install shape:
+
+ - **checkout** (git clone + venv): make the venv match
+ ``pyproject.toml``/``uv.lock``. For the tree this module runs FROM,
+ the work is delegated to :func:`pm.sync_venv` — pm owns the extras
+ ledger and records the result in facts.json, so update and fresh
+ clone converge on one authority. For a foreign ``--project-root``
+ (installer bootstrapping a clone it has not exec'd into yet), uv is
+ driven directly with pm's pinned binary and sanitized env.
+ - **sealed** (desktop bundle, nix, docker): the interpreter tree is a
+ build artifact — syncing it is not possible and not meaningful.
+ Exit 0 with ``{"state": "sealed"}``, cleanly.
+
+Stdlib-only at import is a hard contract: this runs on freshly-cloned
+trees where the venv does not exist yet, and after tree swaps where the
+venv is not trustworthy — exactly the moments a third-party import
+would explode. ``pm`` is itself stdlib-only first-party code, and it is
+imported lazily, only once a sync is actually due.
+
+Why the sync is not just "run uv every time": ``uv sync`` on an
+already-current venv still costs ~1-2s of resolver work, and the boot
+path calls this through ``post_update``. The lockfile digest recorded in
+``<runtime dir>/cache/venv-sync.json`` makes currency a file read.
+
+Invocation:
+
+ python -m hermes_cli.venv_sync # sync if stale
+ python -m hermes_cli.venv_sync --check # report, change nothing
+ python -m hermes_cli.venv_sync --json # machine-readable
+
+Exit 0: current/synced/sealed. Exit 1: a sync was needed and failed.
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+STAMP_NAME = "venv-sync.json"
+STAMP_SCHEMA = 1
+
+
+def _project_root() -> Path:
+ return Path(__file__).resolve().parents[1]
+
+
+def _runtime_dir(project_root: Path) -> Path:
+ """Where per-install runtime state lives for ``project_root``.
+
+ Mirrors pm.paths.store_root()'s ladder (HERMES_RUNTIME_DIR, then the
+ install stamp's runtimeDir) but stays stdlib-local and falls back to
+ ``<root>/.hermes-runtime`` instead of the machine-global tool store:
+ the venv-sync stamp is per-install, and two checkouts sharing the
+ default store must not share a currency claim.
+ """
+ env = os.environ.get("HERMES_RUNTIME_DIR")
+ if env:
+ return Path(env)
+ try:
+ data = json.loads(
+ (project_root / "install-stamp.json").read_text(encoding="utf-8-sig")
+ )
+ stamped = data.get("runtimeDir") if isinstance(data, dict) else None
+ if stamped:
+ return Path(stamped)
+ except (OSError, ValueError):
+ pass
+ return project_root / ".hermes-runtime"
+
+
+def _stamp_path(project_root: Path) -> Path:
+ return _runtime_dir(project_root) / "cache" / STAMP_NAME
+
+
+def _lock_digest(project_root: Path) -> str | None:
+ """Content hash of what a sync would consume.
+
+ pyproject.toml is part of the key: an extras edit without a lock
+ bump must re-sync (same reasoning as pm's venv expected_stamp keying
+ on uv.lock — pyproject rides along here because this module cannot
+ assume pm's ledger exists yet).
+ """
+ h = hashlib.sha256()
+ found = False
+ for name in ("uv.lock", "pyproject.toml"):
+ try:
+ h.update((project_root / name).read_bytes())
+ found = True
+ except OSError:
+ h.update(b"-")
+ return h.hexdigest() if found else None
+
+
+def _is_sealed(project_root: Path) -> bool:
+ """A sealed tree ships its interpreter; only checkouts own a venv.
+
+ The stamp file is the authority (hermes_cli.steward reads the same
+ file; restated here to keep the bare import stdlib-and-local). A
+ tree with BOTH a stamp and .git is a dev tree — treat as checkout.
+
+ A stamp without a valid ``updateMechanism`` is a build-lane bug and
+ must not be silently read as "not sealed" (that is exactly the
+ misclassification that made sealed trees look updatable) — same
+ guard as hermes_cli.version_info._stamp_version_info.
+ """
+ if (project_root / ".git").exists():
+ return False
+ try:
+ data = json.loads(
+ (project_root / "install-stamp.json").read_text(encoding="utf-8-sig")
+ )
+ except (OSError, ValueError):
+ return False
+ if not (isinstance(data, dict) and bool(data)):
+ return False
+ if data.get("updateMechanism") not in ("self", "electron-updater", "external"):
+ raise RuntimeError(
+ f"install-stamp.json at {project_root} is missing a valid "
+ "'updateMechanism' (one of self, electron-updater, external). The "
+ "build lane that wrote this stamp must pass --update-mechanism to "
+ "scripts/write_install_stamp.py."
+ )
+ return True
+
+
+def _managed_uv() -> tuple:
+ """(uv binary path, sanitized env) from pm, or (None, None).
+
+ ``pm.ensure.uv`` IS the resolution: facts from the store the pins
+ point at, env sanitized against interpreter hijack (#83914). pm is
+ stdlib-only first-party code, so the lazy import costs nothing and
+ keeps this module's bare-import surface stdlib-pure.
+ """
+ try:
+ from pm.ensure import uv as pm_uv
+
+ uv_bin, env = pm_uv(realize=True)
+ except Exception:
+ return None, None
+ return uv_bin, env
+
+
+def read_stamp(project_root: Path) -> dict:
+ try:
+ data = json.loads(_stamp_path(project_root).read_text(encoding="utf-8-sig"))
+ return data if isinstance(data, dict) else {}
+ except (OSError, ValueError):
+ return {}
+
+
+def write_stamp(project_root: Path, digest: str) -> None:
+ path = _stamp_path(project_root)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ tmp = path.with_suffix(".tmp")
+ tmp.write_text(
+ json.dumps(
+ {
+ "schemaVersion": STAMP_SCHEMA,
+ "lockDigest": digest,
+ "python": sys.version.split()[0],
+ }
+ ),
+ encoding="utf-8",
+ )
+ os.replace(tmp, path)
+
+
+def _pm_sync(root: Path) -> dict:
+ """Bring ``root``'s venv current. pm's ledger when root IS this tree,
+ a direct pinned-uv drive when it is a foreign clone.
+
+ Returns ``{"ok": bool, "detail": str | None}``.
+ """
+ try:
+ from pm import paths as pm_paths
+
+ own_tree = Path(pm_paths.repo_root()).resolve() == root.resolve()
+ except Exception:
+ own_tree = False
+
+ if own_tree:
+ # pm owns the extras ledger; explicit=True because reaching a
+ # stale-venv verdict here IS the deliberate remedy (installer /
+ # post-update path), the same trust `hermes update` carries.
+ try:
+ from pm import sync_venv
+
+ sync_venv(explicit=True)
+ except Exception as exc:
+ return {"ok": False, "detail": str(exc)}
+ return {"ok": True, "detail": None}
+
+ uv, env = _managed_uv()
+ if uv is None:
+ return {
+ "ok": False,
+ "detail": "managed uv not provisioned (run `hermes pm install`)",
+ }
+ env = dict(env)
+ env["UV_PROJECT_ENVIRONMENT"] = str(root / "venv")
+ # A stale VIRTUAL_ENV from the calling shell would win over the
+ # project environment and sync the WRONG venv.
+ env.pop("VIRTUAL_ENV", None)
+ cmd = [str(uv), "sync"]
+ if (root / "uv.lock").is_file():
+ cmd.append("--frozen")
+ proc = subprocess.run(cmd, cwd=str(root), env=env)
+ if proc.returncode != 0:
+ return {"ok": False, "detail": f"uv sync exited {proc.returncode}"}
+ return {"ok": True, "detail": None}
+
+
+def sync(project_root: Path | None = None, *, check: bool = False) -> dict:
+ """Bring the venv up to the tree. Returns a state dict, never raises.
+
+ States: ``sealed`` (nothing to sync, by design), ``current`` (stamp
+ matches the lockfile digest), ``synced`` (the sync ran and the stamp
+ moved), ``failed`` (the sync did not converge — detail says why),
+ ``would-sync`` (check mode found staleness and stopped).
+ """
+ root = Path(project_root) if project_root else _project_root()
+
+ if _is_sealed(root):
+ return {"state": "sealed", "ok": True}
+
+ digest = _lock_digest(root)
+ if digest is None:
+ return {
+ "state": "failed",
+ "ok": False,
+ "detail": f"no pyproject.toml or uv.lock under {root}",
+ }
+
+ if read_stamp(root).get("lockDigest") == digest:
+ return {"state": "current", "ok": True}
+
+ if check:
+ return {"state": "would-sync", "ok": True}
+
+ result = _pm_sync(root)
+ if not result["ok"]:
+ # No stamp write: the next run must try again, not skip.
+ return {"state": "failed", "ok": False, "detail": result["detail"]}
+
+ write_stamp(root, digest)
+ return {"state": "synced", "ok": True}
+
+
+def main(argv: list | None = None) -> int:
+ parser = argparse.ArgumentParser(prog="hermes_cli.venv_sync")
+ parser.add_argument("--project-root", default=None)
+ parser.add_argument(
+ "--check", action="store_true", help="report; change nothing"
+ )
+ parser.add_argument("--json", action="store_true")
+ args = parser.parse_args(argv)
+
+ result = sync(
+ Path(args.project_root) if args.project_root else None, check=args.check
+ )
+
+ if args.json:
+ print(json.dumps(result))
+ else:
+ detail = f" ({result['detail']})" if result.get("detail") else ""
+ print(f"venv sync: {result['state']}{detail}")
+ return 0 if result["ok"] else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/hermes_state.py b/hermes_state.py
index 3da58aa600d..0962d6f2f8d 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -1435,6 +1435,8 @@ def _wal_reset_repair_hint() -> str:
cmd = recommended_update_command_for_method(method)
if method in {"git", "unknown"}:
return f"Hermes-managed installs can repair the embedded runtime with `{cmd}`"
+ if method == "source":
+ return "source checkouts can repair the runtime by re-running their venv setup"
if method == "docker":
return f"update the container image with `{cmd}`"
# nix/nixos
diff --git a/nix/hermes-agent.nix b/nix/hermes-agent.nix
index 2055c9cd6c1..a8f8fe2465a 100644
--- a/nix/hermes-agent.nix
+++ b/nix/hermes-agent.nix
@@ -33,11 +33,40 @@
# check for updates without needing a local .git directory. Null for
# impure / dirty builds where flakes can't determine a rev.
rev ? null,
+ revCount ? null,
+ branch ? null,
+ dirty ? false,
+ lastModified ? null,
# Overridable parameters
extraPythonPackages ? [ ],
extraDependencyGroups ? [ ],
}:
let
+ version = (fromTOML (builtins.readFile ../pyproject.toml)).project.version;
+ versionModule = builtins.readFile ../hermes_cli/__init__.py;
+ releaseRevCountLine = lib.findFirst (line: lib.hasPrefix "__release_rev_count__" line) null (
+ lib.splitString "\n" versionModule
+ );
+ releaseRevCountMatch =
+ if releaseRevCountLine == null then null else builtins.match ".*= ([0-9]+)" releaseRevCountLine;
+ releaseRevCount =
+ if releaseRevCountMatch == null then null else builtins.fromJSON (builtins.elemAt releaseRevCountMatch 0);
+
+ # Install stamp values — written to install-stamp.json so the Python
+ # runtime (CLI, TUI) reads one file instead of env vars or .git probes.
+ stampDistance =
+ if revCount != null && releaseRevCount != null then
+ lib.trivial.max 0 (revCount - releaseRevCount)
+ else
+ null;
+ stampDisplayVersion =
+ if stampDistance != null && stampDistance > 0 then
+ "${version}+${toString stampDistance}"
+ else if dirty && stampDistance == null then
+ "${version}+?"
+ else
+ version;
+
mkHermesVenv =
extraDependencyGroups:
callPackage ./python.nix {
@@ -160,7 +189,7 @@ let
in
stdenv.mkDerivation (finalAttrs: {
pname = "hermes-agent";
- version = (fromTOML (builtins.readFile ../pyproject.toml)).project.version;
+ inherit version;
dontUnpack = true;
dontBuild = true;
@@ -181,6 +210,15 @@ stdenv.mkDerivation (finalAttrs: {
ln -s ${hermesWeb} $out/share/hermes-agent/web_dist
ln -s ${hermesTui}/lib/hermes-tui $out/ui-tui
+ # Write the canonical install stamp. version_info.py resolves it
+ # through HERMES_INSTALL_ROOT (set by the wrapper below) — one file,
+ # one resolution path for the Python runtime (CLI, TUI), no .git
+ # probing and no stamp-specific env channel. updateMechanism is
+ # `external`: the nix store path is replaced by nix, never by hermes.
+ cat > $out/share/hermes-agent/install-stamp.json <<STAMP
+ {"schemaVersion":2,"commit":${builtins.toJSON rev},"commitDate":${builtins.toJSON lastModified},"branch":${builtins.toJSON branch},"baseVersion":"${version}","displayVersion":"${stampDisplayVersion}","distance":${builtins.toJSON stampDistance},"dirty":${if dirty then "true" else "false"},"source":"nix","distribution":"nix","updateMechanism":"external"}
+ STAMP
+
${lib.concatMapStringsSep "\n"
(name: ''
makeWrapper ${hermesVenv}/bin/${name} $out/bin/${name} \
@@ -194,13 +232,17 @@ stdenv.mkDerivation (finalAttrs: {
--set HERMES_TUI_DIR $out/ui-tui \
--set-default HERMES_BIN $out/bin/hermes \
--set HERMES_PYTHON ${hermesVenv}/bin/python3 \
- --set HERMES_NODE ${lib.getExe hermesNpmLib.nodejs}${
+ --set HERMES_NODE ${lib.getExe hermesNpmLib.nodejs} \
+ --set HERMES_INSTALL_ROOT $out/share/hermes-agent${
# Fold the line continuation INTO the optionalString: a bare
# `\` on the line above an empty expansion would dangle onto a
# blank line, ending the makeWrapper command early and running
# the next flag as its own shell command (`--suffix: command
# not found`). Only reproduces when rev == null (dirty trees).
- lib.optionalString (rev != null) " \\\n --set HERMES_REVISION ${rev}"
+ # Only embed clean revs — a dirtyRev-derived rev is the parent
+ # of uncommitted work, and the banner's update check would
+ # compare against upstream as if the tree were at that commit.
+ lib.optionalString (rev != null && !dirty) " \\\n --set HERMES_REVISION ${rev}"
}${
lib.optionalString (
extraPythonPackages != [ ]
diff --git a/nix/packages.nix b/nix/packages.nix
index a496f73a3ee..9fdaf6061e5 100644
--- a/nix/packages.nix
+++ b/nix/packages.nix
@@ -12,12 +12,39 @@
sandbox = pkgs.callPackage ./sandbox.nix { };
+ # pm/lock.json translated into derivations — one per tool package
+ # with an artifact for this system. The lockfile carries resolved
+ # urls + hashes, so nix consumes it as pure data. callPackage adds
+ # .override/.overrideDerivation to the returned SET; keep only the
+ # real derivations.
+ pmPackages = lib.filterAttrs (_: lib.isDerivation) (
+ pkgs.callPackage ./pm-packages.nix { }
+ );
+
+ dirtyRevision = inputs.self.dirtyRev or null;
+ # inputs.self.sourceInfo is a string (store path) in current Nix, not a
+ # record. The metadata fields are available as top-level attributes on
+ # inputs.self directly. A flake URL's requested ref is intentionally not
+ # exposed as self.ref after Nix resolves it to an immutable source, so
+ # branch is normally null for remote flakes. Preserve null rather than
+ # inventing a sentinel that could be a real branch name.
+ rev =
+ inputs.self.rev or (if dirtyRevision != null then builtins.substring 0 40 dirtyRevision else null);
+ revCount = inputs.self.revCount or null;
+ rawRef = inputs.self.ref or null;
+ branch = if rawRef != null then builtins.replaceStrings [ "refs/heads/" ] [ "" ] rawRef else null;
+ dirty = dirtyRevision != null;
+ lastModified = inputs.self.lastModified or null;
minimal = pkgs.callPackage ./hermes-agent.nix {
inherit (inputs) uv2nix pyproject-nix pyproject-build-systems;
npm-lockfile-fix = inputs'.npm-lockfile-fix.packages.default;
- # Only embed clean revs — dirtyRev doesn't represent any upstream
- # commit, so comparing it would always claim "update available".
- rev = inputs.self.rev or null;
+ inherit
+ rev
+ revCount
+ branch
+ dirty
+ lastModified
+ ;
};
# All platform-portable optional integrations pre-built.
@@ -70,6 +97,9 @@
desktop = full.hermesDesktop;
update-npm-lockfile = full.hermesNpmLib.updateNpmLockfile;
- };
+ }
+ # Every pm lockfile tool as its own installable derivation:
+ # `nix build .#pm-ripgrep`, `nix build .#pm-gh`, ...
+ // lib.mapAttrs' (name: drv: lib.nameValuePair "pm-${name}" drv) pmPackages;
};
}
diff --git a/package-lock.json b/package-lock.json
index 5e1f45ced26..d7693d1c795 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -159,7 +159,7 @@
"concurrently": "10.0.4",
"cross-env": "10.1.0",
"electron": "40.10.2",
- "electron-builder": "26.15.3",
+ "electron-builder": "27.0.0-alpha.6",
"esbuild": "0.28.1",
"jsdom": "29.1.1",
"prettier": "3.9.5",
@@ -1670,225 +1670,161 @@
}
},
"node_modules/@electron/asar": {
- "version": "3.4.1",
- "resolved": "https://registry.npmjs.org/@electron/asar/-/asar-3.4.1.tgz",
- "integrity": "sha512-i4/rNPRS84t0vSRa2HorerGRXWyF4vThfHesw0dmcWHp+cspK743UanA0suA5Q5y8kzY2y6YKrvbIUn69BCAiA==",
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/@electron/asar/-/asar-4.1.1.tgz",
+ "integrity": "sha512-grbomy1TPEauyu+N4UdRQqSjOhsm0ZoTbprLpvJWQGYeEIMVBwSPV3Rv3E3EfqU5iFSufd/k+2KZvTDbgfesnw==",
"dev": true,
"license": "MIT",
"dependencies": {
- "commander": "^5.0.0",
- "glob": "^7.1.6",
- "minimatch": "^3.0.4"
+ "commander": "^13.1.0",
+ "glob": "^13.0.2",
+ "minimatch": "^10.0.1",
+ "plist": "^3.1.0"
},
"bin": {
- "asar": "bin/asar.js"
+ "asar": "bin/asar.mjs"
},
"engines": {
- "node": ">=10.12.0"
+ "node": ">=22.12.0"
}
},
- "node_modules/@electron/asar/node_modules/minimatch": {
- "version": "3.1.5",
- "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",
- "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",
+ "node_modules/@electron/asar/node_modules/glob": {
+ "version": "13.0.6",
+ "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz",
+ "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==",
"dev": true,
- "license": "ISC",
+ "license": "BlueOak-1.0.0",
"dependencies": {
- "brace-expansion": "^1.1.7"
+ "minimatch": "^10.2.2",
+ "minipass": "^7.1.3",
+ "path-scurry": "^2.0.2"
},
"engines": {
- "node": "*"
- }
- },
- "node_modules/@electron/fuses": {
- "version": "1.8.0",
- "resolved": "https://registry.npmjs.org/@electron/fuses/-/fuses-1.8.0.tgz",
- "integrity": "sha512-zx0EIq78WlY/lBb1uXlziZmDZI4ubcCXIMJ4uGjXzZW0nS19TjSPeXPAjzzTmKQlJUZm0SbmZhPKP7tuQ1SsEw==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "chalk": "^4.1.1",
- "fs-extra": "^9.0.1",
- "minimist": "^1.2.5"
+ "node": "18 || 20 || >=22"
},
- "bin": {
- "electron-fuses": "dist/bin.js"
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
}
},
- "node_modules/@electron/fuses/node_modules/ansi-styles": {
- "version": "4.3.0",
- "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
- "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
+ "node_modules/@electron/asar/node_modules/lru-cache": {
+ "version": "11.5.2",
+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.2.tgz",
+ "integrity": "sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g==",
"dev": true,
- "license": "MIT",
- "dependencies": {
- "color-convert": "^2.0.1"
- },
+ "license": "BlueOak-1.0.0",
"engines": {
- "node": ">=8"
- },
- "funding": {
- "url": "https://github.com/chalk/ansi-styles?sponsor=1"
+ "node": "20 || >=22"
}
},
- "node_modules/@electron/fuses/node_modules/chalk": {
- "version": "4.1.2",
- "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
- "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
+ "node_modules/@electron/asar/node_modules/path-scurry": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz",
+ "integrity": "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==",
"dev": true,
- "license": "MIT",
+ "license": "BlueOak-1.0.0",
"dependencies": {
- "ansi-styles": "^4.1.0",
- "supports-color": "^7.1.0"
+ "lru-cache": "^11.0.0",
+ "minipass": "^7.1.2"
},
"engines": {
- "node": ">=10"
+ "node": "18 || 20 || >=22"
},
"funding": {
- "url": "https://github.com/chalk/chalk?sponsor=1"
+ "url": "https://github.com/sponsors/isaacs"
}
},
- "node_modules/@electron/fuses/node_modules/fs-extra": {
- "version": "9.1.0",
- "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-9.1.0.tgz",
- "integrity": "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==",
+ "node_modules/@electron/fuses": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/@electron/fuses/-/fuses-2.1.3.tgz",
+ "integrity": "sha512-LoKJUXNiJ4JM8IIrUltSHI+8pkogaGj5wmJx81jE/Wk3g2w1/kfMbTEKNoY5kitGE8hiC12h32R/1SlywFtxXg==",
"dev": true,
"license": "MIT",
- "dependencies": {
- "at-least-node": "^1.0.0",
- "graceful-fs": "^4.2.0",
- "jsonfile": "^6.0.1",
- "universalify": "^2.0.0"
+ "bin": {
+ "electron-fuses": "dist/bin.js"
},
"engines": {
- "node": ">=10"
- }
- },
- "node_modules/@electron/fuses/node_modules/jsonfile": {
- "version": "6.2.1",
- "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz",
- "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "universalify": "^2.0.0"
- },
- "optionalDependencies": {
- "graceful-fs": "^4.1.6"
+ "node": ">=22.12.0"
}
},
- "node_modules/@electron/fuses/node_modules/supports-color": {
- "version": "7.2.0",
- "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
- "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
+ "node_modules/@electron/get": {
+ "version": "5.1.0",
+ "resolved": "https://registry.npmjs.org/@electron/get/-/get-5.1.0.tgz",
+ "integrity": "sha512-3kSBtG8ObcTVfXanm5vVJ6UnBLEVmVsRk1M+vGqCuMBV+XLCbJYuWQful+yIy0GQDsSlK0kHEriEHn7SPk4EnA==",
"dev": true,
"license": "MIT",
"dependencies": {
- "has-flag": "^4.0.0"
+ "debug": "^4.1.1",
+ "env-paths": "^3.0.0",
+ "graceful-fs": "^4.2.11",
+ "progress": "^2.0.3",
+ "semver": "^7.6.3",
+ "sumchecker": "^3.0.1"
},
"engines": {
- "node": ">=8"
+ "node": ">=22.12.0"
+ },
+ "optionalDependencies": {
+ "undici": "^7.24.4"
}
},
- "node_modules/@electron/fuses/node_modules/universalify": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
- "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
+ "node_modules/@electron/get/node_modules/env-paths": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-3.0.0.tgz",
+ "integrity": "sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A==",
"dev": true,
"license": "MIT",
"engines": {
- "node": ">= 10.0.0"
- }
- },
- "node_modules/@electron/notarize": {
- "version": "2.5.0",
- "resolved": "https://registry.npmjs.org/@electron/notarize/-/notarize-2.5.0.tgz",
- "integrity": "sha512-jNT8nwH1f9X5GEITXaQ8IF/KdskvIkOFfB2CvwumsveVidzpSc+mvhhTMdAGSYF3O+Nq49lJ7y+ssODRXu06+A==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "debug": "^4.1.1",
- "fs-extra": "^9.0.1",
- "promise-retry": "^2.0.1"
+ "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
},
- "engines": {
- "node": ">= 10.0.0"
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
}
},
- "node_modules/@electron/notarize/node_modules/fs-extra": {
- "version": "9.1.0",
- "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-9.1.0.tgz",
- "integrity": "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==",
+ "node_modules/@electron/get/node_modules/semver": {
+ "version": "7.8.5",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
+ "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
"dev": true,
- "license": "MIT",
- "dependencies": {
- "at-least-node": "^1.0.0",
- "graceful-fs": "^4.2.0",
- "jsonfile": "^6.0.1",
- "universalify": "^2.0.0"
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
},
"engines": {
"node": ">=10"
}
},
- "node_modules/@electron/notarize/node_modules/jsonfile": {
- "version": "6.2.1",
- "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz",
- "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==",
+ "node_modules/@electron/notarize": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/@electron/notarize/-/notarize-3.1.1.tgz",
+ "integrity": "sha512-uQQSlOiJnqRkTL1wlEBAxe90nVN/Fc/hEmk0bqpKk8nKjV1if/tXLHKUPePtv9Xsx90PtZU8aidx5lAiOpjkQQ==",
"dev": true,
"license": "MIT",
"dependencies": {
- "universalify": "^2.0.0"
+ "debug": "^4.4.0",
+ "promise-retry": "^2.0.1"
},
- "optionalDependencies": {
- "graceful-fs": "^4.1.6"
- }
- },
- "node_modules/@electron/notarize/node_modules/universalify": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
- "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
- "dev": true,
- "license": "MIT",
"engines": {
- "node": ">= 10.0.0"
+ "node": ">= 22.12.0"
}
},
"node_modules/@electron/osx-sign": {
- "version": "1.3.3",
- "resolved": "https://registry.npmjs.org/@electron/osx-sign/-/osx-sign-1.3.3.tgz",
- "integrity": "sha512-KZ8mhXvWv2rIEgMbWZ4y33bDHyUKMXnx4M0sTyPNK/vcB81ImdeY9Ggdqy0SWbMDgmbqyQ+phgejh6V3R2QuSg==",
+ "version": "2.4.0",
+ "resolved": "https://registry.npmjs.org/@electron/osx-sign/-/osx-sign-2.4.0.tgz",
+ "integrity": "sha512-9mJiKF/yrn2FYt1Pd9hIN8bUWs6w6uhm8DJJ/tZtTPMVmqv9/NO1JvRh+NyOJp8kE2bfffK4YkU3ZyM+rHipUw==",
"dev": true,
"license": "BSD-2-Clause",
"dependencies": {
- "compare-version": "^0.1.2",
"debug": "^4.3.4",
- "fs-extra": "^10.0.0",
"isbinaryfile": "^4.0.8",
- "minimist": "^1.2.6",
- "plist": "^3.0.5"
+ "plist": "^3.0.5",
+ "semver": "^7.7.1"
},
"bin": {
- "electron-osx-flat": "bin/electron-osx-flat.js",
- "electron-osx-sign": "bin/electron-osx-sign.js"
- },
- "engines": {
- "node": ">=12.0.0"
- }
- },
- "node_modules/@electron/osx-sign/node_modules/fs-extra": {
- "version": "10.1.0",
- "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz",
- "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "graceful-fs": "^4.2.0",
- "jsonfile": "^6.0.1",
- "universalify": "^2.0.0"
+ "electron-osx-flat": "bin/electron-osx-flat.mjs",
+ "electron-osx-sign": "bin/electron-osx-sign.mjs"
},
"engines": {
- "node": ">=12"
+ "node": ">=22.12.0"
}
},
"node_modules/@electron/osx-sign/node_modules/isbinaryfile": {
@@ -1904,27 +1840,17 @@
"url": "https://github.com/sponsors/gjtorikian/"
}
},
- "node_modules/@electron/osx-sign/node_modules/jsonfile": {
- "version": "6.2.1",
- "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz",
- "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==",
+ "node_modules/@electron/osx-sign/node_modules/semver": {
+ "version": "7.8.5",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
+ "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
"dev": true,
- "license": "MIT",
- "dependencies": {
- "universalify": "^2.0.0"
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
},
- "optionalDependencies": {
- "graceful-fs": "^4.1.6"
- }
- },
- "node_modules/@electron/osx-sign/node_modules/universalify": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
- "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
- "dev": true,
- "license": "MIT",
"engines": {
- "node": ">= 10.0.0"
+ "node": ">=10"
}
},
"node_modules/@electron/rebuild": {
@@ -1949,76 +1875,18 @@
}
},
"node_modules/@electron/universal": {
- "version": "2.0.3",
- "resolved": "https://registry.npmjs.org/@electron/universal/-/universal-2.0.3.tgz",
- "integrity": "sha512-Wn9sPYIVFRFl5HmwMJkARCCf7rqK/EurkfQ/rJZ14mHP3iYTjZSIOSVonEAnhWeAXwtw7zOekGRlc6yTtZ0t+g==",
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/@electron/universal/-/universal-3.0.4.tgz",
+ "integrity": "sha512-G7mNdfZIdPbx54dTorGlV7SN7nHAKlbJU1NjjeuEo7RzEMYBG62+tKpA2VrzocGcvFLxqJI5XYIknca9EijwOw==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@electron/asar": "^3.3.1",
- "@malept/cross-spawn-promise": "^2.0.0",
+ "@electron/asar": "^4.0.0",
"debug": "^4.3.1",
- "dir-compare": "^4.2.0",
- "fs-extra": "^11.1.1",
- "minimatch": "^9.0.3",
"plist": "^3.1.0"
},
"engines": {
- "node": ">=16.4"
- }
- },
- "node_modules/@electron/universal/node_modules/fs-extra": {
- "version": "11.3.6",
- "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.3.6.tgz",
- "integrity": "sha512-w8ZNZr2mKIc7qeNaQ9AVPT1+iFaI+Avd4xudVOvdDJ8VytREi1Ft5Ih7hd9jjehod8vAM5GMsfQ/TpPf4EyoEA==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "graceful-fs": "^4.2.0",
- "jsonfile": "^6.0.1",
- "universalify": "^2.0.0"
- },
- "engines": {
- "node": ">=14.14"
- }
- },
- "node_modules/@electron/universal/node_modules/jsonfile": {
- "version": "6.2.1",
- "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz",
- "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "universalify": "^2.0.0"
- },
- "optionalDependencies": {
- "graceful-fs": "^4.1.6"
- }
- },
- "node_modules/@electron/universal/node_modules/minimatch": {
- "version": "9.0.9",
- "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz",
- "integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==",
- "dev": true,
- "license": "ISC",
- "dependencies": {
- "brace-expansion": "^2.0.2"
- },
- "engines": {
- "node": ">=16 || 14 >=14.17"
- },
- "funding": {
- "url": "https://github.com/sponsors/isaacs"
- }
- },
- "node_modules/@electron/universal/node_modules/universalify": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
- "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">= 10.0.0"
+ "node": ">=22.12.0"
}
},
"node_modules/@electron/windows-sign": {
@@ -2044,9 +1912,9 @@
}
},
"node_modules/@electron/windows-sign/node_modules/fs-extra": {
- "version": "11.3.6",
- "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.3.6.tgz",
- "integrity": "sha512-w8ZNZr2mKIc7qeNaQ9AVPT1+iFaI+Avd4xudVOvdDJ8VytREi1Ft5Ih7hd9jjehod8vAM5GMsfQ/TpPf4EyoEA==",
+ "version": "11.4.0",
+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.4.0.tgz",
+ "integrity": "sha512-EQsFzMUJkCKGr1ePqlYADkIUmHW1s3ZXr5Yqy6wbGrfUCphpl2maM/kyOIRA2HpP3AaFQTZXD4ldjek+nccddA==",
"dev": true,
"license": "MIT",
"optional": true,
@@ -7350,6 +7218,7 @@
"version": "0.8.13",
"resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.13.tgz",
"integrity": "sha512-KRYzxepc14G/CEpEGc3Yn+JKaAeT63smlDr+vjB8jRfgTBBI9wRj/nkQEO+ucV8p8I9bfKLWp37uHgFrbntPvw==",
+ "deprecated": "this version has critical issues, please update to the latest version",
"dev": true,
"license": "MIT",
"engines": {
@@ -7520,36 +7389,35 @@
}
},
"node_modules/app-builder-lib": {
- "version": "26.15.3",
- "resolved": "https://registry.npmjs.org/app-builder-lib/-/app-builder-lib-26.15.3.tgz",
- "integrity": "sha512-2VnyWkqsP5v5XbBhL3tD5Syx8iNPBYsoU7kY4S2fz7wg8Rj/nztWKCUzGKaFRTv0Xwf3/H058CR1Kvtd/3lRow==",
+ "version": "27.0.0-alpha.6",
+ "resolved": "https://registry.npmjs.org/app-builder-lib/-/app-builder-lib-27.0.0-alpha.6.tgz",
+ "integrity": "sha512-XWQfZQJ7gTudBUQ49cId4hv7Z+JXNm+i8eR8Nj6pFVPMsCoEWRrbHLay1/W0HpHCEcSrR+7G6A+/yMrtR5AtZw==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@electron/asar": "3.4.1",
- "@electron/fuses": "^1.8.0",
- "@electron/get": "^3.0.0",
- "@electron/notarize": "2.5.0",
- "@electron/osx-sign": "1.3.3",
+ "@electron/asar": "4.1.1",
+ "@electron/fuses": "^2.1.1",
+ "@electron/get": "^5.0.0",
+ "@electron/notarize": "3.1.1",
+ "@electron/osx-sign": "2.4.0",
"@electron/rebuild": "^4.0.4",
- "@electron/universal": "2.0.3",
+ "@electron/universal": "3.0.4",
"@malept/flatpak-bundler": "^0.4.0",
"@noble/hashes": "^2.2.0",
"@peculiar/webcrypto": "^1.7.1",
"@types/fs-extra": "9.0.13",
"ajv": "^8.18.0",
"asn1js": "^3.0.10",
- "async-exit-hook": "^2.0.1",
- "builder-util": "26.15.3",
- "builder-util-runtime": "9.7.0",
+ "builder-util": "27.0.0-alpha.6",
+ "builder-util-runtime": "10.0.0-alpha.5",
"chromium-pickle-js": "^0.2.0",
"ci-info": "4.3.1",
"debug": "^4.3.4",
"dotenv": "^16.4.5",
"dotenv-expand": "^11.0.6",
"ejs": "^3.1.8",
- "electron-publish": "26.15.3",
- "fs-extra": "^10.1.0",
+ "electron-publish": "27.0.0-alpha.6",
+ "fs-extra": "^11.3.0",
"hosted-git-info": "^4.1.0",
"isbinaryfile": "^5.0.0",
"jiti": "^2.4.2",
@@ -7565,62 +7433,16 @@
"tar": "^7.5.7",
"temp-file": "^3.4.0",
"tiny-async-pool": "1.3.0",
+ "undici": "^7.27.1",
"unzipper": "^0.12.3",
"which": "^5.0.0"
},
"engines": {
- "node": ">=14.0.0"
+ "node": ">=22.12.0"
},
"peerDependencies": {
- "dmg-builder": "26.15.3",
- "electron-builder-squirrel-windows": "26.15.3"
- }
- },
- "node_modules/app-builder-lib/node_modules/@electron/get": {
- "version": "3.1.0",
- "resolved": "https://registry.npmjs.org/@electron/get/-/get-3.1.0.tgz",
- "integrity": "sha512-F+nKc0xW+kVbBRhFzaMgPy3KwmuNTYX1fx6+FxxoSnNgwYX6LD7AKBTWkU0MQ6IBoe7dz069CNkR673sPAgkCQ==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "debug": "^4.1.1",
- "env-paths": "^2.2.0",
- "fs-extra": "^8.1.0",
- "got": "^11.8.5",
- "progress": "^2.0.3",
- "semver": "^6.2.0",
- "sumchecker": "^3.0.1"
- },
- "engines": {
- "node": ">=14"
- },
- "optionalDependencies": {
- "global-agent": "^3.0.0"
- }
- },
- "node_modules/app-builder-lib/node_modules/@electron/get/node_modules/fs-extra": {
- "version": "8.1.0",
- "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz",
- "integrity": "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "graceful-fs": "^4.2.0",
- "jsonfile": "^4.0.0",
- "universalify": "^0.1.0"
- },
- "engines": {
- "node": ">=6 <7 || >=8"
- }
- },
- "node_modules/app-builder-lib/node_modules/@electron/get/node_modules/semver": {
- "version": "6.3.1",
- "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
- "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
- "dev": true,
- "license": "ISC",
- "bin": {
- "semver": "bin/semver.js"
+ "dmg-builder": "27.0.0-alpha.6",
+ "electron-builder-squirrel-windows": "27.0.0-alpha.6"
}
},
"node_modules/app-builder-lib/node_modules/ajv": {
@@ -7657,9 +7479,9 @@
}
},
"node_modules/app-builder-lib/node_modules/fs-extra": {
- "version": "10.1.0",
- "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz",
- "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==",
+ "version": "11.4.0",
+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.4.0.tgz",
+ "integrity": "sha512-EQsFzMUJkCKGr1ePqlYADkIUmHW1s3ZXr5Yqy6wbGrfUCphpl2maM/kyOIRA2HpP3AaFQTZXD4ldjek+nccddA==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -7668,30 +7490,7 @@
"universalify": "^2.0.0"
},
"engines": {
- "node": ">=12"
- }
- },
- "node_modules/app-builder-lib/node_modules/fs-extra/node_modules/jsonfile": {
- "version": "6.2.1",
- "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz",
- "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "universalify": "^2.0.0"
- },
- "optionalDependencies": {
- "graceful-fs": "^4.1.6"
- }
- },
- "node_modules/app-builder-lib/node_modules/fs-extra/node_modules/universalify": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
- "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">= 10.0.0"
+ "node": ">=14.14"
}
},
"node_modules/app-builder-lib/node_modules/isexe": {
@@ -7711,6 +7510,19 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/app-builder-lib/node_modules/jsonfile": {
+ "version": "6.2.1",
+ "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz",
+ "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "universalify": "^2.0.0"
+ },
+ "optionalDependencies": {
+ "graceful-fs": "^4.1.6"
+ }
+ },
"node_modules/app-builder-lib/node_modules/semver": {
"version": "7.7.4",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",
@@ -7724,6 +7536,16 @@
"node": ">=10"
}
},
+ "node_modules/app-builder-lib/node_modules/universalify": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
+ "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 10.0.0"
+ }
+ },
"node_modules/app-builder-lib/node_modules/which": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/which/-/which-5.0.0.tgz",
@@ -8157,18 +7979,18 @@
"license": "MIT"
},
"node_modules/builder-util": {
- "version": "26.15.3",
- "resolved": "https://registry.npmjs.org/builder-util/-/builder-util-26.15.3.tgz",
- "integrity": "sha512-q2hn7Mbo2nFNkVekPiHFx6Nfo3hURmES3tfBn+k5Pqxl2RkmP3QGqZUhH/q9Pch/4G05NRhPjDlVj1O8q4Txvw==",
+ "version": "27.0.0-alpha.6",
+ "resolved": "https://registry.npmjs.org/builder-util/-/builder-util-27.0.0-alpha.6.tgz",
+ "integrity": "sha512-EboYx4Srrhq33B5psjWKcnATsYtqenVzA+Y8vpBU6QmyPJ9699thXCNwVbK5P0+CsxDrnaYwR/YeYOE/HAvdHg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/debug": "^4.1.6",
- "builder-util-runtime": "9.7.0",
+ "builder-util-runtime": "10.0.0-alpha.5",
"chalk": "^4.1.2",
"cross-spawn": "^7.0.6",
"debug": "^4.3.4",
- "fs-extra": "^10.1.0",
+ "fs-extra": "^11.3.0",
"http-proxy-agent": "^7.0.0",
"https-proxy-agent": "^7.0.0",
"js-yaml": "^4.1.0",
@@ -8179,13 +8001,13 @@
"tiny-async-pool": "1.3.0"
},
"engines": {
- "node": ">=14.0.0"
+ "node": ">=22.12.0"
}
},
"node_modules/builder-util-runtime": {
- "version": "9.7.0",
- "resolved": "https://registry.npmjs.org/builder-util-runtime/-/builder-util-runtime-9.7.0.tgz",
- "integrity": "sha512-g/kR520giAFYkSXTzcmF3kqQq7wi8F6N6SzeDgZrqTBN+VHdmgWOyTdD1yD7AATDId/yXLvuP34CxW46/BwCdw==",
+ "version": "10.0.0-alpha.5",
+ "resolved": "https://registry.npmjs.org/builder-util-runtime/-/builder-util-runtime-10.0.0-alpha.5.tgz",
+ "integrity": "sha512-ofrNMSQ2E5iUgWPyywWme5Mm55kMqq0Yz/wJ6iEuXdWt7pdr4hIL2FPuY8OVHD4LuPMUyGszPERsqVnD1zkZ4g==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -8193,7 +8015,7 @@
"sax": "^1.2.4"
},
"engines": {
- "node": ">=12.0.0"
+ "node": ">=22.12.0"
}
},
"node_modules/builder-util/node_modules/ansi-styles": {
@@ -8230,9 +8052,9 @@
}
},
"node_modules/builder-util/node_modules/fs-extra": {
- "version": "10.1.0",
- "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz",
- "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==",
+ "version": "11.4.0",
+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.4.0.tgz",
+ "integrity": "sha512-EQsFzMUJkCKGr1ePqlYADkIUmHW1s3ZXr5Yqy6wbGrfUCphpl2maM/kyOIRA2HpP3AaFQTZXD4ldjek+nccddA==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -8241,7 +8063,7 @@
"universalify": "^2.0.0"
},
"engines": {
- "node": ">=12"
+ "node": ">=14.14"
}
},
"node_modules/builder-util/node_modules/jsonfile": {
@@ -8758,23 +8580,13 @@
}
},
"node_modules/commander": {
- "version": "5.1.0",
- "resolved": "https://registry.npmjs.org/commander/-/commander-5.1.0.tgz",
- "integrity": "sha512-P0CysNDQ7rtVw4QIQtm+MRxV66vKFSvlsQvGYXZWR3qFU0jlMKHZZZgw8e+8DSah4UDKMqnknRDQz+xuQXQ/Zg==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">= 6"
- }
- },
- "node_modules/compare-version": {
- "version": "0.1.2",
- "resolved": "https://registry.npmjs.org/compare-version/-/compare-version-0.1.2.tgz",
- "integrity": "sha512-pJDh5/4wrEnXX/VWRZvruAGHkzKdr46z11OlTPN+VrATlWWhSKewNCJ1futCO5C7eJB3nPMFZA1LeYtcFboZ2A==",
+ "version": "13.1.0",
+ "resolved": "https://registry.npmjs.org/commander/-/commander-13.1.0.tgz",
+ "integrity": "sha512-/rFeCpNJQbhSZjGVwO9RFV3xPqbnERS8MmIQzCtD/zl6gpJuV/bMLuN92oG3F7d8oDEHHRrujSXNUr8fpjntKw==",
"dev": true,
"license": "MIT",
"engines": {
- "node": ">=0.10.0"
+ "node": ">=18"
}
},
"node_modules/concurrently": {
@@ -9720,47 +9532,27 @@
"integrity": "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==",
"license": "MIT"
},
- "node_modules/dir-compare": {
- "version": "4.2.0",
- "resolved": "https://registry.npmjs.org/dir-compare/-/dir-compare-4.2.0.tgz",
- "integrity": "sha512-2xMCmOoMrdQIPHdsTawECdNPwlVFB9zGcz3kuhmBO6U3oU+UQjsue0i8ayLKpgBcm+hcXPMVSGUN9d+pvJ6+VQ==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "minimatch": "^3.0.5",
- "p-limit": "^3.1.0 "
- }
- },
- "node_modules/dir-compare/node_modules/minimatch": {
- "version": "3.1.5",
- "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",
- "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",
- "dev": true,
- "license": "ISC",
- "dependencies": {
- "brace-expansion": "^1.1.7"
- },
- "engines": {
- "node": "*"
- }
- },
"node_modules/dmg-builder": {
- "version": "26.15.3",
- "resolved": "https://registry.npmjs.org/dmg-builder/-/dmg-builder-26.15.3.tgz",
- "integrity": "sha512-O3zJUFUYHJKgzPqioHxfxzBzlSC1eXCSr79gMSBKBP5AgjjpmrydMsMLotEg9fAJF36vdUncb+4ndRNxoPdlSQ==",
+ "version": "27.0.0-alpha.6",
+ "resolved": "https://registry.npmjs.org/dmg-builder/-/dmg-builder-27.0.0-alpha.6.tgz",
+ "integrity": "sha512-3bvNvPmeeHVoWyR0iW6pX3lQG94sacieuiwvb3o5s6sn1GtjS6XQuKHHNrRZAi3PnDJ/XkfwuI6RIsJfsuqa6g==",
"dev": true,
"license": "MIT",
"dependencies": {
- "app-builder-lib": "26.15.3",
- "builder-util": "26.15.3",
- "fs-extra": "^10.1.0",
+ "app-builder-lib": "27.0.0-alpha.6",
+ "builder-util": "27.0.0-alpha.6",
+ "builder-util-runtime": "10.0.0-alpha.5",
+ "fs-extra": "^11.3.0",
"js-yaml": "^4.1.0"
+ },
+ "engines": {
+ "node": ">=22.12.0"
}
},
"node_modules/dmg-builder/node_modules/fs-extra": {
- "version": "10.1.0",
- "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz",
- "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==",
+ "version": "11.4.0",
+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.4.0.tgz",
+ "integrity": "sha512-EQsFzMUJkCKGr1ePqlYADkIUmHW1s3ZXr5Yqy6wbGrfUCphpl2maM/kyOIRA2HpP3AaFQTZXD4ldjek+nccddA==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -9769,7 +9561,7 @@
"universalify": "^2.0.0"
},
"engines": {
- "node": ">=12"
+ "node": ">=14.14"
}
},
"node_modules/dmg-builder/node_modules/jsonfile": {
@@ -9985,20 +9777,20 @@
}
},
"node_modules/electron-builder": {
- "version": "26.15.3",
- "resolved": "https://registry.npmjs.org/electron-builder/-/electron-builder-26.15.3.tgz",
- "integrity": "sha512-a1KM5heqS3gQCZzizXEI8RjJy3QVogULPdeSknt76uLDpBIW/HDGsMg/XgP0riP6PI9COsRvFITKKGDqA8fJxA==",
+ "version": "27.0.0-alpha.6",
+ "resolved": "https://registry.npmjs.org/electron-builder/-/electron-builder-27.0.0-alpha.6.tgz",
+ "integrity": "sha512-vnsyKuG60X3+Dyl2VnxVoPxndjnXlczb15qE250hpAkIEtu5T/edNmSihDZw7GEZw15zU8g/4egEqaIfeatn0w==",
"dev": true,
"license": "MIT",
"dependencies": {
- "app-builder-lib": "26.15.3",
- "builder-util": "26.15.3",
- "builder-util-runtime": "9.7.0",
+ "app-builder-lib": "27.0.0-alpha.6",
+ "builder-util": "27.0.0-alpha.6",
+ "builder-util-runtime": "10.0.0-alpha.5",
"chalk": "^4.1.2",
"ci-info": "^4.2.0",
- "dmg-builder": "26.15.3",
- "fs-extra": "^10.1.0",
- "lazy-val": "^1.0.5",
+ "dmg-builder": "27.0.0-alpha.6",
+ "electron-publish": "27.0.0-alpha.6",
+ "fs-extra": "^11.3.0",
"simple-update-notifier": "2.0.0",
"yargs": "^17.6.2"
},
@@ -10007,20 +9799,23 @@
"install-app-deps": "install-app-deps.js"
},
"engines": {
- "node": ">=14.0.0"
+ "node": ">=22.12.0"
}
},
"node_modules/electron-builder-squirrel-windows": {
- "version": "26.15.3",
- "resolved": "https://registry.npmjs.org/electron-builder-squirrel-windows/-/electron-builder-squirrel-windows-26.15.3.tgz",
- "integrity": "sha512-Jc19XPV9y9+2bAdZPkXuVNGNIEFBq9poHC61l8Kv6FdK7DRG3+Ic0rerC0DXOaeHNz8yW0fg/JnF8GQROOF5MA==",
+ "version": "27.0.0-alpha.6",
+ "resolved": "https://registry.npmjs.org/electron-builder-squirrel-windows/-/electron-builder-squirrel-windows-27.0.0-alpha.6.tgz",
+ "integrity": "sha512-WjFLFsuI5Yd9A+3ZohGWnaiLYYALd/0gH+1TmfyANym3r1YnxltXsdK3OvfpVUTurnEmABYfRhgQBwKVOd3xgg==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
- "app-builder-lib": "26.15.3",
- "builder-util": "26.15.3",
+ "app-builder-lib": "27.0.0-alpha.6",
+ "builder-util": "27.0.0-alpha.6",
"electron-winstaller": "5.4.0"
+ },
+ "engines": {
+ "node": ">=22.12.0"
}
},
"node_modules/electron-builder/node_modules/ansi-styles": {
@@ -10079,9 +9874,9 @@
"license": "MIT"
},
"node_modules/electron-builder/node_modules/fs-extra": {
- "version": "10.1.0",
- "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz",
- "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==",
+ "version": "11.4.0",
+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.4.0.tgz",
+ "integrity": "sha512-EQsFzMUJkCKGr1ePqlYADkIUmHW1s3ZXr5Yqy6wbGrfUCphpl2maM/kyOIRA2HpP3AaFQTZXD4ldjek+nccddA==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -10090,7 +9885,7 @@
"universalify": "^2.0.0"
},
"engines": {
- "node": ">=12"
+ "node": ">=14.14"
}
},
"node_modules/electron-builder/node_modules/is-fullwidth-code-point": {
@@ -10215,21 +10010,24 @@
}
},
"node_modules/electron-publish": {
- "version": "26.15.3",
- "resolved": "https://registry.npmjs.org/electron-publish/-/electron-publish-26.15.3.tgz",
- "integrity": "sha512-g/2bn8YTavY4cuS5F+jOS7zmZbXXBV8KZ8yHKfJjFPoKtzBqrpCdNPxBd3tqdBwP7BVd0lGzf7Bk2s0KesWZ4Q==",
+ "version": "27.0.0-alpha.6",
+ "resolved": "https://registry.npmjs.org/electron-publish/-/electron-publish-27.0.0-alpha.6.tgz",
+ "integrity": "sha512-5MBpfPNIz0H/zZkvH6hfd6CQzYW4+OO0aGZOhtjPgglUAANFiafhMWwMJ19Plioc3zF1d9kq7t9eTKOwbi1veQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/fs-extra": "^9.0.11",
"aws4": "^1.13.2",
- "builder-util": "26.15.3",
- "builder-util-runtime": "9.7.0",
+ "builder-util": "27.0.0-alpha.6",
+ "builder-util-runtime": "10.0.0-alpha.5",
"chalk": "^4.1.2",
"form-data": "^4.0.5",
- "fs-extra": "^10.1.0",
+ "fs-extra": "^11.3.0",
"lazy-val": "^1.0.5",
"mime": "^2.5.2"
+ },
+ "engines": {
+ "node": ">=22.12.0"
}
},
"node_modules/electron-publish/node_modules/ansi-styles": {
@@ -10266,9 +10064,9 @@
}
},
"node_modules/electron-publish/node_modules/fs-extra": {
- "version": "10.1.0",
- "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz",
- "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==",
+ "version": "11.4.0",
+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.4.0.tgz",
+ "integrity": "sha512-EQsFzMUJkCKGr1ePqlYADkIUmHW1s3ZXr5Yqy6wbGrfUCphpl2maM/kyOIRA2HpP3AaFQTZXD4ldjek+nccddA==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -10277,7 +10075,7 @@
"universalify": "^2.0.0"
},
"engines": {
- "node": ">=12"
+ "node": ">=14.14"
}
},
"node_modules/electron-publish/node_modules/jsonfile": {
@@ -10345,6 +10143,36 @@
"@electron/windows-sign": "^1.1.2"
}
},
+ "node_modules/electron-winstaller/node_modules/@electron/asar": {
+ "version": "3.4.1",
+ "resolved": "https://registry.npmjs.org/@electron/asar/-/asar-3.4.1.tgz",
+ "integrity": "sha512-i4/rNPRS84t0vSRa2HorerGRXWyF4vThfHesw0dmcWHp+cspK743UanA0suA5Q5y8kzY2y6YKrvbIUn69BCAiA==",
+ "dev": true,
+ "license": "MIT",
+ "peer": true,
+ "dependencies": {
+ "commander": "^5.0.0",
+ "glob": "^7.1.6",
+ "minimatch": "^3.0.4"
+ },
+ "bin": {
+ "asar": "bin/asar.js"
+ },
+ "engines": {
+ "node": ">=10.12.0"
+ }
+ },
+ "node_modules/electron-winstaller/node_modules/commander": {
+ "version": "5.1.0",
+ "resolved": "https://registry.npmjs.org/commander/-/commander-5.1.0.tgz",
+ "integrity": "sha512-P0CysNDQ7rtVw4QIQtm+MRxV66vKFSvlsQvGYXZWR3qFU0jlMKHZZZgw8e+8DSah4UDKMqnknRDQz+xuQXQ/Zg==",
+ "dev": true,
+ "license": "MIT",
+ "peer": true,
+ "engines": {
+ "node": ">= 6"
+ }
+ },
"node_modules/electron-winstaller/node_modules/fs-extra": {
"version": "7.0.1",
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-7.0.1.tgz",
@@ -10361,6 +10189,20 @@
"node": ">=6 <7 || >=8"
}
},
+ "node_modules/electron-winstaller/node_modules/minimatch": {
+ "version": "3.1.5",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",
+ "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",
+ "dev": true,
+ "license": "ISC",
+ "peer": true,
+ "dependencies": {
+ "brace-expansion": "^1.1.7"
+ },
+ "engines": {
+ "node": "*"
+ }
+ },
"node_modules/emoji-regex": {
"version": "10.6.0",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz",
@@ -10950,9 +10792,9 @@
"peer": true
},
"node_modules/fast-uri": {
- "version": "3.1.5",
- "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.5.tgz",
- "integrity": "sha512-gHwA1O9LDIcKunMKhObS/HimwtehO1nPUECKAu5TpKgaO19fcWEl4bliWe1jWxVFvIXztJjjQ4L8XQ1EU9f7Jw==",
+ "version": "3.1.6",
+ "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.6.tgz",
+ "integrity": "sha512-7Ical1vFEMr0onbVzEDIreM22I4khW+fzyQPwvAFWBp1iwdshSZRsL4jjRvPG9JP1uiqMHRto+YU6R2/CzDz5Q==",
"dev": true,
"funding": [
{
@@ -15291,6 +15133,7 @@
"integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"yocto-queue": "^0.1.0"
},
@@ -15845,9 +15688,9 @@
}
},
"node_modules/pvutils": {
- "version": "1.1.5",
- "resolved": "https://registry.npmjs.org/pvutils/-/pvutils-1.1.5.tgz",
- "integrity": "sha512-KTqnxsgGiQ6ZAzZCVlJH5eOjSnvlyEgx1m8bkRJfOhmGRqfo5KLvmAlACQkrjEtOQ4B7wF9TdSLIs9O90MX9xA==",
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/pvutils/-/pvutils-1.2.0.tgz",
+ "integrity": "sha512-BbubeCEyTuQjVMakvJQ/Sxbc93F2pwmbsxONT/ZRrwU7Ua38d8unYTwXpTVLAKJ4BDuH9IGztCjQcd/N/39Dvg==",
"dev": true,
"license": "MIT",
"engines": {
@@ -16945,9 +16788,9 @@
}
},
"node_modules/sax": {
- "version": "1.6.0",
- "resolved": "https://registry.npmjs.org/sax/-/sax-1.6.0.tgz",
- "integrity": "sha512-6R3J5M4AcbtLUdZmRv2SygeVaM7IhrLXu9BmnOGmmACak8fiUtOsYNWUS4uK7upbmHIBbLBeFeI//477BKLBzA==",
+ "version": "1.6.1",
+ "resolved": "https://registry.npmjs.org/sax/-/sax-1.6.1.tgz",
+ "integrity": "sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q==",
"dev": true,
"license": "BlueOak-1.0.0",
"engines": {
@@ -19376,6 +19219,7 @@
"integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==",
"dev": true,
"license": "MIT",
+ "peer": true,
"engines": {
"node": ">=10"
},
diff --git a/scripts/audit-old-updater-imports.py b/scripts/audit-old-updater-imports.py
index d4d4735d67a..05cd6f18bf6 100644
--- a/scripts/audit-old-updater-imports.py
+++ b/scripts/audit-old-updater-imports.py
@@ -79,7 +79,7 @@ UPDATE_MODULE_CANDIDATES = (
# in these is treated as post-swap.
POST_SWAP_HELPER_MODULES = (
"hermes_cli/post_update.py",
- "hermes_cli/managed_uv.py",
+ "hermes_cli/runtime_repair.py",
"hermes_cli/update_lock.py",
# pm era: `hermes update` drives the store through the pm package. A pm
# module imported BEFORE the swap keeps running as old code afterwards,
diff --git a/scripts/dev-minimal-sandbox.sh b/scripts/dev-minimal-sandbox.sh
new file mode 100755
index 00000000000..1808674309a
--- /dev/null
+++ b/scripts/dev-minimal-sandbox.sh
@@ -0,0 +1,198 @@
+#!/usr/bin/env bash
+# Run a Hermes instance in an isolated sandbox — separate HERMES_HOME,
+# separate Electron userData, and a distinct Desktop app name so it doesn't compete
+# with your main desktop instance's single-instance lock.
+#
+# By default the sandbox is throwaway: a temp dir is created and removed on
+# exit. Use --persistent to keep the sandbox across restarts (stored under
+# .hermes-minimal-sandbox/ in the worktree git root).
+#
+# Usage:
+# scripts/dev-minimal-sandbox.sh python -m hermes_cli.main
+# scripts/dev-minimal-sandbox.sh hermes desktop
+# scripts/dev-minimal-sandbox.sh electron .
+# scripts/dev-minimal-sandbox.sh -- npm run dev # from apps/desktop/
+# scripts/dev-minimal-sandbox.sh --persistent hermes desktop
+# scripts/dev-minimal-sandbox.sh --persistent -- npm run dev
+#
+# Seed the sandbox HERMES_HOME from an existing directory (e.g. your main
+# ~/.hermes) so config, sessions, skills, etc. are pre-populated:
+# scripts/dev-minimal-sandbox.sh --from ~/.hermes hermes desktop
+#
+# Override the app name (default: HermesSandbox):
+# HERMES_DEV_SANDBOX_NAME=Staging scripts/dev-minimal-sandbox.sh hermes desktop
+#
+# Override the persistent sandbox dir name (default: .hermes-sandbox):
+# HERMES_DEV_SANDBOX_DIR=.staging-sandbox scripts/dev-minimal-sandbox.sh --persistent hermes desktop
+
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+
+print_help() {
+ cat <<'EOF'
+Usage: dev-minimal-sandbox.sh [--persistent] [--from DIR] [--] <command...>
+
+Run a Hermes instance in an isolated sandbox.
+
+Options:
+ --persistent Keep the sandbox dir across restarts (under the worktree
+ git root, in .hermes-sandbox/). Without this flag the
+ sandbox is a temp dir that is removed on exit.
+ --from DIR Copy DIR into the sandbox HERMES_HOME as the starting
+ point (config, sessions, skills, etc.).
+ Ignored if the sandbox HERMES_HOME already has content
+ (e.g. reusing a --persistent sandbox) to avoid clobbering.
+ --delete Delete the existing persistent sandbox in .hermes-sandbox.
+ -h, --help Show this help message.
+
+Environment:
+ HERMES_DEV_SANDBOX_NAME Override the app name (default: HermesSandbox)
+ HERMES_DEV_SANDBOX_DIR Override the persistent dir name (default: .hermes-sandbox)
+
+Examples:
+ dev-minimal-sandbox.sh hermes desktop
+ dev-minimal-sandbox.sh --persistent hermes desktop
+ dev-minimal-sandbox.sh --from ~/.hermes hermes desktop
+ dev-minimal-sandbox.sh -- npm run dev
+EOF
+}
+
+PERSISTENT=false
+DELETE=false
+SEED_DIR=""
+
+while [ "$#" -gt 0 ]; do
+ case "$1" in
+ --persistent)
+ PERSISTENT=true
+ shift
+ ;;
+ --from)
+ if [ "$#" -lt 2 ] || [[ "$2" == -* ]]; then
+ echo "error: --from requires a directory argument" >&2
+ exit 1
+ fi
+ SEED_DIR="$2"
+ shift 2
+ ;;
+ --from=*)
+ SEED_DIR="${1#--from=}"
+ if [ -z "$SEED_DIR" ]; then
+ echo "error: --from requires a directory argument" >&2
+ exit 1
+ fi
+ shift
+ ;;
+ --delete)
+ DELETE=true
+ shift
+ ;;
+ -h|--help)
+ print_help
+ exit 0
+ ;;
+ --)
+ shift
+ break
+ ;;
+ *)
+ break
+ ;;
+ esac
+done
+
+if [ -n "$SEED_DIR" ]; then
+ if [ ! -d "$SEED_DIR" ]; then
+ echo "error: --from dir '$SEED_DIR' does not exist" >&2
+ exit 1
+ fi
+ # Resolve to absolute path so it's valid after we cd later.
+ SEED_DIR="$(cd "$SEED_DIR" && pwd)"
+fi
+
+if [ "$#" -eq 0 ]; then
+ print_help >&2
+ exit 1
+fi
+
+
+SANDBOX_DIR_NAME="${HERMES_DEV_SANDBOX_DIR:-.hermes-minimal-sandbox}"
+GIT_ROOT="$(git rev-parse --show-toplevel 2>/dev/null || echo "$SCRIPT_DIR/..")"
+GIT_ROOT="$(cd "$GIT_ROOT" && pwd)"
+PERSISTENT_SANDBOX_ROOT="$GIT_ROOT/$SANDBOX_DIR_NAME"
+
+if [ "$DELETE" = true ]; then
+ if [ -d "$PERSISTENT_SANDBOX_ROOT" ]; then
+ read -r -p "[sandbox] delete $PERSISTENT_SANDBOX_ROOT? [y/N] " REPLY
+ case "$REPLY" in
+ [yY]|[yY][eE][sS])
+ echo "[sandbox] deleting $PERSISTENT_SANDBOX_ROOT" >&2
+ rm -rf -- "$PERSISTENT_SANDBOX_ROOT"
+ ;;
+ *)
+ echo "[sandbox] aborted" >&2
+ exit 1
+ ;;
+ esac
+ else
+ echo "[sandbox] nothing to delete at $PERSISTENT_SANDBOX_ROOT" >&2
+ fi
+ exit 0
+fi
+
+# Derive a per-worktree app name so multiple checkouts don't collide.
+# Each worktree has its own toplevel path even though they share one repo,
+# so we hash that path into a short, stable suffix.
+WORKTREE_ROOT="$(git rev-parse --show-toplevel 2>/dev/null || echo "$SCRIPT_DIR/..")"
+WORKTREE_ROOT="$(cd "$WORKTREE_ROOT" && pwd)"
+WORKTREE_HASH="$(printf '%s' "$WORKTREE_ROOT" | cksum | cut -d' ' -f1)"
+WORKTREE_NAME="$(basename "$WORKTREE_ROOT")"
+DEFAULT_SANDBOX_NAME="HermesMinimalSandbox-${WORKTREE_NAME}-${WORKTREE_HASH}"
+
+SANDBOX_NAME="${HERMES_DEV_SANDBOX_NAME:-$DEFAULT_SANDBOX_NAME}"
+
+if [ "$PERSISTENT" = true ]; then
+ SANDBOX_ROOT="$PERSISTENT_SANDBOX_ROOT"
+else
+ SANDBOX_ROOT="$(mktemp -d -t hermes-minimal-sandbox.XXXXXX)"
+fi
+
+export HERMES_HOME="$SANDBOX_ROOT/hermes-home"
+export HERMES_DESKTOP_USER_DATA_DIR="$SANDBOX_ROOT/user-data"
+export HERMES_DESKTOP_APP_NAME="$SANDBOX_NAME"
+
+mkdir -p "$HERMES_HOME" "$HERMES_DESKTOP_USER_DATA_DIR"
+
+if [ -n "$SEED_DIR" ]; then
+ # Only seed when the sandbox HERMES_HOME is empty — avoids clobbering an
+ # existing persistent sandbox on re-run.
+ if [ -z "$(ls -A "$HERMES_HOME" 2>/dev/null)" ]; then
+ echo "[sandbox] seeding HERMES_HOME from $SEED_DIR" >&2
+ cp -a "$SEED_DIR/." "$HERMES_HOME/"
+ else
+ echo "[sandbox] --from ignored: $HERMES_HOME already has content" >&2
+ fi
+fi
+
+echo "[sandbox] HERMES_HOME=$HERMES_HOME" >&2
+echo "[sandbox] userData=$HERMES_DESKTOP_USER_DATA_DIR" >&2
+echo "[sandbox] appName=$HERMES_DESKTOP_APP_NAME" >&2
+if [ "$PERSISTENT" = true ]; then
+ echo "[sandbox] persistent: $SANDBOX_ROOT" >&2
+else
+ echo "[sandbox] ephemeral (will be cleaned up on exit)" >&2
+fi
+
+if [ "$PERSISTENT" = false ]; then
+ cleanup() {
+ chmod -R u+w "$SANDBOX_ROOT"
+ rm -rf -- "$SANDBOX_ROOT"
+ }
+ trap cleanup EXIT
+ trap 'cleanup; exit 130' INT TERM
+fi
+
+"$@"
+rc=$?
+exit $rc
\ No newline at end of file
diff --git a/scripts/install.ps1 b/scripts/install.ps1
index fec7e48d618..a5396448399 100644
--- a/scripts/install.ps1
+++ b/scripts/install.ps1
@@ -1,5012 +1,365 @@
-# ============================================================================
-# Hermes Agent Installer for Windows
-# ============================================================================
-# Installation script for Windows (PowerShell).
-# Uses uv for fast Python provisioning and package management.
-#
-# Usage:
-# iex (irm https://hermes-agent.nousresearch.com/install.ps1)
-#
-# Or download and run with options:
-# .\install.ps1 -NoVenv -SkipSetup
-#
-# ============================================================================
-
+# Hermes Agent bootstrap: git checkout + venv + hermes command on PATH.
+# Heavy dependencies (tool binaries, browsers, node) are pm's job after
+# this: `hermes pm install`. Stage protocol kept for Hermes-Setup:
+# -Manifest print the stage list as JSON
+# -Stage NAME [-Json] run one stage
+# -NonInteractive skip stages that need input
+# -IncludeDesktop add the desktop build stage
+# -ProtocolVersion print the stage protocol version
param(
- [switch]$NoVenv,
- [switch]$SkipSetup,
- [switch]$SkipComputerUse,
[string]$Branch = "main",
- # -Commit and -Tag are higher-precedence variants of -Branch for users
- # who need reproducible installs (desktop installer pinning, CI, release
- # bundles). When set, the repository stage clones $Branch (faster than
- # cloning the full default-branch history) and then `git checkout`s the
- # exact ref. Precedence: Commit > Tag > Branch.
[string]$Commit = "",
- # Apply -Commit even when it would roll an existing install BACKWARDS.
- # Without this the repository stage skips a pin that is already an ancestor
- # of HEAD, so a stale baked-in BUILD_PIN_COMMIT can't downgrade a current
- # checkout. Reproducible/CI installs that genuinely want an older SHA on an
- # existing tree pass -ForceCommit.
- [switch]$ForceCommit,
- [string]$Tag = "",
[string]$HermesHome = $(if ($env:HERMES_HOME) { $env:HERMES_HOME } else { "$env:LOCALAPPDATA\hermes" }),
[string]$InstallDir = $(if ($env:HERMES_HOME) { "$env:HERMES_HOME\hermes-agent" } else { "$env:LOCALAPPDATA\hermes\hermes-agent" }),
-
- # --- Stage protocol (additive; default invocation behaves as before) ----
- # See the "Stage protocol" section near the bottom of the file for the
- # full contract. Intended for programmatic drivers (the desktop GUI's
- # onboarding wizard, CI, future install.sh parity, etc.). CLI users
- # running the canonical `irm | iex` one-liner never touch these flags.
[switch]$Manifest,
[string]$Stage,
[switch]$ProtocolVersion,
[switch]$NonInteractive,
[switch]$Json,
-
- # Print the paths this install would use, as JSON, and exit without
- # touching anything. The first question on any "installer says a path
- # doesn't exist" report is which paths it actually resolved -- especially
- # on profiles Windows exposes through an 8.3 alias, where what the user
- # sees in Explorer and what the installer receives differ.
- #
- # powershell -File install.ps1 -ShowResolvedPaths
- [switch]$ShowResolvedPaths,
-
- # --- Ensure mode (dep_ensure.py entry point) ---
- [string]$Ensure = "",
- [switch]$PostInstall,
-
- # --- Desktop GUI build (opt-in) ---
- # When set, install.ps1 includes Stage-Desktop in the manifest and
- # builds apps/desktop into a launchable Hermes.exe.
- #
- # Why opt-in:
- # * Hermes-Setup.exe (the signed Tauri bootstrap installer) passes
- # -IncludeDesktop so a user who installed via the GUI ends up
- # with a launchable desktop binary.
- # * The Electron desktop's own bootstrap-runner.ts runs install.ps1
- # from inside an already-launched Hermes.exe; if THAT recursively
- # built apps/desktop it would try to overwrite the live Hermes.exe
- # on disk and fail. The recursive path omits the flag.
- # * The canonical CLI one-liner (irm | iex) omits the flag too;
- # terminal users don't need a desktop binary built for them, and
- # `hermes desktop` already builds on demand.
[switch]$IncludeDesktop
)
$ErrorActionPreference = "Stop"
+$RepoUrl = if ($env:HERMES_REPO_URL) { $env:HERMES_REPO_URL } else { "https://github.com/NousResearch/hermes-agent.git" }
-# Suppress Invoke-WebRequest's per-chunk progress bar. Windows PowerShell
-# 5.1's progress UI repaints synchronously on every received byte, which
-# pegs CPU on a single core and throttles downloads by 10-100x (a 57MB
-# PortableGit grab can take 5 minutes with progress on vs 20 seconds
-# with progress off, on the same network). Every IWR call in this
-# script is fire-and-forget so we never need to see the bar. Restored
-# automatically when the script exits.
-$ProgressPreference = "SilentlyContinue"
-
-# Force the console to UTF-8 so non-ASCII output from native commands
-# (e.g. playwright's box-drawing progress bars and download banners,
-# git's bullet glyphs, npm's check marks) renders correctly instead of
-# as IBM437/Windows-1252 mojibake (sequences like 0xE2 0x95 0x94 box-
-# drawing chars decoded under the legacy DOS codepage). This is a
-# DISPLAY-only fix; the underlying bytes are already correct. We do
-# NOT change the file's own encoding (it remains pure ASCII for PS 5.1
-# parser compatibility; see comments at the top of the entry-point
-# dispatch). This affects only what the user sees in their terminal
-# during this install run, and reverts automatically when the script
-# exits and the host's console encoding is restored.
-try {
- [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new()
-} catch {
- # Some constrained PowerShell hosts disallow encoding mutation.
- # Mojibake on output is then cosmetic-only, install still works.
-}
-
-# ============================================================================
-# 8.3 short-path normalization
-# ============================================================================
-# Windows generates an 8.3 short alias for a user-profile folder whose name
-# contains a space ("First Last" -> FIRST~1.LAS), a dot ("Stone.ZEN8" ->
-# STONE~1.ZEN), or an accented character ("Ruben" spelled with an acute e ->
-# RUBN~1). It can then expose %TEMP%, %TMP%, %LOCALAPPDATA%, %APPDATA% and
-# %USERPROFILE% -- plus everything derived from them, including the default
-# HERMES_HOME and InstallDir -- in that short form:
-# C:\Users\FIRST~1.LAS\AppData\Local\Temp
-#
-# PowerShell's FileSystem provider mishandles the aliased component when such a
-# path reaches a provider cmdlet (`Tee-Object -FilePath`, `Out-File`,
-# `New-Item`, `Test-Path`), throwing "An object at the specified path
-# C:\Users\FIRST~1.LAS does not exist" -- localized on non-English hosts.
-# Every Node/Electron stage streams its build log to %TEMP% via Tee-Object and
-# the desktop stage probes the binary it produced under the profile-derived
-# InstallDir, so the bootstrap aborts even though the artifact built fine.
-# The Python/uv stages, which never hand a %TEMP% path to a provider cmdlet,
-# sail through -- which is why the failure looks Node-specific.
-#
-# Expanding every profile-rooted path back to long form once, up front, lets
-# every downstream cmdlet and child process see something the provider can
-# resolve. Three resolvers, tried in order, because no single one covers every
-# host:
-#
-# 1. kernel32!GetLongPathNameW -- expands any 8.3 component regardless of
-# locale, including the accented-username aliases the COM resolver misses.
-# 2. Scripting.FileSystemObject -- fallback for hosts where P/Invoke is
-# blocked.
-# 3. Profile-root substitution -- when the volume has 8.3 generation disabled
-# or the alias is stale, neither resolver can expand the name because it
-# no longer maps to anything on disk. The aliased component is always the
-# profile folder itself (everything below it was created long), so swap in
-# a profile root we can prove is long and reattach the tail.
-#
-# All three degrade to returning the input untouched, so a host where none of
-# them apply -- including non-Windows -- behaves exactly as it did before.
-
-$script:LongProfileRoot = $null
-
-function Write-PathDiag {
- # Diagnostics for this block go to stderr, never stdout: the stage protocol
- # hands drivers a single line of JSON on stdout and a stray note would break
- # anything parsing it.
- #
- # Suppressed entirely under -ShowResolvedPaths, which is a machine-readable
- # query: Windows PowerShell 5.1 wraps any native-command stderr in a
- # NativeCommandError and folds it back into the caller's own stream, so a
- # child writing here at all is enough to corrupt a 5.1 caller's capture.
- # The JSON already carries everything these lines say.
- #
- # [Console]::Error.WriteLine specifically -- verified reaching a caller on a
- # windows-latest runner. $host.UI.WriteErrorLine was tried and silently
- # produced nothing there under a non-interactive host.
- param([string]$Message)
- if ($ShowResolvedPaths) { return }
- [Console]::Error.WriteLine("[hermes] $Message")
-}
-
-function Get-LongProfileRoot {
- # The user's profile directory in long form, or '' when every source we
- # can reach is itself aliased. Cached: this runs per env var.
- if ($null -ne $script:LongProfileRoot) { return $script:LongProfileRoot }
- $script:LongProfileRoot = ''
-
- # %USERPROFILE% first: it is what the rest of the install derives from, and
- # on a host handing us aliased paths the .NET known-folder lookup tends to
- # be aliased in exactly the same way. Then the HOMEDRIVE/HOMEPATH pair, then
- # the profile's parent (C:\Users never carries an alias) plus %USERNAME%,
- # which stays the long account name even when every path is short.
- $envProfile = [Environment]::GetEnvironmentVariable('USERPROFILE')
- $shellProfile = [Environment]::GetFolderPath('UserProfile')
- $candidates = @($envProfile, $shellProfile, "$env:HOMEDRIVE$env:HOMEPATH")
- foreach ($anchor in @($envProfile, $shellProfile)) {
- if ($anchor -and $env:USERNAME) {
- $parent = Split-Path -Parent $anchor.TrimEnd('\', '/')
- if ($parent) { $candidates += (Join-Path $parent $env:USERNAME) }
- }
- }
-
- foreach ($candidate in $candidates) {
- if ([string]::IsNullOrWhiteSpace($candidate)) { continue }
- # Trailing separators make Split-Path -Parent return the directory
- # itself, which would silently break the ancestry check downstream.
- $candidate = $candidate.TrimEnd('\', '/')
- if (-not $candidate) { continue }
- if ($candidate -match '~\d') { continue }
- try {
- if (Test-Path -LiteralPath $candidate -PathType Container) {
- $script:LongProfileRoot = $candidate
- break
- }
- } catch {
- # Unreadable candidate (denied, malformed): try the next one.
- }
- }
-
- # Say which root we landed on. When someone reports "still broken" this is
- # the first thing worth knowing, and it costs one line on the rare path
- # where an alias actually showed up.
- if ($script:LongProfileRoot) {
- Write-PathDiag "long profile root: $script:LongProfileRoot"
- } else {
- Write-PathDiag "no long profile root found; 8.3 paths left as-is (tried: $($candidates -join ', '))"
+# --- BEGIN GENERATED: bootstrap pins (scripts/gen-bootstrap-pins.py) ---
+# Derived from pm/lock.json. DO NOT EDIT BY HAND:
+# run scripts/gen-bootstrap-pins.py after a pin bump.
+$script:UvPinVersion = "0.12.3"
+$script:UvPinFiles = @{
+ "win32-x64" = @{
+ Url = "https://github.com/astral-sh/uv/releases/download/0.12.3/uv-x86_64-pc-windows-msvc.zip"
+ Sha256 = "b23350c79e8ad0192b8124af13a0f17e8d4e4549524785e1aef389ae5a06990e"
}
- return $script:LongProfileRoot
-}
-
-function Expand-ShortProfileRoot {
- # Rebuild $Path onto a known-long profile root when its aliased component
- # is the profile folder. Returns $Path unchanged when it isn't, so a custom
- # TEMP on another volume (D:\SHORT~1\Temp) is never rewritten.
- param([string]$Path)
-
- $longRoot = Get-LongProfileRoot
- if (-not $longRoot) { return $Path }
- $longRootParent = Split-Path -Parent $longRoot
- if (-not $longRootParent) { return $Path }
-
- $node = $Path
- $tail = ''
- while ($node -and ($node -match '~\d')) {
- $leaf = Split-Path -Leaf $node
- $parent = Split-Path -Parent $node
- if (-not $parent) { return $Path }
- if ($leaf -match '~\d') {
- # Candidate profile folder. Only substitute when it sits in the
- # same directory as the real profile (both C:\Users).
- if ($parent -ne $longRootParent) { return $Path }
- if ($tail) { return (Join-Path $longRoot $tail) }
- return $longRoot
- }
- $tail = if ($tail) { Join-Path $leaf $tail } else { $leaf }
- $node = $parent
+ "win32-arm64" = @{
+ Url = "https://github.com/astral-sh/uv/releases/download/0.12.3/uv-aarch64-pc-windows-msvc.zip"
+ Sha256 = "4343217d668727b8a8eb5cad92389a1d2eeead93c89940d1b955ba1bb15462eb"
}
- return $Path
}
-function ConvertTo-LongPath {
- param([string]$Path)
- if ([string]::IsNullOrWhiteSpace($Path)) { return $Path }
- # Only 8.3 short names carry a tilde+digit ("~1"); skip every resolver for
- # ordinary long paths, which is the overwhelmingly common case.
- if ($Path -notmatch '~\d') {
- $script:LastResolver = 'skipped-long-path'
- return $Path
- }
-
- # 1. kernel32. Compiled on first use only, so a normal profile never pays
- # the Add-Type cost (this file is re-entered once per install stage).
- try {
- if (-not ([System.Management.Automation.PSTypeName]'HermesInstall.LongPath').Type) {
- Add-Type -Namespace 'HermesInstall' -Name 'LongPath' -MemberDefinition @'
-[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
-public static extern int GetLongPathNameW(string lpszShortPath, System.Text.StringBuilder lpszLongPath, int cchBuffer);
-'@
- }
- $buffer = New-Object System.Text.StringBuilder 4096
- $length = [HermesInstall.LongPath]::GetLongPathNameW($Path, $buffer, $buffer.Capacity)
- if ($length -gt $buffer.Capacity) {
- $buffer = New-Object System.Text.StringBuilder $length
- $length = [HermesInstall.LongPath]::GetLongPathNameW($Path, $buffer, $buffer.Capacity)
- }
- if ($length -gt 0) {
- $expanded = $buffer.ToString()
- if ($expanded -and $expanded -notmatch '~\d') {
- $script:LastResolver = 'kernel32'
- return $expanded
- }
- }
- } catch {
- # Not Windows, or P/Invoke denied by policy: try the next resolver.
- }
-
- # 2. COM. Validate the result the same way the kernel32 branch does: this
- # resolver can report success and still hand back a path that carries the
- # alias (observed on a windows-latest runner, where it "resolved"
- # C:\Users\FIRST~1.LAS\... to itself). Accepting that silently is what let a
- # short path reach the provider cmdlets in the first place, so an
- # unexpanded result counts as failure and falls through.
- try {
- $fso = New-Object -ComObject Scripting.FileSystemObject
- $resolved = $null
- if ($fso.FolderExists($Path)) { $resolved = $fso.GetFolder($Path).Path }
- elseif ($fso.FileExists($Path)) { $resolved = $fso.GetFile($Path).Path }
- if ($resolved -and $resolved -notmatch '~\d') {
- $script:LastResolver = 'com'
- return $resolved
- }
- } catch {
- # COM unavailable / locked-down host: try the next resolver.
+$script:GitPinVersion = "2.53.0+3"
+$script:GitPinFiles = @{
+ "win32-x64" = @{
+ Url = "https://github.com/git-for-windows/git/releases/download/v2.53.0.windows.3/Git-2.53.0.3-64-bit.tar.bz2"
+ Sha256 = "1661f02e85a7901ad7920e2a358ee3772ed9066b00d8590bf2d9046ef10aa8b2"
}
-
- # 3. The alias resolves to nothing. Rebuild from a long profile root.
- $rebuilt = Expand-ShortProfileRoot $Path
- $script:LastResolver = if ($rebuilt -ne $Path) { 'profile-root' } else { 'none' }
- return $rebuilt
-}
-
-function Set-LongProfileEnvVars {
- # Normalize every profile-rooted variable the install reads, not just
- # %TEMP%: the desktop stage derives InstallDir from %LOCALAPPDATA%, and a
- # short root there fails the post-build probe after a successful build.
- # Returns $true when anything was rewritten.
- $rewrote = $false
- $script:NormalizedPathRewrites = @{}
- foreach ($name in @('TEMP', 'TMP', 'LOCALAPPDATA', 'APPDATA', 'USERPROFILE')) {
- $current = [Environment]::GetEnvironmentVariable($name)
- if (-not $current) { continue }
- $expanded = ConvertTo-LongPath $current
- if ($expanded -and $expanded -ne $current) {
- Set-Item -Path "Env:$name" -Value $expanded
- $rewrote = $true
- $script:NormalizedPathRewrites[$name] = $expanded
- # Rewriting a profile path is rare and corrective; say so. Every
- # report of this bug class arrived as a bare "does not exist" with
- # no hint that a short alias was involved. stderr, so the stage
- # protocol's stdout JSON stays parseable.
- Write-PathDiag "expanded 8.3 short path in %$name%: $current -> $expanded"
- }
+ "win32-arm64" = @{
+ Url = "https://github.com/git-for-windows/git/releases/download/v2.53.0.windows.3/Git-2.53.0.3-arm64.tar.bz2"
+ Sha256 = "4015f05a68bd2bcf3cc6c426e8d44b65d670fbb879225bb7b7c347cfc3a2758a"
}
- return $rewrote
-}
-
-# ConvertTo-LongPath only assigns $script:LastResolver when a ~\d short path
-# actually needs expansion, so an ordinary long profile leaves it unset -- and
-# the ResolvedPathReport below reads it unconditionally, which is fatal under
-# Set-StrictMode before any stage starts. 'none' is the resolver's own value
-# for "nothing ran".
-$script:LastResolver = 'none'
-$script:NormalizedProfilePaths = Set-LongProfileEnvVars
-
-# Re-derive the install paths now that the env vars behind their defaults are
-# long. An explicitly passed -HermesHome / -InstallDir is normalized in place
-# rather than replaced, so a caller's choice is never overwritten by a default.
-# $PSBoundParameters is only meaningful at script scope, so this stays inline.
-if ($PSBoundParameters.ContainsKey('HermesHome')) {
- $HermesHome = ConvertTo-LongPath $HermesHome
-} else {
- $HermesHome = ConvertTo-LongPath $(
- if ($env:HERMES_HOME) { $env:HERMES_HOME } else { "$env:LOCALAPPDATA\hermes" }
- )
-}
-if ($PSBoundParameters.ContainsKey('InstallDir')) {
- $InstallDir = ConvertTo-LongPath $InstallDir
-} else {
- $InstallDir = ConvertTo-LongPath $(
- if ($env:HERMES_HOME) { "$env:HERMES_HOME\hermes-agent" } else { "$env:LOCALAPPDATA\hermes\hermes-agent" }
- )
-}
-if ($script:NormalizedProfilePaths) {
- # Which paths the install actually settled on. Absent from every report of
- # this bug class, and the whole question once a short alias is in play.
- Write-PathDiag "resolved install paths: HermesHome=$HermesHome InstallDir=$InstallDir"
}
+# --- END GENERATED: bootstrap pins ---
-# Captured here, where the values are final, and emitted from the entry-point
-# dispatch at the bottom (alongside -ProtocolVersion / -Manifest) so
-# -ShowResolvedPaths exits before any stage runs.
-#
-# The report goes to STDOUT as JSON: on Windows a child's stderr does not
-# reliably reach a parent process -- three separate capture mechanisms each came
-# back empty on a windows-latest runner while stdout arrived intact -- and the
-# first question on any "installer says a path doesn't exist" report is which
-# paths it actually resolved.
-$script:ResolvedPathReport = @{
- long_profile_root = (Get-LongProfileRoot)
- normalized = $script:NormalizedPathRewrites
- resolver = $script:LastResolver
- temp = $env:TEMP
- hermes_home = $HermesHome
- install_dir = $InstallDir
+# Resolve the pm store root (same resolution as pm's store_root()):
+# $env:HERMES_RUNTIME_DIR wins, else <HermesHome>\tools.
+function Get-PmStoreRoot {
+ if ($env:HERMES_RUNTIME_DIR) { return $env:HERMES_RUNTIME_DIR }
+ return (Join-Path $HermesHome "tools")
}
-# ============================================================================
-# Configuration
-# ============================================================================
-
-$RepoUrlSsh = "[email protected]:NousResearch/hermes-agent.git"
-$RepoUrlHttps = "https://github.com/NousResearch/hermes-agent.git"
-$PythonVersion = "3.11"
-# Minor versions the installer accepts when the requested $PythonVersion isn't
-# available, in preference order. uv discovers both uv-managed and system
-# interpreters, so this list also matches a pre-existing system Python. Single
-# source of truth shared by Test-Python's fallback and Resolve-AvailablePythonVersion.
-$PythonFallbackVersions = @("3.12", "3.13", "3.10")
-$NodeVersion = "22"
-# The npm range the root package.json pins in `engines.npm`. A constant rather
-# than a manifest read like the POSIX side does: Test-Node runs BEFORE the repo
-# is cloned, so there is usually no package.json on disk yet (and none at all
-# when install.ps1 is piped straight from the web). Keep this fallback in sync
-# with package.json; Get-NpmRange prefers the manifest once a checkout exists.
-$NpmRange = "<11.10.0 || >=11.17.0"
-
-# Stage-protocol version. Bumped only for genuinely breaking changes to the
-# manifest schema, stage-name set semantics, or stdout JSON shape. Adding a
-# new stage does NOT bump this -- drivers iterate the manifest dynamically.
-$InstallStageProtocolVersion = 1
-
-# ============================================================================
-# Helper functions
-
-# Return the real OS processor architecture as a lowercase string suitable for
-# Node.js / electron download URL slugs: "arm64", "x64", or "x86".
-#
-# Why not just trust [Environment]::Is64BitOperatingSystem or
-# [RuntimeInformation]::OSArchitecture? On Windows on ARM, when this script
-# is invoked from Windows PowerShell 5.1 (the default `powershell.exe`) or
-# any x64 PowerShell host, the process runs under Prism x64 emulation and
-# BOTH of those APIs report `X64` -- they describe the emulated view, not
-# the real OS. We've seen this concretely on Snapdragon X1 hardware: an
-# ARM64-based Surface Laptop returns OSArchitecture=X64 from an emulated
-# PowerShell session.
-#
-# Win32_Processor.Architecture is invariant to emulation. Values:
-# 0=x86, 5=ARM, 9=AMD64/x64, 12=ARM64. We fall back to
-# PROCESSOR_ARCHITEW6432 (set on WoW64 with the real OS arch) and then
-# PROCESSOR_ARCHITECTURE so we still produce a sensible answer if CIM
-# isn't available (locked-down WMI, container, etc.).
+# The MACHINE's architecture (registry PROCESSOR_ARCHITECTURE), not the
+# interpreter's — an x64 powershell on Windows-on-ARM must stage arm64.
function Get-WindowsArch {
- try {
- $proc = Get-CimInstance -ClassName Win32_Processor -ErrorAction Stop |
- Select-Object -First 1
- switch ([int]$proc.Architecture) {
- 12 { return "arm64" }
- 9 { return "x64" }
- 0 { return "x86" }
- 5 { return "arm" }
- }
- } catch {
- # CIM unavailable -- fall through to env-var path
- }
-
- $envArch = if ($env:PROCESSOR_ARCHITEW6432) {
- $env:PROCESSOR_ARCHITEW6432
- } else {
- $env:PROCESSOR_ARCHITECTURE
- }
- switch ($envArch) {
- "ARM64" { return "arm64" }
- "AMD64" { return "x64" }
- "x86" { return "x86" }
- default {
- # Last-resort: respect 64-bitness so we don't ship a 32-bit
- # toolchain to anyone.
- if ([Environment]::Is64BitOperatingSystem) { return "x64" } else { return "x86" }
- }
- }
-}
-
-# ============================================================================
-
-function Write-Banner {
- Write-Host ""
- Write-Host "+---------------------------------------------------------+" -ForegroundColor Magenta
- Write-Host "| * Hermes Agent Installer |" -ForegroundColor Magenta
- Write-Host "+---------------------------------------------------------+" -ForegroundColor Magenta
- Write-Host "| An open source AI agent by Nous Research. |" -ForegroundColor Magenta
- Write-Host "+---------------------------------------------------------+" -ForegroundColor Magenta
- Write-Host ""
-}
-
-function Write-Info {
- param([string]$Message)
- Write-Host "-> $Message" -ForegroundColor Cyan
-}
-
-function Write-Success {
- param([string]$Message)
- Write-Host "[OK] $Message" -ForegroundColor Green
-}
-
-function Write-Warn {
- param([string]$Message)
- Write-Host "[!] $Message" -ForegroundColor Yellow
-}
-
-function Write-Err {
- param([string]$Message)
- Write-Host "[X] $Message" -ForegroundColor Red
-}
-
-function Invoke-NativeWithRelaxedErrorAction {
- param([scriptblock]$Script)
-
- $prevEAP = $ErrorActionPreference
- $ErrorActionPreference = "Continue"
- try {
- & $Script
+ $machineArch = (Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' -ErrorAction SilentlyContinue).PROCESSOR_ARCHITECTURE
+ if ($machineArch -eq 'ARM64') { return 'arm64' }
+ return 'x64'
+}
+
+# Provision uv for this host from the pinned pm/lock.json artifact. Stages
+# the EXACT artifact pm itself uses into the same store slot
+# (<store>\uv-<version>-<target>\), sha256-verified, so pm adopts the same
+# bytes — no astral-latest, no irm|iex. Returns the uv.exe path.
+function Get-Uv {
+ $existing = Get-Command uv -ErrorAction SilentlyContinue
+ if ($existing) { return $existing.Source } # dev shortcut; fetches nothing
+ $target = "win32-$(Get-WindowsArch)"
+ $pin = $script:UvPinFiles[$target]
+ if (-not $pin) {
+ Fail "no pinned uv artifact for $target; install uv manually: https://docs.astral.sh/uv/"
+ }
+ $entry = Join-Path (Get-PmStoreRoot) "uv-$($script:UvPinVersion)-$target"
+ $uvExe = Join-Path $entry "uv.exe"
+ if (Test-Path $uvExe) { return $uvExe }
+ Log "staging pinned uv $($script:UvPinVersion) ($target) into the pm store"
+ $tmpDir = Join-Path ([IO.Path]::GetTempPath()) "hermes-uv-bootstrap-$PID"
+ try {
+ New-Item -ItemType Directory -Force -Path $tmpDir | Out-Null
+ $zipPath = Join-Path $tmpDir "uv.zip"
+ Invoke-WebRequest -Uri $pin.Url -OutFile $zipPath -UseBasicParsing
+ # Digest check BEFORE extraction — a mismatched archive is deleted,
+ # never unpacked.
+ $digest = (Get-FileHash -Path $zipPath -Algorithm SHA256).Hash.ToLowerInvariant()
+ if ($digest -ne $pin.Sha256.ToLowerInvariant()) {
+ Fail "uv digest mismatch (expected $($pin.Sha256), got $digest)"
+ }
+ $extractDir = Join-Path $tmpDir "unpacked"
+ Expand-Archive -Path $zipPath -DestinationPath $extractDir -Force
+ # 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" }
+ 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
+ if ($uvx) { Move-Item -Path $uvx.FullName -Destination (Join-Path $entry "uvx.exe") -Force }
} finally {
- $ErrorActionPreference = $prevEAP
+ Remove-Item -Path $tmpDir -Recurse -Force -ErrorAction SilentlyContinue
+ }
+ if (-not (& $uvExe --version 2>$null)) { Fail "pinned uv staged but does not run on this host" }
+ return $uvExe
+}
+
+# Provision git for this host from the pinned pm/lock.json artifact, into
+# the same store slot (<store>\git-<version>-<target>\) pm uses. Returns the
+# git.exe path, or $null when no pinned artifact exists for this target.
+function Get-PinnedGit {
+ $existing = Get-Command git -ErrorAction SilentlyContinue
+ if ($existing) { return $existing.Source } # dev shortcut; fetches nothing
+ $target = "win32-$(Get-WindowsArch)"
+ $pin = $script:GitPinFiles[$target]
+ if (-not $pin) { return $null }
+ $entry = Join-Path (Get-PmStoreRoot) "git-$($script:GitPinVersion)-$target"
+ $gitExe = Join-Path $entry "cmd\git.exe"
+ if (Test-Path $gitExe) { return $gitExe }
+ Log "staging pinned git $($script:GitPinVersion) ($target) into the pm store"
+ $tmpDir = Join-Path ([IO.Path]::GetTempPath()) "hermes-git-bootstrap-$PID"
+ try {
+ New-Item -ItemType Directory -Force -Path $tmpDir | Out-Null
+ $tarPath = Join-Path $tmpDir "git.tar.bz2"
+ Invoke-WebRequest -Uri $pin.Url -OutFile $tarPath -UseBasicParsing
+ # Digest check BEFORE extraction — the archive IS code.
+ $digest = (Get-FileHash -Path $tarPath -Algorithm SHA256).Hash.ToLowerInvariant()
+ if ($digest -ne $pin.Sha256.ToLowerInvariant()) {
+ Fail "git digest mismatch (expected $($pin.Sha256), got $digest)"
+ }
+ $extractDir = Join-Path $tmpDir "unpacked"
+ New-Item -ItemType Directory -Force -Path $extractDir | Out-Null
+ # The pinned artifact is a git-for-windows tar.bz2 (the same one pm
+ # itself extracts). Windows 10+ ships bsdtar with bzip2 support.
+ & tar.exe -xf $tarPath -C $extractDir
+ if ($LASTEXITCODE) { Fail "failed to extract pinned git archive" }
+ # Layout: Git-<ver>/cmd\git.exe — flatten the single wrapper dir.
+ $inner = @(Get-ChildItem $extractDir)
+ $src = $extractDir
+ if ($inner.Count -eq 1 -and $inner[0].PSIsContainer) { $src = $inner[0].FullName }
+ if (-not (Test-Path (Join-Path $src "cmd\git.exe"))) { Fail "git.exe not found in the downloaded archive" }
+ if (Test-Path $entry) { Remove-Item -Recurse -Force $entry }
+ Move-Item $src $entry
+ } finally {
+ Remove-Item -Path $tmpDir -Recurse -Force -ErrorAction SilentlyContinue
}
+ return $gitExe
}
-function Discard-LockfileChurn {
- param([string]$Repo = $InstallDir)
-
- if (-not $Repo -or -not (Test-Path (Join-Path $Repo ".git"))) { return }
-
- try {
- $diff = & git -c windows.appendAtomically=false -C $Repo diff --name-only 2>$null
- if ($LASTEXITCODE -ne 0 -or -not $diff) { return }
-
- $dirtyPackageDirs = [System.Collections.Generic.HashSet[string]]::new(
- [System.StringComparer]::OrdinalIgnoreCase
- )
- foreach ($path in $diff) {
- if ($path -like "*package.json") {
- $null = $dirtyPackageDirs.Add((Split-Path $path -Parent))
- }
- }
- $dirtyLocks = [System.Collections.Generic.List[string]]::new()
- foreach ($path in $diff) {
- if ($path -notlike "*package-lock.json") { continue }
- $lockDir = Split-Path $path -Parent
- if ($dirtyPackageDirs.Contains($lockDir)) { continue }
- $dirtyLocks.Add($path)
- }
-
- if ($dirtyLocks.Count -eq 0) { return }
- & git -c windows.appendAtomically=false -C $Repo checkout -- @($dirtyLocks) 2>$null
- if ($LASTEXITCODE -eq 0) {
- Write-Info "Discarded npm lockfile churn ($($dirtyLocks.Count) file(s))"
- }
- } catch {
- # Best-effort only; never let cleanup block the installer update path.
+# Ensure a usable git for the rest of the ladder: pinned pm store slot
+# first, then PATH. Returns $true on success.
+function Ensure-Git {
+ $g = Get-PinnedGit
+ if (-not $g) { return $false }
+ if ($g -ne "git") {
+ # Store-staged git: expose cmd + usr\bin on this process's PATH so
+ # bare `git` works for the rest of the ladder (the same dirs pm's
+ # git package env() composes).
+ $gitEntry = Split-Path (Split-Path $g -Parent) -Parent
+ $env:Path = "$gitEntry\cmd;$gitEntry\usr\bin;$env:Path"
}
-}
-# Inspect npm output for a TLS-trust failure and, if found, print actionable
-# remediation. npm/Node surface corporate MITM proxies and missing root CAs as
-# "unable to get local issuer certificate" / "self-signed certificate in
-# certificate chain" / UNABLE_TO_GET_ISSUER_CERT_LOCALLY -- most commonly while
-# Electron's install.js postinstall downloads the Electron binary. The reporter
-# usually misreads this as an admin-rights or generic install failure (see
-# issue #38016), so detect it once here and route every npm stage through this
-# hint. Returns $true when a cert error was detected (caller may adjust its own
-# messaging), $false otherwise.
-function Show-NpmCertHint {
- param([string]$NpmOutput)
- if (-not $NpmOutput) { return $false }
- $isCertError = $NpmOutput -match "unable to get local issuer certificate" `
- -or $NpmOutput -match "self.signed certificate" `
- -or $NpmOutput -match "UNABLE_TO_GET_ISSUER_CERT_LOCALLY" `
- -or $NpmOutput -match "SELF_SIGNED_CERT_IN_CHAIN" `
- -or $NpmOutput -match "CERT_HAS_EXPIRED"
- if (-not $isCertError) { return $false }
- Write-Warn "This looks like a TLS certificate-trust failure, not a permissions problem."
- Write-Info " A corporate proxy or antivirus is likely intercepting HTTPS and presenting a"
- Write-Info " certificate Node.js doesn't trust. To fix, point Node at your org's root CA:"
- Write-Info " 1. Get the corporate root CA as a .pem/.crt from your IT team."
- Write-Info " 2. setx NODE_EXTRA_CA_CERTS `"C:\path\to\corp-ca.pem`""
- Write-Info " 3. Open a NEW terminal (so the env var takes effect) and re-run the installer."
- Write-Info " Quick (less secure) alternative -- disable TLS verification just for the install:"
- Write-Info " npm config set strict-ssl false (re-enable afterwards: npm config set strict-ssl true)"
return $true
}
-function Write-NpmDebugLogTail {
- # On failure npm prints only a terse summary to stdout/stderr; the real
- # evidence (postinstall script stderr like Electron's install.js, network
- # traces, EBUSY retries) lives in npm's own debug log under
- # <npm-cache>\_logs\<timestamp>-debug-0.log. The bootstrap installer's
- # streaming sink only captures what WE emit, so on any npm failure this
- # helper locates that debug log and replays its tail into our output
- # stream -- making the bootstrap log a self-contained diagnosis instead
- # of "exit 1, details in a file on a VM nobody can reach".
- param(
- [string]$NpmOutput,
- [int]$TailLines = 200
- )
- $logPath = $null
- # Preferred: npm names the exact file in its failure summary.
- if ($NpmOutput -and $NpmOutput -match "A complete log of this run can be found in:\s*(?<path>[^\r\n]+)") {
- $candidate = $Matches['path'].Trim()
- if (Test-Path -LiteralPath $candidate) { $logPath = $candidate }
- }
- # Fallback (covers --silent runs, truncated output): newest debug log in
- # npm's cache _logs directory.
- if (-not $logPath) {
- try {
- $npm = Resolve-NpmCmd
- if ($npm) {
- $prevEAPLocal = $ErrorActionPreference
- $ErrorActionPreference = "Continue"
- $cacheDir = (& $npm config get cache 2>$null | Select-Object -Last 1)
- $ErrorActionPreference = $prevEAPLocal
- if ($cacheDir) {
- $logsDir = Join-Path ("$cacheDir").Trim() "_logs"
- if (Test-Path -LiteralPath $logsDir) {
- $newest = Get-ChildItem -LiteralPath $logsDir -Filter "*-debug-*.log" -ErrorAction SilentlyContinue |
- Sort-Object LastWriteTime -Descending | Select-Object -First 1
- if ($newest) { $logPath = $newest.FullName }
- }
- }
- }
- } catch { }
- }
- if (-not $logPath) {
- Write-Warn "npm debug log could not be located -- no further npm detail available"
- return
- }
- $tail = $null
- try {
- $tail = Get-Content -LiteralPath $logPath -Tail $TailLines -ErrorAction Stop
- } catch {
- Write-Warn "Could not read npm debug log ${logPath}: $($_.Exception.Message)"
- return
- }
- Write-Warn "---- npm debug log: last $TailLines lines of $logPath ----"
- foreach ($line in $tail) { Write-Host " $line" -ForegroundColor DarkGray }
- Write-Warn "---- end npm debug log ----"
-}
-
-# --- Ensure-mode helpers ---
-
-function Resolve-NpmCmd {
- $npmCmd = Get-Command npm -ErrorAction SilentlyContinue
- if (-not $npmCmd) { return $null }
- $npmExe = $npmCmd.Source
- if ($npmExe -like "*.ps1") {
- $npmCmdSibling = Join-Path (Split-Path $npmExe -Parent) "npm.cmd"
- if (Test-Path $npmCmdSibling) { return $npmCmdSibling }
- }
- return $npmExe
-}
-
-function Find-SystemBrowser {
- # Honor ONLY an explicit, user-set AGENT_BROWSER_EXECUTABLE_PATH override.
- #
- # We no longer scan well-known install locations for a system browser.
- # Auto-detection silently bound the install to an arbitrary binary instead
- # of the bundled Playwright Chromium, which made the browser tool behave
- # differently across hosts (and, on Linux, picked up a sandboxed Snap
- # Chromium that hangs every browser_navigate). Every install now uses the
- # bundled Chromium unless the user explicitly points elsewhere.
- $override = $env:AGENT_BROWSER_EXECUTABLE_PATH
- if ([string]::IsNullOrWhiteSpace($override)) { return $null }
- if (Test-Path $override) { return $override }
- return $null
-}
+function Log([string]$msg) { Write-Host "[hermes] $msg" -ForegroundColor Blue }
+function Fail([string]$msg) { Write-Host "[hermes] $msg" -ForegroundColor Red; exit 1 }
-function Write-BrowserEnv {
- param([string]$BrowserPath)
- if (-not (Test-Path $HermesHome)) {
- New-Item -ItemType Directory -Force -Path $HermesHome | Out-Null
- }
- $envFile = Join-Path $HermesHome ".env"
- if (-not (Test-Path $envFile)) {
- Set-Content -Path $envFile -Value "AGENT_BROWSER_EXECUTABLE_PATH=$BrowserPath" -Encoding UTF8
- return
- }
- $content = Get-Content $envFile -Raw -ErrorAction SilentlyContinue
- if ($content -and $content -match "AGENT_BROWSER_EXECUTABLE_PATH=") { return }
- Add-Content -Path $envFile -Value "AGENT_BROWSER_EXECUTABLE_PATH=$BrowserPath" -Encoding UTF8
+function Emit-Frame([bool]$ok, [string]$name, [bool]$skipped, [string]$reason = "") {
+ $frame = [ordered]@{ ok = $ok; stage = $name; skipped = $skipped }
+ if ($reason) { $frame.reason = $reason }
+ $frame | ConvertTo-Json -Compress | Write-Output
}
-function Install-AgentBrowser {
- $npm = Resolve-NpmCmd
- if (-not $npm) {
- Write-Err "npm not found -- install Node.js first"
- throw "npm not found"
- }
-
- # agent-browser itself is intentionally NOT installed here (#43564 /
- # PR #44772 review): it resolves lazily via `npx agent-browser` instead,
- # which every consumer (tools/browser_tool.py, `hermes update`'s npx
- # cache warm) already goes through. Eagerly npm-installing a second,
- # separately version-pinned copy here -- only reachable via this
- # explicit -Ensure browser fallback in the first place -- was redundant
- # complexity and an extra credential/supply-chain surface for a path
- # npx already covers.
- Write-Info "Installing camofox browser server..."
- $prefixDir = Join-Path $HermesHome "node"
- if (-not (Test-Path $prefixDir)) {
- New-Item -ItemType Directory -Path $prefixDir -Force | Out-Null
- }
- $npmLog = [System.IO.Path]::GetTempFileName()
- $prevEAP = $ErrorActionPreference
- $ErrorActionPreference = "Continue"
- & $npm install -g --prefix $prefixDir --silent --ignore-scripts "@askjo/camofox-browser@^1.5.2" 2>&1 | Tee-Object -FilePath $npmLog | Out-Null
- $npmExit = $LASTEXITCODE
- $ErrorActionPreference = $prevEAP
- if ($npmExit -ne 0) {
- $npmDetail = Get-Content $npmLog -Raw -ErrorAction SilentlyContinue
- Remove-Item $npmLog -Force -ErrorAction SilentlyContinue
- Write-Err "npm install -g failed (exit $npmExit): $npmDetail"
- Show-NpmCertHint $npmDetail | Out-Null
- # This install runs with --silent, so $npmDetail is often near-empty;
- # npm's debug log is the only place the real error survives.
- Write-NpmDebugLogTail -NpmOutput $npmDetail
- throw "npm install failed"
- }
- Remove-Item $npmLog -Force -ErrorAction SilentlyContinue
-
- $sysBrowser = Find-SystemBrowser
- if ($sysBrowser) {
- Write-BrowserEnv -BrowserPath $sysBrowser
- Write-Info "Explicit browser override set -- Chromium download will be skipped when agent-browser installs on demand"
- }
- Write-Success "Agent-browser ready"
+$Stages = @(
+ @{ name = "prerequisites"; title = "System prerequisites"; category = "runtime"; needs_user_input = $false },
+ @{ name = "repository"; title = "Download Hermes Agent"; category = "runtime"; needs_user_input = $false },
+ @{ name = "venv"; title = "Create Python environment"; category = "runtime"; needs_user_input = $false },
+ @{ name = "python-deps"; title = "Install Python dependencies"; category = "runtime"; needs_user_input = $false },
+ @{ name = "node-deps"; title = "Install tool dependencies"; category = "runtime"; needs_user_input = $false },
+ @{ name = "path"; title = "Install hermes command"; category = "runtime"; needs_user_input = $false },
+ @{ name = "config"; title = "Prepare config and skills"; category = "configuration"; needs_user_input = $false },
+ @{ name = "setup"; title = "Configure API keys and settings"; category = "configuration"; needs_user_input = $true },
+ @{ name = "gateway"; title = "Configure gateway service"; category = "configuration"; needs_user_input = $true }
+)
+if ($IncludeDesktop) {
+ $Stages += @{ name = "desktop"; title = "Build desktop app"; category = "runtime"; needs_user_input = $false }
}
+$Stages += @{ name = "complete"; title = "Finish install"; category = "runtime"; needs_user_input = $false }
-# ============================================================================
-# Dependency checks
-# ============================================================================
-
-# Resolve the PowerShell host executable used to spawn child PowerShell
-# processes (the astral uv installer below). We must NOT hardcode the bare
-# name `powershell`: it names *Windows PowerShell* and only resolves when its
-# System32 directory is on PATH. When install.ps1 is run under PowerShell 7+
-# (`pwsh`) -- or any session where `powershell` isn't on PATH -- a bare
-# `powershell` spawn dies with "The term 'powershell' is not recognized",
-# aborting uv installation (field report: Windows install stuck, uv install
-# failed with exactly that message). Prefer the absolute path of the host we
-# are already running in (PATH-independent), then fall back to whichever of
-# powershell/pwsh is resolvable, and only then to the bare name.
-function Get-PowerShellHostExe {
- try {
- $hostExe = (Get-Process -Id $PID).Path
- if ($hostExe -and (Test-Path $hostExe)) {
- $leaf = Split-Path $hostExe -Leaf
- # Only trust the current host when it is a real PowerShell CLI
- # (not e.g. powershell_ise.exe or an embedded host that can't take
- # `-ExecutionPolicy`/`-Command`).
- if ($leaf -match '^(?i:powershell|pwsh)\.exe$') { return $hostExe }
- }
- } catch { }
- foreach ($candidate in @("powershell", "pwsh")) {
- $cmd = Get-Command $candidate -CommandType Application -ErrorAction SilentlyContinue |
- Select-Object -First 1
- if ($cmd -and $cmd.Source) { return $cmd.Source }
+function Stage-Prerequisites {
+ if (-not (Ensure-Git)) {
+ Fail "git is required. Install Git for Windows: https://git-scm.com/download/win"
}
- # Last-ditch: hand back the bare name so the spawn surfaces its own error.
- return "powershell"
+ Log "prerequisites ok (git)"
}
-function Install-Uv {
- # Hermes owns its own uv at $HermesHome\bin\uv.exe. Always install there --
- # no PATH probing, no conda guards, no multi-location resolution chains.
- # The runtime update path (hermes_cli/managed_uv.py) looks in the same
- # place, so install.ps1 and `hermes update` stay in sync.
- $managedUv = Join-Path $HermesHome "bin\uv.exe"
-
- if (Test-Path $managedUv) {
- $script:UvCmd = $managedUv
- $version = & $managedUv --version
- Write-Success "Managed uv found ($version)"
- return $true
+function Stage-Repository {
+ if (Test-Path (Join-Path $InstallDir ".git")) {
+ Log "updating $InstallDir"
+ git -C $InstallDir fetch origin $Branch; if ($LASTEXITCODE) { Fail "git fetch failed" }
+ git -C $InstallDir checkout $Branch; if ($LASTEXITCODE) { Fail "git checkout failed" }
+ git -C $InstallDir pull --ff-only origin $Branch
+ if ($LASTEXITCODE) { Log "not fast-forwardable; keeping local state" }
+ } else {
+ Log "cloning $RepoUrl ($Branch) into $InstallDir"
+ New-Item -ItemType Directory -Force -Path (Split-Path $InstallDir) | Out-Null
+ git clone --branch $Branch $RepoUrl $InstallDir; if ($LASTEXITCODE) { Fail "git clone failed" }
}
-
- Write-Info "Installing managed uv into $HermesHome\bin ..."
- New-Item -ItemType Directory -Path (Join-Path $HermesHome "bin") -Force | Out-Null
-
- # UV_INSTALL_DIR tells the astral installer to place the binary
- # directly into $HermesHome\bin instead of ~/.local/bin.
- $prevEAP = $ErrorActionPreference
- try {
- $ErrorActionPreference = "Continue"
- $env:UV_INSTALL_DIR = Join-Path $HermesHome "bin"
- # Spawn via the resolved host exe (see Get-PowerShellHostExe) rather
- # than a bare `powershell`, which isn't guaranteed to be on PATH under
- # PowerShell 7 / pwsh-only setups.
- $psHostExe = Get-PowerShellHostExe
-
- # Rungs 1 + 2: run the uv installer -- astral.sh first, then the
- # byte-identical copy published on GitHub releases. Corporate
- # proxies and AV products frequently block astral.sh while
- # github.com is reachable (issue #69216), so a second source turns
- # a hard failure into a working install. Capture the installer
- # output (Tee-Object) instead of discarding it: when every source
- # fails, the real error (download blocked, AV quarantine,
- # permissions) must reach the user instead of only the generic
- # "installed but not found" message.
- $installerOutput = @()
- $astralOut = @()
- & $psHostExe -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" 2>&1 | Tee-Object -Variable astralOut | Out-Null
- $installerOutput += "--- uv installer source: astral.sh ---"
- $installerOutput += @($astralOut | ForEach-Object { "$_" })
- if (Test-Path $managedUv) {
- Write-Info "uv installer succeeded via astral.sh"
- } else {
- Write-Info "astral.sh uv installer did not produce $managedUv; trying GitHub releases mirror ..."
- $ghOut = @()
- & $psHostExe -ExecutionPolicy ByPass -c "irm https://github.com/astral-sh/uv/releases/latest/download/uv-installer.ps1 | iex" 2>&1 | Tee-Object -Variable ghOut | Out-Null
- $installerOutput += "--- uv installer source: GitHub releases ---"
- $installerOutput += @($ghOut | ForEach-Object { "$_" })
- if (Test-Path $managedUv) {
- Write-Info "uv installer succeeded via GitHub releases"
- }
- }
-
- # Rung 3: salvage an existing uv.exe. When the installer cannot run
- # at all (network fully blocked) but a working uv already exists --
- # on PATH, or at ~/.local/bin (the astral default location when
- # UV_INSTALL_DIR was ignored by an older installer) -- copy it into
- # the managed location so the managed-first invariant holds
- # (hermes_cli/managed_uv.py looks only at $HermesHome\bin\uv.exe).
- if (-not (Test-Path $managedUv)) {
- $existingUv = $null
- $uvOnPath = Get-Command uv -CommandType Application -ErrorAction SilentlyContinue |
- Select-Object -First 1
- if ($uvOnPath -and $uvOnPath.Source -and (Test-Path $uvOnPath.Source)) {
- $existingUv = $uvOnPath.Source
- }
- if (-not $existingUv) {
- $defaultUv = Join-Path $env:USERPROFILE ".local\bin\uv.exe"
- if (Test-Path $defaultUv) { $existingUv = $defaultUv }
- }
- if ($existingUv) {
- Write-Info "Salvaging existing uv from $existingUv"
- try {
- Copy-Item $existingUv $managedUv -Force
- # Verify the salvaged binary actually runs before
- # trusting it as the managed uv.
- $null = & $managedUv --version
- } catch {
- Write-Info "Existing uv at $existingUv could not be salvaged: $_"
- Remove-Item $managedUv -Force -ErrorAction SilentlyContinue
- }
- }
- }
-
- $ErrorActionPreference = $prevEAP
-
- if (Test-Path $managedUv) {
- $script:UvCmd = $managedUv
- $version = & $managedUv --version
- Write-Success "Managed uv installed ($version)"
- return $true
- }
-
- Write-Err "uv installed but not found at $managedUv"
- if ($installerOutput.Count -gt 0) {
- Write-Info "uv installer output (last 15 lines):"
- $installerOutput | Select-Object -Last 15 | ForEach-Object { Write-Info " $_" }
- }
- Write-Info "Install manually: https://docs.astral.sh/uv/getting-started/installation/"
- return $false
- } catch {
- if ($prevEAP) { $ErrorActionPreference = $prevEAP }
- Write-Err "Failed to install uv: $_"
- Write-Info "Install manually: https://docs.astral.sh/uv/getting-started/installation/"
- return $false
+ if ($Commit) {
+ git -C $InstallDir checkout $Commit; if ($LASTEXITCODE) { Fail "could not pin commit $Commit" }
}
}
-# Refresh $env:Path from the User + Machine registry hives. Stage drivers
-# invoke each stage in a fresh powershell process, but those processes
-# inherit env from the parent driver shell, NOT from the registry. When
-# an earlier stage (Stage-Git, Stage-Node, ...) installs a binary and
-# pushes its directory into User PATH, the next child process's $env:Path
-# is stale and the binary appears missing. This helper re-reads PATH
-# from the registry so every Invoke-Stage starts from a fresh, up-to-date
-# PATH view. Cheap (registry reads, no I/O elsewhere) and idempotent.
-function Sync-EnvPath {
- $env:Path = [Environment]::GetEnvironmentVariable("Path", "User") + ";" + [Environment]::GetEnvironmentVariable("Path", "Machine")
-}
-
-# npm lifecycle scripts on Windows spawn ``cmd.exe /d /s /c node <script>``.
-# PowerShell can resolve ``node`` via Get-Command while the child cmd process
-# still sees a PATH without node.exe's directory (nvm4w shims, App Paths
-# aliases, stale cross-process PATH). Prepend the resolved node.exe parent
-# directory so postinstall hooks (electron-winstaller, native modules, etc.)
-# can find ``node``. Regression for #48130.
-function Ensure-NodeExeOnPath {
- $nodeCmd = Get-Command node -ErrorAction SilentlyContinue
- if (-not $nodeCmd) { return $false }
-
- $nodeExeDir = Split-Path $nodeCmd.Source -Parent
- if (-not $nodeExeDir) { return $false }
-
- $pathParts = $env:Path -split ";"
- if ($pathParts -notcontains $nodeExeDir) {
- $env:Path = "$nodeExeDir;$env:Path"
- }
- return $true
+function Stage-Venv {
+ $uv = Get-Uv
+ Log "creating venv"
+ Push-Location $InstallDir
+ & $uv venv --allow-existing venv; $code = $LASTEXITCODE
+ Pop-Location
+ if ($code) { Fail "uv venv failed" }
}
-# Put the Hermes-managed Node dir at the FRONT of the persisted User PATH.
-#
-# Appending is not enough: it leaves a pre-existing system Node ahead of the
-# bundled one in every new shell, so anything launched without a curated
-# environment (a standalone hermes-setup.exe run, a user typing `npm`) silently
-# resolves the wrong Node. Bundled must win.
-#
-# Move-to-front rather than add-if-missing, because installs made by an older
-# install.ps1 already have this dir in User PATH -- at the tail. An
-# add-if-missing check sees it present and leaves the broken ordering in place
-# forever, so the very users the ordering bug hurt would never be repaired.
-#
-# Unrelated entries keep their relative order, including empty segments (a
-# trailing ';' is legal and common in a real User PATH; Install-Git's splitting
-# preserves them too, so this must not quietly rewrite them). Duplicate
-# occurrences of the managed dir collapse into the single leading entry.
-# PowerShell's -ne is case-insensitive for strings, which is the right
-# comparison on Windows. Persists only when the resulting string differs, so
-# an already-correct PATH costs one registry read and no write.
-function Set-ManagedNodeFirstOnUserPath {
- param([string]$NodeDir)
-
- if (-not $NodeDir) { return }
-
+function Stage-PythonDeps {
+ $uv = Get-Uv
+ Log "syncing python dependencies (uv sync --frozen)"
+ Push-Location $InstallDir
+ $env:VIRTUAL_ENV = Join-Path $InstallDir "venv"
+ & $uv sync --frozen --extra all --active; $code = $LASTEXITCODE
+ Remove-Item Env:VIRTUAL_ENV -ErrorAction SilentlyContinue
+ Pop-Location
+ if ($code) { Fail "uv sync failed" }
+}
+
+function Stage-NodeDeps {
+ Log "tool dependencies are managed by pm (hermes pm install)"
+}
+
+function Stage-Path {
+ $binDir = Join-Path $HermesHome "bin"
+ New-Item -ItemType Directory -Force -Path $binDir | Out-Null
+ # Mint the boot launchers (hermes / hermes-acp) bound to the pm STORE
+ # python with PYTHONPATH=repo;venv-site-packages — never the venv
+ # python (no boot through the venv; pyvenv.cfg is inert dead config).
+ # The venv python below is install-time machinery (the materializer),
+ # not a boot path. On a fresh install the store interpreter does not
+ # exist yet, so a runtime-resolving .cmd delegator is staged;
+ # hermes_cli/_install_repair.py upgrades it to an exe once
+ # `hermes pm install` materializes the store.
+ $venvPython = Join-Path $InstallDir "venv\Scripts\python.exe"
+ if (-not (Test-Path $venvPython)) { Fail "venv python missing at $venvPython" }
+ Push-Location $InstallDir
+ & $venvPython -c "from hermes_cli._launchers import ensure_install_launchers; import sys; written = ensure_install_launchers(r'$InstallDir', r'$binDir'); print(';'.join(written)); sys.exit(0 if written else 1)"
+ $code = $LASTEXITCODE
+ Pop-Location
+ if ($code) { Fail "launcher staging failed" }
$userPath = [Environment]::GetEnvironmentVariable("Path", "User")
- $items = if ($userPath) { @($userPath -split ";") } else { @() }
-
- $rest = @($items | Where-Object { $_ -ne $NodeDir })
- $updated = (@($NodeDir) + $rest) -join ";"
-
- if ($updated -ne $userPath) {
- [Environment]::SetEnvironmentVariable("Path", $updated, "User")
+ if ($userPath -notlike "*$binDir*") {
+ [Environment]::SetEnvironmentVariable("Path", "$binDir;$userPath", "User")
+ Log "added $binDir to your user PATH (new shells pick it up)"
}
+ Log "hermes command installed at $binDir"
}
-# The npm range to install into the managed Node tree. Prefers the checkout's
-# root package.json so the installer and the manifest cannot drift; falls back
-# to the $NpmRange constant, which is the common case here because Test-Node
-# runs before the repo is cloned.
-function Get-NpmRange {
- $manifest = Join-Path $InstallDir "package.json"
- if (Test-Path $manifest) {
- try {
- $engines = (Get-Content $manifest -Raw | ConvertFrom-Json).engines
- if ($engines -and $engines.npm) { return [string]$engines.npm }
- } catch { }
+function Stage-Config {
+ foreach ($d in @("cron","sessions","logs","pairing","hooks","image_cache","audio_cache","memories","skills")) {
+ New-Item -ItemType Directory -Force -Path (Join-Path $HermesHome $d) | Out-Null
}
- return $NpmRange
-}
-
-# Convert the numeric core of an npm version or range operand into a stable
-# three-component System.Version. npm reports semantic versions, but the
-# installer only needs the numeric core for the comparator ranges authored in
-# package.json (for example, <11.10.0 || >=11.17.0).
-function ConvertTo-NpmVersion {
- param([string]$Version)
-
- if (-not $Version) { return $null }
-
- $core = ($Version.Trim() -replace '^v', '' -replace '-.*$', '')
- $parts = @($core -split '\.')
- if ($parts.Count -lt 1 -or $parts.Count -gt 3) { return $null }
- foreach ($part in $parts) {
- if ($part -notmatch '^\d+$') { return $null }
- }
- while ($parts.Count -lt 3) { $parts += '0' }
-
- try {
- return [version]($parts -join '.')
- } catch {
- return $null
+ $envFile = Join-Path $HermesHome ".env"
+ if (-not (Test-Path $envFile)) {
+ $example = Join-Path $InstallDir ".env.example"
+ if (Test-Path $example) { Copy-Item $example $envFile } else { New-Item -ItemType File -Path $envFile | Out-Null }
}
+ $cfg = Join-Path $HermesHome "config.yaml"
+ $cfgExample = Join-Path $InstallDir "cli-config.yaml.example"
+ if (-not (Test-Path $cfg) -and (Test-Path $cfgExample)) { Copy-Item $cfgExample $cfg }
+ Log "config prepared in $HermesHome"
}
-# Evaluate the comparator-only npm ranges used by the root manifest and the
-# pre-clone fallback. Alternatives are separated with || and each alternative
-# may contain one or more whitespace-separated <, <=, >, or >= comparators.
-# Unknown range syntax fails closed so an incompatible system npm cannot reach
-# npm ci and fail later with EBADENGINE.
-function Test-NpmVersionOk {
- param(
- [string]$Version,
- [string]$Range = (Get-NpmRange)
- )
-
- $actual = ConvertTo-NpmVersion $Version
- if (-not $actual -or -not $Range) { return $false }
-
- foreach ($alternative in @($Range -split '\s*\|\|\s*')) {
- $clause = $alternative.Trim()
- if (-not $clause) { continue }
-
- $comparators = [regex]::Matches(
- $clause,
- '(?:^|\s)(<=|>=|<|>)\s*(\d+(?:\.\d+){0,2})(?=\s|$)'
- )
- if ($comparators.Count -eq 0) { continue }
-
- $remainder = [regex]::Replace(
- $clause,
- '(?:^|\s)(?:<=|>=|<|>)\s*\d+(?:\.\d+){0,2}(?=\s|$)',
- ''
- ).Trim()
- if ($remainder) { continue }
-
- $matchesClause = $true
- foreach ($comparator in $comparators) {
- $target = ConvertTo-NpmVersion $comparator.Groups[2].Value
- if (-not $target) {
- $matchesClause = $false
- break
- }
-
- $matchesComparator = switch ($comparator.Groups[1].Value) {
- '<' { $actual -lt $target }
- '<=' { $actual -le $target }
- '>' { $actual -gt $target }
- '>=' { $actual -ge $target }
- default { $false }
- }
- if (-not $matchesComparator) {
- $matchesClause = $false
- break
- }
- }
-
- if ($matchesClause) { return $true }
- }
-
- return $false
+function Stage-Setup {
+ if ($NonInteractive) { return }
+ & (Join-Path $InstallDir "venv\Scripts\python.exe") (Join-Path $InstallDir "hermes") setup
}
-# Upgrade the Hermes-managed Node tree's bundled npm into $NpmRange when
-# needed. Managed Node trees survive updates, so their bundled npm can drift
-# outside a newer root package.json engine range. The repo .npmrc sets
-# `engine-strict=true`, making that mismatch fatal at the first `npm ci`.
-# Provision the right npm here instead of reacting to EBADENGINE later.
-#
-# Three details are load-bearing, mirroring _nb_ensure_bundled_npm_range in
-# scripts/lib/node-bootstrap.sh and upgrade_managed_npm in
-# hermes_cli/npm_engine.py:
-# - a temp cwd, so the checkout's own .npmrc (engine-strict,
-# min-release-age) does not gate the very upgrade meant to satisfy it;
-# - npm_config_min_release_age=0, which also neutralises a user ~/.npmrc;
-# - an explicit --prefix at the managed tree, so the upgrade rewrites the
-# tree's own npm rather than installing a second copy elsewhere.
-#
-# Best-effort: a failure leaves a working Node with an old npm, which beats no
-# Node at all, and npm_engine.py still covers the EBADENGINE that follows.
-function Update-ManagedNpm {
- param([string]$NodeDir)
-
- $npmCmd = Join-Path $NodeDir "npm.cmd"
- if (-not (Test-Path $npmCmd)) { return $false }
-
- $range = Get-NpmRange
-
- # Skip the network round-trip when the bundled npm already satisfies the
- # same range used by the system-Node acceptance gate.
- try {
- $have = (& $npmCmd --version 2>$null | Select-Object -First 1)
- if ($have -and (Test-NpmVersionOk $have $range)) { return $true }
- } catch { }
-
- # In-app updates run while the desktop app's Node processes are alive.
- # The managed npm lives inside the very tree they execute from, so an
- # in-place upgrade would hit WinError 5 (Access denied) on npm.cmd
- # (#80926). Defer; the next update with the app closed retries.
- if (Test-ManagedNodeInUse $NodeDir) {
- Write-Warn "Hermes-managed Node.js is in use by a running app; skipping the bundled npm upgrade (applies on a later update with the app closed)."
- return $false
- }
-
- Write-Info "Upgrading bundled npm to satisfy $range ..."
-
- $tmpCwd = Join-Path $env:TEMP ("hermes-npm-upgrade-" + [Guid]::NewGuid().ToString("N"))
- New-Item -ItemType Directory -Force -Path $tmpCwd | Out-Null
- $prevAge = $env:npm_config_min_release_age
- $prevCI = $env:CI
- $prevEAP = $ErrorActionPreference
- Push-Location $tmpCwd
- try {
- $env:npm_config_min_release_age = "0"
- $env:CI = "1"
- # Relax EAP=Stop so npm's stderr lines don't get wrapped as
- # ErrorRecords and short-circuit before $LASTEXITCODE is checked.
- # Same pattern as Install-Uv.
- $ErrorActionPreference = "Continue"
- & $npmCmd install --global --prefix $NodeDir "npm@$range" `
- --no-fund --no-audit --progress=false 2>&1 | Out-Null
- $exit = $LASTEXITCODE
- } catch {
- $exit = 1
- } finally {
- $ErrorActionPreference = $prevEAP
- Pop-Location
- $env:npm_config_min_release_age = $prevAge
- $env:CI = $prevCI
- Remove-Item -Recurse -Force $tmpCwd -ErrorAction SilentlyContinue
- }
-
- if ($exit -ne 0) {
- Write-Warn "Could not upgrade bundled npm to $range -- ``npm ci`` may fail with EBADENGINE."
- Write-Info "Fix manually: npm install -g --prefix `"$NodeDir`" npm@`"$range`""
- return $false
- }
-
- Write-Success "npm $(& $npmCmd --version 2>$null) installed"
- return $true
+function Stage-Gateway {
+ if ($NonInteractive) { return }
+ & (Join-Path $InstallDir "venv\Scripts\python.exe") (Join-Path $InstallDir "hermes") gateway install
}
-function Test-ManagedNodeInUse {
- param([string]$NodeDir)
- # Windows locks files that running processes execute from. During an
- # in-app update the desktop app's Node processes may hold the managed
- # tree open, and rewriting it then fails with WinError 5 (Access denied)
- # on npm.cmd (#80926). Cheap pre-check used to skip destructive steps;
- # the rename/move itself remains the authoritative guard.
- #
- # Check the executable path AND the command line: a cmd.exe wrapper
- # running npm.cmd from the tree reports its own exe (cmd.exe lives in
- # System32) while the tree path appears only in the command line.
- # Win32_Process.CommandLine is available on Windows PowerShell 5.1 and
- # 7+ (the Get-Process .CommandLine ETS property is 7.4+ only), and a
- # single CIM query beats a per-process property access loop.
- return @(
- Get-CimInstance Win32_Process -ErrorAction SilentlyContinue |
- Where-Object {
- ($_.ExecutablePath -like "$NodeDir\*") -or
- ($_.CommandLine -like "*$NodeDir*")
- }
- ).Count -gt 0
+function Stage-Desktop {
+ & (Join-Path $InstallDir "venv\Scripts\python.exe") (Join-Path $InstallDir "hermes") desktop build
+ if ($LASTEXITCODE) { Fail "desktop build failed" }
}
-# Re-discover uv without re-installing it. Cross-process stage drivers
-# (the desktop GUI's onboarding wizard, CI step-runners) invoke each stage
-# in a fresh powershell process, so $script:UvCmd set by Install-Uv in a
-# prior process is not visible here. Later stages (Test-Python,
-# Install-Venv, Install-Dependencies, Install-PlatformSdks) call this
-# at the top to populate $script:UvCmd from the managed location.
-# Throws if uv is not findable -- the caller's stage then surfaces a
-# clean error via the stage-driver's try/catch.
-function Resolve-UvCmd {
- # Already resolved (default invocation path: Install-Uv ran earlier
- # in the same process and set $script:UvCmd).
- if ($script:UvCmd) {
- if ($script:UvCmd -eq "uv") {
- # "uv" on PATH -- verify it's still resolvable (PATH could have
- # changed mid-session; cheap to recheck).
- if (Get-Command uv -ErrorAction SilentlyContinue) { return }
- } elseif (Test-Path $script:UvCmd) {
- return
+function Stage-Complete {
+ $commit = $Commit
+ if (-not $commit) { $commit = git -C $InstallDir rev-parse HEAD 2>$null }
+ if ($commit) {
+ $marker = [ordered]@{
+ schemaVersion = 1
+ pinnedCommit = "$commit"
+ pinnedBranch = $Branch
+ completedAt = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ")
}
- # Stale; fall through to re-discover.
- }
-
- # Check the managed location first -- this is where Install-Uv puts it.
- $managedUv = Join-Path $HermesHome "bin\uv.exe"
- if (Test-Path $managedUv) {
- $script:UvCmd = $managedUv
- return
- }
-
- # Fall back to PATH (covers edge cases where the installer ran in a
- # sibling process and HERMES_HOME wasn't propagated).
- if (Get-Command uv -ErrorAction SilentlyContinue) {
- $script:UvCmd = "uv"
- return
+ $markerPath = Join-Path $InstallDir ".hermes-bootstrap-complete"
+ $tmp = "$markerPath.tmp"
+ $marker | ConvertTo-Json | Set-Content -Path $tmp -Encoding utf8
+ Move-Item -Force $tmp $markerPath
}
-
- # Refresh PATH from registry in case the current process started before
- # Install-Uv updated User PATH.
- $env:Path = [Environment]::GetEnvironmentVariable("Path", "User") + ";" + [Environment]::GetEnvironmentVariable("Path", "Machine")
- if (Get-Command uv -ErrorAction SilentlyContinue) {
- $script:UvCmd = "uv"
- return
- }
-
- throw "uv is not installed. Run install.ps1 -Stage uv first."
+ Log "install complete. Run: hermes"
}
-function Resolve-AvailablePythonVersion {
- # Return the first Python minor version uv can actually find, preferring the
- # requested $PythonVersion and then $PythonFallbackVersions. Returns $null
- # when none are available.
- #
- # This is the cross-process-safe counterpart to Test-Python's in-memory
- # ``$script:PythonVersion = $fallbackVer`` mutation. Under Hermes-Setup.exe
- # each ``-Stage NAME`` runs in a *fresh* powershell.exe, so the fallback the
- # ``python`` stage settled on (e.g. 3.12 when 3.11 is absent) does NOT
- # survive into the ``venv`` stage's process -- there $PythonVersion is back
- # at its "3.11" default. Consumers re-resolve here instead of trusting that
- # default, which is exactly the propagation gap behind issue #50769.
- $candidates = @($PythonVersion) + $PythonFallbackVersions
- $seen = @{}
- foreach ($ver in $candidates) {
- if (-not $ver -or $seen.ContainsKey($ver)) { continue }
- $seen[$ver] = $true
- try {
- $found = & $UvCmd python find $ver 2>$null
- if ($found) { return $ver }
- } catch { }
+function Invoke-StageByName([string]$name) {
+ switch ($name) {
+ "prerequisites" { Stage-Prerequisites }
+ "repository" { Stage-Repository }
+ "venv" { Stage-Venv }
+ "python-deps" { Stage-PythonDeps }
+ "node-deps" { Stage-NodeDeps }
+ "path" { Stage-Path }
+ "config" { Stage-Config }
+ "setup" { Stage-Setup }
+ "gateway" { Stage-Gateway }
+ "desktop" { Stage-Desktop }
+ "complete" { Stage-Complete }
+ default { Write-Error "unknown stage: $name"; exit 2 }
}
- return $null
}
-function Test-Python {
- Write-Info "Checking Python $PythonVersion..."
-
- # Let uv find or install Python
- try {
- $pythonPath = & $UvCmd python find $PythonVersion 2>$null
- if ($pythonPath) {
- $ver = & $pythonPath --version 2>$null
- Write-Success "Python found: $ver"
- return $true
- }
- } catch { }
-
- # Python not found -- use uv to install it (no admin needed!)
- Write-Info "Python $PythonVersion not found, installing via uv..."
- # Capture EAP outside the try block so the catch's restore call always
- # has a meaningful value (see Install-Uv for the full rationale).
- $prevEAP = $ErrorActionPreference
- try {
- # Temporarily relax ErrorActionPreference: uv writes download progress
- # ("Downloading cpython-3.11.15-windows-x86_64-none (24.5MiB)") to
- # stderr. With $ErrorActionPreference = "Stop" (set at the top of this
- # script) PowerShell wraps stderr lines from native commands as
- # ErrorRecord objects when captured via 2>&1, then throws a terminating
- # exception on the first one -- even though uv exits 0 and Python was
- # installed successfully. Verify success via `uv python find`
- # afterwards, which is the reliable signal regardless of exit-code
- # semantics or stderr noise. This fix was previously landed as
- # commit ec1714e71 and then lost in a release squash; reapplied here.
- $ErrorActionPreference = "Continue"
- $uvOutput = & $UvCmd python install $PythonVersion 2>&1
- $uvExitCode = $LASTEXITCODE
- $ErrorActionPreference = $prevEAP
-
- # Check if Python is now available (more reliable than exit code
- # since uv may return non-zero due to "already installed" etc.)
- $pythonPath = & $UvCmd python find $PythonVersion 2>$null
- if ($pythonPath) {
- $ver = & $pythonPath --version 2>$null
- Write-Success "Python installed: $ver"
- return $true
- }
-
- # uv ran but Python still not findable -- show what happened
- if ($uvExitCode -ne 0) {
- Write-Warn "uv python install output:"
- Write-Host $uvOutput -ForegroundColor DarkGray
- }
- } catch {
- # Restore EAP in case the try block threw before the assignment
- if ($prevEAP) { $ErrorActionPreference = $prevEAP }
- Write-Warn "uv python install error: $_"
- }
-
- # Fallback: check if ANY Python 3.10+ is already available on the system
- Write-Info "Trying to find any existing Python 3.10+..."
- foreach ($fallbackVer in $PythonFallbackVersions) {
- try {
- $pythonPath = & $UvCmd python find $fallbackVer 2>$null
- if ($pythonPath) {
- $ver = & $pythonPath --version 2>$null
- Write-Success "Found fallback: $ver"
- $script:PythonVersion = $fallbackVer
- return $true
- }
- } catch { }
- }
-
- # Fallback: try system python -- but skip the Microsoft Store stub.
- # On Windows, %LOCALAPPDATA%\Microsoft\WindowsApps\python.exe is a 0-byte
- # reparse-point stub that prints "Python was not found; run without
- # arguments to install from the Microsoft Store..." to stdout and exits
- # non-zero. Get-Command finds it; invoking it produces a confusing error
- # that the user sees as our installer crashing.
- $pythonCmd = Get-Command python -ErrorAction SilentlyContinue
- if ($pythonCmd) {
- $isStoreStub = $false
- try {
- $pythonSource = $pythonCmd.Source
- if ($pythonSource -and $pythonSource -like "*\WindowsApps\*") {
- $isStoreStub = $true
- } else {
- # Even outside WindowsApps, a 0-byte file is the stub
- $item = Get-Item $pythonSource -ErrorAction SilentlyContinue
- if ($item -and $item.Length -eq 0) { $isStoreStub = $true }
- }
- } catch { }
-
- if (-not $isStoreStub) {
- try {
- $prevEAP2 = $ErrorActionPreference
- $ErrorActionPreference = "Continue"
- $sysVer = & python --version 2>&1
- $ErrorActionPreference = $prevEAP2
- if ($sysVer -match "Python 3\.(1[0-9]|[1-9][0-9])") {
- Write-Success "Using system Python: $sysVer"
- return $true
- }
- } catch {
- if ($prevEAP2) { $ErrorActionPreference = $prevEAP2 }
- }
- }
- }
+if ($ProtocolVersion) { Write-Output 1; exit 0 }
- Write-Err "Failed to install Python $PythonVersion"
- Write-Info "Install Python 3.11 manually, then re-run this script:"
- Write-Info " https://www.python.org/downloads/"
- Write-Info " Or: winget install Python.Python.3.11"
- return $false
+if ($Manifest) {
+ @{ protocol_version = 1; stages = $Stages } | ConvertTo-Json -Depth 4 -Compress | Write-Output
+ exit 0
}
-$script:GitInstallFailureReason = $null
-$script:GitBashPath = $null
-$script:GitBashProbeOutput = $null
-
-function Test-GitBashCompatibility {
- <#
- .SYNOPSIS
- Verify that Git Bash can launch external MSYS programs, not just evaluate
- shell builtins. Mandatory ASLR can allow bash.exe itself to start while
- every child linked to msys-2.0.dll fails during fork/spawn.
- #>
- param([Parameter(Mandatory = $true)][string]$BashPath)
-
- $script:GitBashProbeOutput = $null
- if (-not (Test-Path -LiteralPath $BashPath)) {
- $script:GitBashProbeOutput = "bash.exe was not found at $BashPath"
- return $false
+if ($Stage) {
+ $known = @($Stages | ForEach-Object { $_.name })
+ if ($known -notcontains $Stage -and $Stage -ne "desktop") {
+ if ($Json) { Emit-Frame $false $Stage $false "unknown stage: $Stage" }
+ else { [Console]::Error.WriteLine("unknown stage: $Stage") }
+ exit 2
}
-
- $process = New-Object System.Diagnostics.Process
- try {
- $startInfo = New-Object System.Diagnostics.ProcessStartInfo
- $startInfo.FileName = $BashPath
- $startInfo.Arguments = '--noprofile --norc -c "/usr/bin/true; /usr/bin/cat --version >/dev/null"'
- $startInfo.UseShellExecute = $false
- $startInfo.CreateNoWindow = $true
- $startInfo.RedirectStandardOutput = $true
- $startInfo.RedirectStandardError = $true
- $process.StartInfo = $startInfo
-
- if (-not $process.Start()) {
- $script:GitBashProbeOutput = "bash.exe did not start"
- return $false
- }
- if (-not $process.WaitForExit(15000)) {
- try { $process.Kill() } catch { }
- $script:GitBashProbeOutput = "Git Bash compatibility probe timed out"
- return $false
- }
-
- $stdout = $process.StandardOutput.ReadToEnd()
- $stderr = $process.StandardError.ReadToEnd()
- $script:GitBashProbeOutput = ("$stdout`n$stderr").Trim()
- return ($process.ExitCode -eq 0)
- } catch {
- $script:GitBashProbeOutput = $_.Exception.Message
- return $false
- } finally {
- $process.Dispose()
+ $needsInput = ($Stage -eq "setup") -or ($Stage -eq "gateway")
+ if ($NonInteractive -and $needsInput) {
+ if ($Json) { Emit-Frame $true $Stage $true "needs user input" }
+ exit 0
}
-}
-
-function Test-MandatoryAslrEnabled {
- <# Return true only when Windows reports system-wide ForceRelocateImages=ON. #>
try {
- $cmd = Get-Command Get-ProcessMitigation -ErrorAction SilentlyContinue
- if (-not $cmd) { return $false }
- $mitigations = & $cmd -System
- $value = $mitigations.Aslr.ForceRelocateImages
- return ($null -ne $value -and $value.ToString().ToUpperInvariant() -eq "ON")
+ Invoke-StageByName $Stage
+ if ($Json) { Emit-Frame $true $Stage $false }
+ exit 0
} catch {
- return $false
- }
-}
-
-function Get-GitRootFromBashPath {
- param([Parameter(Mandatory = $true)][string]$BashPath)
-
- $binDir = Split-Path -Path $BashPath -Parent
- if ((Split-Path -Path $binDir -Leaf) -ine "bin") {
- return (Split-Path -Path $binDir -Parent)
- }
-
- $parent = Split-Path -Path $binDir -Parent
- if ((Split-Path -Path $parent -Leaf) -ieq "usr") {
- return (Split-Path -Path $parent -Parent)
+ if ($Json) { Emit-Frame $false $Stage $false "$_" }
+ exit 1
}
- return $parent
-}
-
-function New-GitBashAslrFailureReason {
- param([Parameter(Mandatory = $true)][string]$BashPath)
-
- $gitRoot = Get-GitRootFromBashPath -BashPath $BashPath
- $escapedRoot = $gitRoot -replace "'", "''"
- return @(
- "Git Bash at $BashPath cannot launch required MSYS child processes because Windows Mandatory ASLR (ForceRelocateImages) is enabled system-wide. Reinstalling Git will not change this policy."
- "Open PowerShell as Administrator and run:"
- "`$gitRoot = '$escapedRoot'"
- 'Get-Item "$gitRoot\bin\bash.exe", "$gitRoot\usr\bin\*.exe" -ErrorAction SilentlyContinue | ForEach-Object { Set-ProcessMitigation -Name $_.FullName -Disable ForceRelocateImages }'
- "Then rerun Hermes setup. If the override is blocked or later re-applied, ask your Windows administrator to allow this per-program exception."
- ) -join [Environment]::NewLine
}
-function Install-Git {
- <#
- .SYNOPSIS
- Ensure Git (and Git Bash) are installed. Git for Windows bundles bash.exe
- which Hermes uses to run shell commands.
-
- Priority order (deliberately simple -- no winget, no registry, no system
- package manager):
- 1. Existing ``git`` on PATH -- use it as-is (the common fast path).
- 2. Download **PortableGit** from the official git-for-windows GitHub
- release (self-extracting 7z.exe) and unpack it to
- ``%LOCALAPPDATA%\hermes\git`` -- never touches system Git, never
- requires admin, works even on locked-down machines and machines
- with a broken system Git install.
-
- **Why PortableGit, not MinGit:** MinGit is the minimal-automation
- distribution and ships ONLY ``git.exe`` -- no bash, no POSIX utilities.
- Hermes needs ``bash.exe`` to run shell commands. PortableGit is the
- full Git for Windows distribution without the installer UI; it ships
- ``git.exe`` + ``bash.exe`` + ``sh``, ``awk``, ``sed``, ``grep``, ``curl``,
- ``ssh``, etc. in ``usr\bin\``.
-
- We deliberately skip winget because it fails badly when the system Git
- install is in a half-installed state (partially registered, or uninstall-
- blocked). Owning the Hermes copy of Git ourselves is predictable and
- recoverable: if it ever breaks, ``Remove-Item %LOCALAPPDATA%\hermes\git``
- and re-running this installer fully recovers.
-
- After install we locate ``bash.exe`` and persist the path in
- ``HERMES_GIT_BASH_PATH`` (User scope) so Hermes can find it in a fresh
- shell without a second PATH refresh.
- #>
- $script:GitInstallFailureReason = $null
- Write-Info "Checking Git..."
-
- if (Get-Command git -ErrorAction SilentlyContinue) {
- $version = git --version
- Write-Success "Git found ($version)"
- Set-GitBashEnvVar
- if ($script:GitBashPath -and (Test-GitBashCompatibility -BashPath $script:GitBashPath)) {
- Write-Success "Git Bash can launch MSYS programs"
- return $true
- }
-
- if ($script:GitBashPath -and (Test-MandatoryAslrEnabled)) {
- $script:GitInstallFailureReason = New-GitBashAslrFailureReason -BashPath $script:GitBashPath
- Write-Err $script:GitInstallFailureReason
- return $false
- }
-
- if ($script:GitBashPath) {
- $probeDetail = if ($script:GitBashProbeOutput) { ": $script:GitBashProbeOutput" } else { "" }
- Write-Warn "System Git Bash could not launch required MSYS programs$probeDetail"
- } else {
- Write-Warn "Git is on PATH, but its Git Bash installation could not be located."
- }
- Write-Info "Trying a Hermes-managed PortableGit install instead..."
- }
-
- # Download PortableGit into $HermesHome\git. Always works as long as
- # we can reach github.com -- no admin, no winget, no reliance on the
- # user's possibly-broken system Git install.
- Write-Info "Git not found -- downloading PortableGit to $HermesHome\git\ ..."
- Write-Info "(no admin rights required; isolated from any system Git install)"
-
- try {
- $arch = Get-WindowsArch
- if ($arch -eq 'arm64') {
- $assetTag = 'arm64'
- $downloadIsZip = $false
- } elseif ($arch -eq 'x64') {
- $assetTag = '64-bit'
- $downloadIsZip = $false
- } else {
- # PortableGit does not ship 32-bit / arm builds -- fall back to MinGit
- # 32-bit with a warning that bash-based features will be unavailable.
- $assetTag = '32-bit-mingit'
- $downloadIsZip = $true
- }
-
- # Pinned git-for-windows release. We deliberately do NOT hit
- # api.github.com/repos/.../releases/latest here: that endpoint
- # is rate-limited to 60 requests/hour/IP for unauthenticated
- # callers, and users behind CGNAT / corporate NAT / dorm WiFi
- # routinely hit the limit, breaking the installer.
- # Static github.com/.../releases/download/<tag>/<asset> URLs
- # are not subject to the API rate limit.
- $gitTag = "v2.54.0.windows.1"
- $gitVer = "2.54.0"
- $gitVerTag = "$gitVer.windows.1"
-
- if ($arch -eq "32-bit-mingit") {
- Write-Warn "32-bit Windows detected -- PortableGit is 64-bit only. Installing MinGit 32-bit as a last resort; bash-dependent Hermes features (terminal tool, agent-browser) will not work on this machine."
- $assetName = "MinGit-$gitVer-32-bit.zip"
- $downloadIsZip = $true
- } elseif ($arch -eq "arm64") {
- $assetName = "PortableGit-$gitVer-arm64.7z.exe"
- $downloadIsZip = $false
- } else {
- $assetName = "PortableGit-$gitVer-64-bit.7z.exe"
- $downloadIsZip = $false
- }
-
- $downloadUrl = "https://github.com/git-for-windows/git/releases/download/$gitTag/$assetName"
- $downloadExt = if ($downloadIsZip) { "zip" } else { "7z.exe" }
- $tmpFile = "$env:TEMP\$assetName"
- $gitDir = "$HermesHome\git"
-
- Write-Info "Downloading $assetName (Git for Windows $gitVerTag)..."
- Invoke-WebRequest -Uri $downloadUrl -OutFile $tmpFile -UseBasicParsing
-
- if (Test-Path $gitDir) {
- Write-Info "Removing previous Git install at $gitDir ..."
- Remove-Item -Recurse -Force $gitDir
- }
- New-Item -ItemType Directory -Path $gitDir -Force | Out-Null
-
- if ($downloadIsZip) {
- Expand-Archive -Path $tmpFile -DestinationPath $gitDir -Force
- } else {
- # PortableGit is a self-extracting 7z archive. Invoke it with
- # `-o<target> -y` (silent) to extract to $gitDir. No 7z install
- # required; it's fully self-contained.
- Write-Info "Extracting PortableGit to $gitDir ..."
- $extractProc = Start-Process -FilePath $tmpFile `
- -ArgumentList "-o`"$gitDir`"", "-y" `
- -NoNewWindow -Wait -PassThru
- if ($extractProc.ExitCode -ne 0) {
- throw "PortableGit extraction failed (exit code $($extractProc.ExitCode))"
- }
- }
- Remove-Item -Force $tmpFile -ErrorAction SilentlyContinue
-
- # PortableGit layout: cmd\git.exe + bin\bash.exe + usr\bin\ (coreutils)
- # MinGit layout: cmd\git.exe + usr\bin\bash.exe (if present)
- $gitExe = "$gitDir\cmd\git.exe"
- if (-not (Test-Path $gitExe)) {
- throw "Git extraction did not produce git.exe at $gitExe"
- }
-
- # Add to session PATH so the rest of this install run can use git.
- $env:Path = "$gitDir\cmd;$env:Path"
-
- # Persist to User PATH so fresh shells see it. PortableGit needs
- # cmd\ (for git.exe), bin\ (for bash.exe + core tools), and
- # usr\bin\ (for perl, ssh, curl, and other POSIX coreutils).
- $newPathEntries = @(
- "$gitDir\cmd",
- "$gitDir\bin",
- "$gitDir\usr\bin"
- )
- $userPath = [Environment]::GetEnvironmentVariable("Path", "User")
- $userPathItems = if ($userPath) { $userPath -split ";" } else { @() }
- $changed = $false
- foreach ($entry in $newPathEntries) {
- if ($userPathItems -notcontains $entry) {
- $userPathItems += $entry
- $changed = $true
- }
- }
- if ($changed) {
- [Environment]::SetEnvironmentVariable("Path", ($userPathItems -join ";"), "User")
- }
-
- $version = & $gitExe --version
- Write-Success "Git $version installed to $gitDir (portable, user-scoped)"
- Set-GitBashEnvVar
- if (-not $script:GitBashPath) {
- throw "PortableGit extraction did not produce a usable bash.exe"
- }
- if (-not (Test-GitBashCompatibility -BashPath $script:GitBashPath)) {
- if (Test-MandatoryAslrEnabled) {
- $script:GitInstallFailureReason = New-GitBashAslrFailureReason -BashPath $script:GitBashPath
- } else {
- $probeDetail = if ($script:GitBashProbeOutput) { " Probe output: $script:GitBashProbeOutput" } else { "" }
- $script:GitInstallFailureReason = "Git Bash at $script:GitBashPath exists but cannot launch required MSYS programs.$probeDetail"
- }
- throw $script:GitInstallFailureReason
- }
- Write-Success "Git Bash can launch MSYS programs"
- return $true
- } catch {
- if ($script:GitInstallFailureReason) {
- Write-Err $script:GitInstallFailureReason
- return $false
- }
- Write-Err "Could not install portable Git: $_"
- Write-Info ""
- Write-Info "Fallback: install Git manually from https://git-scm.com/download/win"
- Write-Info "then re-run this installer. Hermes needs Git Bash on Windows to run"
- Write-Info "shell commands (same as Claude Code and other coding agents)."
- return $false
- }
-}
-
-function Set-GitBashEnvVar {
- <#
- .SYNOPSIS
- Locate ``bash.exe`` from an already-installed Git and persist the path in
- ``HERMES_GIT_BASH_PATH`` (User env scope) so Hermes can find it even before
- PATH propagation completes in a newly-spawned shell.
- #>
- $script:GitBashPath = $null
- $candidates = @()
-
- # Our own portable Git install is ALWAYS checked first, so a broken
- # system Git doesn't hijack us. If the user had a working system Git
- # we'd have returned early from Install-Git's fast path and never called
- # this with a system-Git-only installation anyway.
- #
- # Layouts:
- # PortableGit (our default): $HermesHome\git\bin\bash.exe
- # MinGit (32-bit fallback): $HermesHome\git\usr\bin\bash.exe
- $candidates += "$HermesHome\git\bin\bash.exe" # PortableGit layout (primary)
- $candidates += "$HermesHome\git\usr\bin\bash.exe" # MinGit / PortableGit usr\bin fallback
-
- # git.exe on PATH can tell us where the install root is
- $gitCmd = Get-Command git -ErrorAction SilentlyContinue
- if ($gitCmd) {
- $gitExe = $gitCmd.Source
- # Git for Windows (full installer): <root>\cmd\git.exe + <root>\bin\bash.exe
- # MinGit: <root>\cmd\git.exe + <root>\usr\bin\bash.exe
- $gitRoot = Split-Path (Split-Path $gitExe -Parent) -Parent
- $candidates += "$gitRoot\bin\bash.exe"
- $candidates += "$gitRoot\usr\bin\bash.exe"
- }
-
- # Standard system install locations as a final fallback. Note:
- # ProgramFiles(x86) can't be referenced via ${env:...} string interpolation
- # because of the parens -- use [Environment]::GetEnvironmentVariable().
- $candidates += "${env:ProgramFiles}\Git\bin\bash.exe"
- $pf86 = [Environment]::GetEnvironmentVariable("ProgramFiles(x86)")
- if ($pf86) { $candidates += "$pf86\Git\bin\bash.exe" }
- $candidates += "${env:LocalAppData}\Programs\Git\bin\bash.exe"
-
- foreach ($candidate in $candidates) {
- if ($candidate -and (Test-Path $candidate)) {
- [Environment]::SetEnvironmentVariable("HERMES_GIT_BASH_PATH", $candidate, "User")
- $env:HERMES_GIT_BASH_PATH = $candidate
- $script:GitBashPath = $candidate
- Write-Info "Set HERMES_GIT_BASH_PATH=$candidate"
- return
- }
- }
-
- Write-Warn "Could not locate bash.exe -- Hermes may not find Git Bash."
- Write-Info "If needed, set HERMES_GIT_BASH_PATH manually to your bash.exe path."
-}
-
-# The dependency tree supports Node 22.22+, 24.11+, and 26+. nanoid 6 excludes
-# Node 23 and 25 while its >=26 arm accepts later releases, and @babel/* 8.x
-# requires ^22.18.0 || >=24.11.0 -- so accepting 23/25 or an early Node 24
-# only defers the failure to `npm ci` under engine-strict. Keep this in sync
-# with the root package.json.
-function Test-NodeVersionOk {
- param([string]$Version)
- if ($Version -match '-') { return $false }
- try {
- $v = [version]($Version -replace '^v', '')
- } catch {
- return $false
- }
- if ($v.Major -eq 22) { return ($v.Minor -ge 22) }
- if ($v.Major -eq 24) { return ($v.Minor -ge 11) }
- return ($v.Major -ge 26)
-}
-
-# Accept a system Node only when its companion npm also satisfies the same
-# range used to provision the Hermes-managed tree. Keeping this probe separate
-# lets the initial PATH check and the post-winget check share one authority.
-function Test-SystemNodeReady {
- if (-not (Get-Command node -ErrorAction SilentlyContinue)) { return $false }
-
- $version = node --version
- if (Test-NodeVersionOk $version) {
- Ensure-NodeExeOnPath | Out-Null
- } else {
- Write-Warn "Node.js $version is unsupported (Hermes requires Node 22.22+, 24.11+, or 26+)"
- return $false
- }
-
- $npmRange = Get-NpmRange
- $npmCmd = Get-Command npm.cmd -ErrorAction SilentlyContinue
- if (-not $npmCmd) {
- $npmCmd = Get-Command npm -ErrorAction SilentlyContinue
- }
-
- $npmVersion = $null
- if ($npmCmd) {
- try {
- $npmVersion = (& $npmCmd --version 2>$null | Select-Object -First 1)
- } catch { }
- }
-
- if ($npmVersion -and (Test-NpmVersionOk $npmVersion $npmRange)) {
- Write-Success "Node.js $version with npm $npmVersion found"
- return $true
- }
-
- if ($npmVersion) {
- Write-Warn "Node.js $version uses npm $npmVersion, which does not satisfy Hermes requirement $npmRange"
- } else {
- Write-Warn "Node.js $version was found, but npm is missing or could not report its version"
- }
- return $false
-}
-
-function Test-Node {
- Write-Info "Checking Node.js (for browser tools)..."
-
- if (Test-SystemNodeReady) {
- $script:HasNode = $true
- return $true
- }
-
- Write-Info "Using a Hermes-managed Node.js installation instead..."
-
- # Prefer a Hermes-managed Node from a previous run over a too-old system one.
- $managedNode = "$HermesHome\node\node.exe"
- if ((Test-Path $managedNode) -and (Test-NodeVersionOk (& $managedNode --version))) {
- $version = & $managedNode --version
- $env:Path = "$HermesHome\node;$env:Path"
- Set-ManagedNodeFirstOnUserPath "$HermesHome\node"
- Write-Success "Node.js $version found (Hermes-managed)"
- # A tree from an older install still has that Node major's bundled
- # npm, which is below the current engines.npm floor. No-ops when the
- # npm is already in range, so reruns cost one --version probe.
- Update-ManagedNpm "$HermesHome\node" | Out-Null
- $script:HasNode = $true
- return $true
- }
-
- Write-Info "Installing Hermes-managed Node.js $NodeVersion LTS..."
-
- # Try the portable-zip path FIRST -- no UAC, no admin, no winget MSI.
- # winget install OpenJS.NodeJS.LTS triggers a system-wide MSI install
- # which prompts UAC (the dialog often appears minimized in the taskbar
- # and the install silently waits for consent, looking like a hang).
- # The portable zip path drops node.exe + npm into $HermesHome\node\
- # which is user-scoped and identical to how Install-Git handles
- # PortableGit. Same UX guarantee: works on locked-down enterprise
- # machines with no admin rights.
- Write-Info "Downloading portable Node.js $NodeVersion to $HermesHome\node\ ..."
- Write-Info "(no admin rights required; isolated from any system Node install)"
- try {
- $arch = Get-WindowsArch
- $indexUrl = "https://nodejs.org/dist/latest-v${NodeVersion}.x/"
- $indexPage = Invoke-WebRequest -Uri $indexUrl -UseBasicParsing
- $zipName = ($indexPage.Content | Select-String -Pattern "node-v${NodeVersion}\.\d+\.\d+-win-${arch}\.zip" -AllMatches).Matches[0].Value
-
- if ($zipName) {
- $downloadUrl = "${indexUrl}${zipName}"
- $tmpZip = "$env:TEMP\$zipName"
- $tmpDir = "$env:TEMP\hermes-node-extract"
-
- Invoke-WebRequest -Uri $downloadUrl -OutFile $tmpZip -UseBasicParsing
- if (Test-Path $tmpDir) { Remove-Item -Recurse -Force $tmpDir }
- Expand-Archive -Path $tmpZip -DestinationPath $tmpDir -Force
-
- $extractedDir = Get-ChildItem $tmpDir -Directory | Select-Object -First 1
- if ($extractedDir) {
- # Rename-swap instead of delete-then-move: the live tree is
- # never removed before its replacement is fully extracted.
- # Windows permits renaming a tree with running executables,
- # but if a process holds it without FILE_SHARE_DELETE the
- # rename fails with WinError 5 -- that refusal means the tree
- # is in use, so defer instead of forcing the write (#80926).
- # Best-effort sweep of staging/backup litter from interrupted
- # runs; locked files simply stay for the next attempt. Only
- # dirs older than 10 minutes are removed so a concurrent
- # heal's in-flight swap is never disturbed.
- Get-ChildItem "$HermesHome" -Directory -Filter "node.old-*" -ErrorAction SilentlyContinue |
- Where-Object { $_.LastWriteTime -lt (Get-Date).AddMinutes(-10) } |
- Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
- Get-ChildItem "$HermesHome" -Directory -Filter "node.new-*" -ErrorAction SilentlyContinue |
- Where-Object { $_.LastWriteTime -lt (Get-Date).AddMinutes(-10) } |
- Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
- $stamp = [Guid]::NewGuid().ToString("N")
- $staged = "$HermesHome\node.new-$stamp"
- $backup = "$HermesHome\node.old-$stamp"
- # Stage to a sibling directory so the final swap is a
- # same-volume rename (atomic), not a cross-volume Move-Item
- # (copy+delete, non-atomic -- a partial copy would leave a
- # broken tree). Move from $env:TEMP here, rename below.
- try {
- Move-Item $extractedDir.FullName $staged -ErrorAction Stop
- } catch {
- Write-Warn "Failed to stage the new Node.js tree; aborting the Node upgrade."
- Remove-Item -Recurse -Force $tmpDir -ErrorAction SilentlyContinue
- Remove-Item -Force $tmpZip -ErrorAction SilentlyContinue
- return $false
- }
- if (Test-Path "$HermesHome\node") {
- try {
- Rename-Item "$HermesHome\node" $backup -ErrorAction Stop
- } catch {
- Write-Warn "Hermes-managed Node.js is in use by a running app; deferring its upgrade. Close the app and re-run the update."
- Remove-Item -Recurse -Force $staged -ErrorAction SilentlyContinue
- Remove-Item -Recurse -Force $tmpDir -ErrorAction SilentlyContinue
- Remove-Item -Force $tmpZip -ErrorAction SilentlyContinue
- return $false
- }
- # A rename preserves LastWriteTime, so a backup renamed
- # from a long-lived tree would instantly look older than
- # the litter-sweep cutoff to a concurrent heal. Touch it
- # (best-effort) so the in-flight backup is never swept.
- try {
- (Get-Item $backup).LastWriteTime = Get-Date
- } catch { }
- try {
- Rename-Item $staged "$HermesHome\node" -ErrorAction Stop
- } catch {
- # Restore the live tree before bailing. The swap is a
- # same-volume rename, so a failure leaves no partial
- # target to clear.
- Rename-Item $backup "$HermesHome\node" -ErrorAction SilentlyContinue
- Remove-Item -Recurse -Force $staged -ErrorAction SilentlyContinue
- Remove-Item -Recurse -Force $tmpDir -ErrorAction SilentlyContinue
- Remove-Item -Force $tmpZip -ErrorAction SilentlyContinue
- return $false
- }
- Remove-Item -Recurse -Force $backup -ErrorAction SilentlyContinue
- } else {
- try {
- Rename-Item $staged "$HermesHome\node" -ErrorAction Stop
- } catch {
- Remove-Item -Recurse -Force $staged -ErrorAction SilentlyContinue
- Remove-Item -Recurse -Force $tmpDir -ErrorAction SilentlyContinue
- Remove-Item -Force $tmpZip -ErrorAction SilentlyContinue
- return $false
- }
- }
-
- # Session PATH so the rest of this run sees node/npm.
- $env:Path = "$HermesHome\node;$env:Path"
-
- # Persist to User PATH so fresh shells (and future stages
- # in cross-process driver mode) see it. Matches the
- # pattern Install-Git uses for PortableGit. See
- # Set-ManagedNodeFirstOnUserPath for why this is a
- # move-to-front and not an add-if-missing.
- Set-ManagedNodeFirstOnUserPath "$HermesHome\node"
-
- $version = & "$HermesHome\node\node.exe" --version
- Write-Success "Node.js $version installed to $HermesHome\node\ (portable, user-scoped)"
- # The zip's bundled npm is below the repo's engines.npm floor.
- Update-ManagedNpm "$HermesHome\node" | Out-Null
- $script:HasNode = $true
-
- Remove-Item -Force $tmpZip -ErrorAction SilentlyContinue
- Remove-Item -Recurse -Force $tmpDir -ErrorAction SilentlyContinue
- return $true
- }
- }
- } catch {
- Write-Warn "Portable Node.js download failed: $_"
- }
-
- # Fallback: try winget (used to be primary, demoted because the MSI
- # install triggers a UAC prompt that frequently appears minimized in
- # the taskbar -- looks like a hang to users on stock Windows).
- # Kept for environments where the portable download fails (proxy,
- # locked firewall, etc.) but the user is willing to consent to UAC.
- if (Get-Command winget -ErrorAction SilentlyContinue) {
- Write-Info "Falling back to winget (may prompt UAC -- check your taskbar for a flashing icon)..."
- # Capture EAP outside the try block so the catch's restore call always
- # has a meaningful value (see Install-Uv for the full rationale).
- $prevEAP = $ErrorActionPreference
- try {
- # Relax EAP=Stop so stderr lines from winget don't get wrapped
- # as ErrorRecords and short-circuit the 2>&1 pipe before we can
- # check the post-condition. See the long comment in Install-Uv
- # for the same pattern.
- $ErrorActionPreference = "Continue"
- # On ARM64, force winget to fetch the ARM64 installer. Without
- # the explicit override, winget on WoW64 sometimes still resolves
- # to x64 manifests, leaving us with an emulated Node toolchain
- # even after a "successful" install. The OpenJS manifest does
- # publish an arm64 installer, so this is safe.
- $wingetArgs = @(
- 'install','OpenJS.NodeJS','--silent',
- '--accept-package-agreements','--accept-source-agreements'
- )
- if ((Get-WindowsArch) -eq 'arm64') {
- $wingetArgs += @('--architecture','arm64')
- }
- winget @wingetArgs 2>&1 | Out-Null
- $ErrorActionPreference = $prevEAP
- # Refresh PATH
- $env:Path = [Environment]::GetEnvironmentVariable("Path", "User") + ";" + [Environment]::GetEnvironmentVariable("Path", "Machine")
- if (Test-SystemNodeReady) {
- $script:HasNode = $true
- return $true
- }
- } catch {
- if ($prevEAP) { $ErrorActionPreference = $prevEAP }
- }
- }
-
-
- Write-Info "Install manually: https://nodejs.org/en/download/"
- $script:HasNode = $false
- return $true
-}
-
-function Update-ProcessPathForPackages {
- # Make freshly-installed shims (rg.exe, ffmpeg.exe) visible to Get-Command in
- # THIS process without spawning a new shell, by folding the persisted
- # User+Machine hives plus winget's alias-shim directory into $env:Path.
- # Called after every package-manager attempt (winget/choco/scoop): previously
- # PATH was only refreshed inside the winget branch, so a successful
- # choco/scoop fallback -- or any install on a box without winget -- could be
- # misreported as "not installed".
- #
- # MERGE rather than overwrite: start from the existing process PATH so any
- # process-only entries added earlier in this installer run survive, then
- # APPEND hive/winget-Links entries not already present (case-insensitive,
- # order-preserving dedupe). A wholesale replace would silently drop those
- # process-only entries.
- $candidates = @()
- $candidates += $env:Path
- $candidates += [Environment]::GetEnvironmentVariable("Path", "User")
- $candidates += [Environment]::GetEnvironmentVariable("Path", "Machine")
- $wingetLinks = Join-Path $env:LOCALAPPDATA "Microsoft\WinGet\Links"
- if (Test-Path $wingetLinks) {
- $candidates += $wingetLinks
- }
- $seen = New-Object System.Collections.Generic.HashSet[string] ([StringComparer]::OrdinalIgnoreCase)
- $ordered = New-Object System.Collections.Generic.List[string]
- foreach ($chunk in $candidates) {
- if ([string]::IsNullOrEmpty($chunk)) { continue }
- foreach ($entry in $chunk.Split(';')) {
- $trimmed = $entry.Trim()
- if ($trimmed -and $seen.Add($trimmed)) {
- $ordered.Add($trimmed)
- }
- }
- }
- $env:Path = [string]::Join(';', $ordered)
-}
-
-function Install-SystemPackages {
- $script:HasRipgrep = $false
- $script:HasFfmpeg = $false
- $needRipgrep = $false
- $needFfmpeg = $false
-
- Write-Info "Checking ripgrep (fast file search)..."
- if (Get-Command rg -ErrorAction SilentlyContinue) {
- $version = rg --version | Select-Object -First 1
- Write-Success "$version found"
- $script:HasRipgrep = $true
- } else {
- $needRipgrep = $true
- }
-
- Write-Info "Checking ffmpeg (TTS voice messages)..."
- if (Get-Command ffmpeg -ErrorAction SilentlyContinue) {
- Write-Success "ffmpeg found"
- $script:HasFfmpeg = $true
- } else {
- $needFfmpeg = $true
- }
-
- if (-not $needRipgrep -and -not $needFfmpeg) { return }
-
- # Build description and package lists for each package manager
- $descParts = @()
- $wingetPkgs = @()
- $chocoPkgs = @()
- $scoopPkgs = @()
-
- if ($needRipgrep) {
- $descParts += "ripgrep for faster file search"
- $wingetPkgs += "BurntSushi.ripgrep.MSVC"
- $chocoPkgs += "ripgrep"
- $scoopPkgs += "ripgrep"
- }
- if ($needFfmpeg) {
- $descParts += "ffmpeg for TTS voice messages"
- $wingetPkgs += "Gyan.FFmpeg"
- $chocoPkgs += "ffmpeg"
- $scoopPkgs += "ffmpeg"
- }
-
- $description = $descParts -join " and "
- $hasWinget = Get-Command winget -ErrorAction SilentlyContinue
- $hasChoco = Get-Command choco -ErrorAction SilentlyContinue
- $hasScoop = Get-Command scoop -ErrorAction SilentlyContinue
-
- # Try winget first (most common on modern Windows)
- if ($hasWinget) {
- Write-Info "Installing $description via winget..."
- # Per-package log paths -- key the lookup by package id so we can
- # decide AFTER the post-install Get-Command check whether to keep
- # the log (still missing -> keep as breadcrumb) or delete it (now
- # present -> happy path, no clutter).
- $pkgLogs = @{}
- foreach ($pkg in $wingetPkgs) {
- $log = "$env:TEMP\hermes-winget-$($pkg -replace '[^A-Za-z0-9]','_')-$(Get-Random).log"
- $pkgLogs[$pkg] = $log
- # --source winget pins us to the github-backed source. Without this,
- # a broken msstore source (cert validation failures like 0x8a15005e
- # are common on Windows-on-ARM and some corporate networks) makes
- # winget bail with "please specify --source" *before* attempting any
- # install -- and it exits 0, so the surrounding try/catch never fires.
- # We don't ship anything from msstore, so pinning is safe.
- try {
- $output = winget install --exact --id $pkg --source winget --silent `
- --accept-package-agreements --accept-source-agreements 2>&1
- $code = $LASTEXITCODE
- $output | Out-File -FilePath $log -Encoding utf8
- "winget exit: $code" | Out-File -FilePath $log -Encoding utf8 -Append
- # 0x8A15002B (-1978335189) = APPINSTALLER_CLI_ERROR_UPDATE_NOT_APPLICABLE.
- # winget treats `install` on a package it already has registered as
- # an *upgrade*, finds no newer version, and bails with this code --
- # even when the binary is gone from disk/PATH (stale registration,
- # files removed outside winget, or a missing alias shim). We KNOW the
- # command was missing (that's why we're here), so a plain install
- # dead-ends forever. Force a reinstall to repair the registration so
- # the shim reappears.
- if ($code -eq -1978335189) {
- "-> already-installed/no-upgrade; retrying with --force" | Out-File -FilePath $log -Encoding utf8 -Append
- $output = winget install --exact --id $pkg --source winget --silent --force `
- --accept-package-agreements --accept-source-agreements 2>&1
- $output | Out-File -FilePath $log -Encoding utf8 -Append
- "winget exit (force): $LASTEXITCODE" | Out-File -FilePath $log -Encoding utf8 -Append
- }
- } catch {
- $_ | Out-File -FilePath $log -Encoding utf8 -Append
- "winget exit: <exception>" | Out-File -FilePath $log -Encoding utf8 -Append
- }
- }
- # Refresh PATH so packages winget exposed via "command line aliases" in
- # %LOCALAPPDATA%\Microsoft\WinGet\Links (added to PATH only in
- # newly-spawned shells, not this process) are visible to Get-Command below.
- Update-ProcessPathForPackages
- if ($needRipgrep -and (Get-Command rg -ErrorAction SilentlyContinue)) {
- Write-Success "ripgrep installed"
- $script:HasRipgrep = $true
- $needRipgrep = $false
- Remove-Item -Path $pkgLogs["BurntSushi.ripgrep.MSVC"] -ErrorAction SilentlyContinue
- } elseif ($pkgLogs.ContainsKey("BurntSushi.ripgrep.MSVC")) {
- Write-Warn "winget could not install ripgrep; details: $($pkgLogs['BurntSushi.ripgrep.MSVC'])"
- }
- if ($needFfmpeg -and (Get-Command ffmpeg -ErrorAction SilentlyContinue)) {
- Write-Success "ffmpeg installed"
- $script:HasFfmpeg = $true
- $needFfmpeg = $false
- Remove-Item -Path $pkgLogs["Gyan.FFmpeg"] -ErrorAction SilentlyContinue
- } elseif ($pkgLogs.ContainsKey("Gyan.FFmpeg")) {
- Write-Warn "winget could not install ffmpeg; details: $($pkgLogs['Gyan.FFmpeg'])"
- }
- if (-not $needRipgrep -and -not $needFfmpeg) { return }
- }
-
- # Fallback: choco
- if ($hasChoco -and ($needRipgrep -or $needFfmpeg)) {
- Write-Info "Trying Chocolatey..."
- foreach ($pkg in $chocoPkgs) {
- try { choco install $pkg -y 2>&1 | Out-Null } catch { }
- }
- Update-ProcessPathForPackages
- if ($needRipgrep -and (Get-Command rg -ErrorAction SilentlyContinue)) {
- Write-Success "ripgrep installed via chocolatey"
- $script:HasRipgrep = $true
- $needRipgrep = $false
- }
- if ($needFfmpeg -and (Get-Command ffmpeg -ErrorAction SilentlyContinue)) {
- Write-Success "ffmpeg installed via chocolatey"
- $script:HasFfmpeg = $true
- $needFfmpeg = $false
- }
- }
-
- # Fallback: scoop
- if ($hasScoop -and ($needRipgrep -or $needFfmpeg)) {
- Write-Info "Trying Scoop..."
- foreach ($pkg in $scoopPkgs) {
- try { scoop install $pkg 2>&1 | Out-Null } catch { }
- }
- Update-ProcessPathForPackages
- if ($needRipgrep -and (Get-Command rg -ErrorAction SilentlyContinue)) {
- Write-Success "ripgrep installed via scoop"
- $script:HasRipgrep = $true
- $needRipgrep = $false
- }
- if ($needFfmpeg -and (Get-Command ffmpeg -ErrorAction SilentlyContinue)) {
- Write-Success "ffmpeg installed via scoop"
- $script:HasFfmpeg = $true
- $needFfmpeg = $false
- }
- }
-
- # Show manual instructions for anything still missing
- if ($needRipgrep) {
- Write-Warn "ripgrep not installed (file search will use findstr fallback)"
- Write-Info " winget install BurntSushi.ripgrep.MSVC"
- }
- if ($needFfmpeg) {
- Write-Warn "ffmpeg not installed (TTS voice messages will be limited)"
- Write-Info " winget install Gyan.FFmpeg"
- }
-}
-
-# ============================================================================
-# Installation
-# ============================================================================
-
-function Install-Repository {
- Write-Info "Installing to $InstallDir..."
-
- $didUpdate = $false
-
- if (Test-Path $InstallDir) {
- # Test-Path "$InstallDir\.git" returns True when .git is a file OR a
- # directory OR a symlink OR a submodule-style gitfile -- and also when
- # it's a broken stub left over from a failed previous install (e.g.
- # a partial Remove-Item that couldn't delete a locked index.lock).
- # Validate the repo properly by asking git itself. Three checks
- # belt-and-braces: rev-parse (work tree), git status, and a resolvable
- # HEAD (an initial commit). If any fails the repo is broken and we
- # fall through to a fresh clone.
- $repoValid = $false
- if (Test-Path "$InstallDir\.git") {
- Push-Location $InstallDir
- try {
- # Reset $LASTEXITCODE before the probe so we don't pick up
- # a stale 0 from an earlier git call in this session.
- $global:LASTEXITCODE = 0
- $revParseOut = & git -c windows.appendAtomically=false rev-parse --is-inside-work-tree 2>&1
- $revParseOk = ($LASTEXITCODE -eq 0) -and ($revParseOut -match "true")
-
- $global:LASTEXITCODE = 0
- $null = & git -c windows.appendAtomically=false status --short 2>&1
- $statusOk = ($LASTEXITCODE -eq 0)
-
- # An interrupted previous clone leaves a repo with NO initial
- # commit. rev-parse/status still succeed there, but the update
- # path's `git stash` (and later `git checkout`) abort with
- # "You do not have the initial commit yet" and fail the install
- # (#40998). Require a resolvable HEAD so such partial checkouts
- # are treated as broken and re-cloned fresh below.
- $global:LASTEXITCODE = 0
- $null = & git -c windows.appendAtomically=false rev-parse --verify HEAD 2>&1
- $hasCommit = ($LASTEXITCODE -eq 0)
-
- if ($revParseOk -and $statusOk -and $hasCommit) {
- $repoValid = $true
- }
- } catch {}
- Pop-Location
- }
-
- if ($repoValid) {
- Write-Info "Existing installation found, updating..."
- Push-Location $InstallDir
- # Wrap the entire fetch+checkout block in EAP=Continue so git's
- # routine stderr output (e.g. 'From <url>' info lines emitted by
- # `git fetch`) doesn't terminate the script under the global
- # EAP=Stop. We rely on $LASTEXITCODE for actual failures.
- $prevEAP = $ErrorActionPreference
- $ErrorActionPreference = "Continue"
- $autostashRef = ""
- try {
- # This is a MANAGED checkout, not a repo the user edits. Git for
- # Windows defaults to core.autocrlf=true, which renormalizes the
- # repo's LF-only text files to CRLF in the working tree -- so
- # tracked files (.envrc, AGENTS.md, agent/*.py, workflows, ...)
- # show as locally modified even though nobody touched them. A
- # bare `git checkout` then aborts with "Your local changes would
- # be overwritten by checkout", which is exactly the failure GUI
- # users hit on update. Pin autocrlf=false so the dirt is never
- # created in the first place.
- git -c windows.appendAtomically=false config core.autocrlf false 2>$null
- Discard-LockfileChurn $InstallDir
- # Preserve any real local changes before the checkout instead of
- # discarding them with `reset --hard HEAD`. The old hard reset
- # silently destroyed agent-edited source on managed clones (the
- # #38542 data-loss class). Stash + restore mirrors install.sh:
- # nothing is lost, and a failed restore leaves the work in a
- # git stash for manual recovery. Untracked files are included so
- # agent-created dirs (e.g. tinker-atropos/) survive too.
- $statusOut = git -c windows.appendAtomically=false status --porcelain 2>$null
- if (-not [string]::IsNullOrWhiteSpace(($statusOut -join "`n"))) {
- # A previously interrupted update can leave the index with
- # unmerged entries. In that state `git stash` aborts with
- # "could not write index" and the following `git checkout`
- # aborts with "you need to resolve your current index first"
- # -- the GUI "git checkout main failed (exit 1)" install
- # failure. Clear the conflict markers with `git reset` first:
- # working-tree changes are kept (and stashed just below); only
- # the index conflict state is dropped. Mirrors the `hermes
- # update` path (#4735).
- $unmergedOut = git -c windows.appendAtomically=false ls-files --unmerged 2>$null
- if (-not [string]::IsNullOrWhiteSpace(($unmergedOut -join "`n"))) {
- Write-Info "Clearing unmerged index entries from a previous conflict..."
- git -c windows.appendAtomically=false reset -q 2>$null
- }
- $stashName = "hermes-install-autostash-" + (Get-Date -Format "yyyyMMdd-HHmmss")
- Write-Info "Local changes detected, stashing before update..."
- git -c windows.appendAtomically=false stash push --include-untracked -m "$stashName"
- if ($LASTEXITCODE -eq 0) { $autostashRef = "stash@{0}" }
- }
- git -c windows.appendAtomically=false fetch origin $Branch
- if ($LASTEXITCODE -ne 0) { throw "git fetch failed (exit $LASTEXITCODE)" }
- # Precedence: Commit > Tag > Branch. Commit and Tag check
- # out as detached HEAD intentionally -- they're meant to be
- # reproducible pins, not branches the user pulls into.
- if ($Commit) {
- # Make sure we have the commit locally (a tag-less commit
- # SHA isn't always reachable from any one branch fetch).
- git -c windows.appendAtomically=false fetch origin $Commit
- # A commit pin must never move an existing install
- # BACKWARDS. hermes-setup.exe bakes its build-time commit
- # into the binary (BUILD_PIN_COMMIT) and passes it as
- # -Commit on every install-mode run -- including the retry
- # the desktop's "Update didn't finish" screen kicks off. An
- # installer built months ago would otherwise rewind a
- # current checkout to its build commit, leaving ancient
- # code against a current venv (npm workspaces and Python
- # deps that no longer match: the #74xxx report). Skip the
- # pin when the target is already an ancestor of HEAD; a
- # fresh clone has no such ancestry and pins normally.
- $skipRollback = $false
- if (-not $ForceCommit) {
- git -c windows.appendAtomically=false merge-base --is-ancestor $Commit HEAD 2>$null
- $isAncestor = ($LASTEXITCODE -eq 0)
- $pinnedSha = (& git -c windows.appendAtomically=false rev-parse "$Commit^{commit}" 2>$null)
- $headSha = (& git -c windows.appendAtomically=false rev-parse HEAD 2>$null)
- $skipRollback = $isAncestor -and ($pinnedSha -ne $headSha)
- }
- if ($skipRollback) {
- Write-Warn "Ignoring -Commit $Commit`: the checkout is already newer."
- Write-Warn "Pinning to it would roll this install back. Pass -ForceCommit to override."
- } else {
- git -c windows.appendAtomically=false checkout --detach $Commit
- if ($LASTEXITCODE -ne 0) { throw "git checkout $Commit failed (exit $LASTEXITCODE)" }
- }
- } elseif ($Tag) {
- git -c windows.appendAtomically=false fetch origin "refs/tags/${Tag}:refs/tags/${Tag}"
- git -c windows.appendAtomically=false checkout --detach "refs/tags/$Tag"
- if ($LASTEXITCODE -ne 0) { throw "git checkout tag $Tag failed (exit $LASTEXITCODE)" }
- } else {
- git -c windows.appendAtomically=false checkout $Branch
- if ($LASTEXITCODE -ne 0) { throw "git checkout $Branch failed (exit $LASTEXITCODE)" }
- # Managed installs should follow origin/$Branch exactly. If
- # the checkout has diverged (or has local-only commits),
- # ff-only pull cannot succeed -- mirror ``hermes update`` and
- # reset to the fetched remote so bootstrap/install can recover.
- git -c windows.appendAtomically=false pull --ff-only origin $Branch
- if ($LASTEXITCODE -ne 0) {
- Write-Warn "Fast-forward not possible; resetting managed install to origin/$Branch..."
- git -c windows.appendAtomically=false reset --hard "origin/$Branch"
- if ($LASTEXITCODE -ne 0) { throw "git reset --hard origin/$Branch failed (exit $LASTEXITCODE)" }
- }
- }
-
- if ($autostashRef) {
- # Default to restoring so work is never silently dropped.
- # Only prompt when we're certain a human can answer: an
- # interactive session AND a real, non-redirected console on
- # both stdin and stdout. The desktop "Update" button and
- # bootstrap run the installer without a usable console -- in
- # those cases Read-Host would hang or return empty, so we
- # skip the prompt and just restore (the safe default).
- $restoreNow = $true
- $hasConsole = $false
- try {
- $hasConsole = (
- [Environment]::UserInteractive `
- -and (-not [Console]::IsInputRedirected) `
- -and (-not [Console]::IsOutputRedirected) `
- -and ($Host.Name -eq "ConsoleHost")
- )
- } catch { $hasConsole = $false }
- if ($hasConsole) {
- Write-Warn "Local changes were stashed before updating."
- Write-Warn "Restoring them may reapply local customizations onto the updated codebase."
- $restoreAnswer = Read-Host "Restore local changes now? [Y/n]"
- if ($restoreAnswer -match '^(n|no)$') { $restoreNow = $false }
- }
-
- if ($restoreNow) {
- Write-Info "Restoring local changes..."
- $restoreOutput = @(git -c windows.appendAtomically=false stash apply $autostashRef 2>&1)
- $restoreExit = $LASTEXITCODE
- $conflictedFiles = @(
- git -c windows.appendAtomically=false diff --name-only --diff-filter=U 2>$null
- ) | Where-Object { $_ -and $_.ToString().Trim() }
- if (($restoreExit -eq 0) -and ($conflictedFiles.Count -eq 0)) {
- git -c windows.appendAtomically=false stash drop $autostashRef 2>$null
- Write-Warn "Local changes were restored on top of the updated codebase."
- Write-Warn "Review git diff / git status if Hermes behaves unexpectedly."
- } else {
- Write-Err "Update pulled new code, but restoring local changes hit conflicts."
- foreach ($line in $restoreOutput) {
- if ($line -and $line.ToString().Trim()) {
- Write-Host $line
- }
- }
- if ($conflictedFiles.Count -gt 0) {
- Write-Host ""
- Write-Host "Conflicted files:"
- foreach ($file in $conflictedFiles) {
- Write-Host " - $file"
- }
- }
- Write-Host ""
- Write-Info "Your stashed changes are preserved -- nothing is lost."
- Write-Info " Stash ref: $autostashRef"
- git -c windows.appendAtomically=false reset --hard HEAD 2>$null | Out-Null
- Write-Info "Working tree reset to clean state."
- Write-Info "Restore your changes later with: git stash apply $autostashRef"
- }
- } else {
- Write-Info "Skipped restoring local changes."
- Write-Info "Your changes are still preserved in git stash."
- Write-Info "Restore manually with: git stash apply $autostashRef"
- }
- $autostashRef = ""
- }
- } finally {
- if ($autostashRef) {
- # We stashed but never reached the restore block (a fetch/
- # checkout/pull failure threw). Leave the stash in place and
- # tell the user how to recover it -- never silently drop it.
- Write-Warn "Update did not complete. Your local changes are preserved in git stash."
- Write-Info "Restore manually with: git stash apply $autostashRef"
- }
- $ErrorActionPreference = $prevEAP
- Pop-Location
- }
- $didUpdate = $true
- } else {
- # Directory exists but isn't a usable git repo -- e.g. an
- # interrupted clone with no initial commit (#40998), or a leftover
- # ``.git`` stub from a partial uninstall that used to lock the
- # installer into the "update" branch forever. Move it aside rather
- # than deleting it -- never destroy a directory the user might still
- # want -- and fall through to a fresh clone.
- $backupDir = "$InstallDir.broken-" + (Get-Date -Format "yyyyMMdd-HHmmss")
- Write-Warn "Existing directory at $InstallDir is not a valid git repo."
- Write-Warn "Moving it aside to $backupDir before re-cloning."
- try {
- Move-Item -LiteralPath $InstallDir -Destination $backupDir -ErrorAction Stop
- } catch {
- Write-Err "Could not move $InstallDir aside : $_"
- Write-Info "Close any programs that might be using files in $InstallDir (editors,"
- Write-Info "terminals, running hermes processes) and try again."
- throw
- }
- }
- }
-
- if (-not $didUpdate) {
- $cloneSuccess = $false
-
- # Fix Windows git "copy-fd: write returned: Invalid argument" error.
- # Git for Windows can fail on atomic file operations (hook templates,
- # config lock files) due to antivirus, OneDrive, or NTFS filter drivers.
- # The -c flag injects config before any file I/O occurs.
- Write-Info "Configuring git for Windows compatibility..."
- $env:GIT_CONFIG_COUNT = "1"
- $env:GIT_CONFIG_KEY_0 = "windows.appendAtomically"
- $env:GIT_CONFIG_VALUE_0 = "false"
- git config --global windows.appendAtomically false 2>$null
-
- # Try SSH first, then HTTPS, with -c flag for atomic write fix
- Write-Info "Trying SSH clone..."
- $env:GIT_SSH_COMMAND = "ssh -o BatchMode=yes -o ConnectTimeout=5"
- try {
- Invoke-NativeWithRelaxedErrorAction { git -c windows.appendAtomically=false clone --depth 1 --branch $Branch $RepoUrlSsh $InstallDir }
- if ($LASTEXITCODE -eq 0) { $cloneSuccess = $true }
- } catch { }
- $env:GIT_SSH_COMMAND = $null
-
- if (-not $cloneSuccess) {
- if (Test-Path $InstallDir) { Remove-Item -Recurse -Force $InstallDir -ErrorAction SilentlyContinue }
- Write-Info "SSH failed, trying HTTPS..."
- try {
- Invoke-NativeWithRelaxedErrorAction { git -c windows.appendAtomically=false clone --depth 1 --branch $Branch $RepoUrlHttps $InstallDir }
- if ($LASTEXITCODE -eq 0) { $cloneSuccess = $true }
- } catch { }
- }
-
- # Fallback: download ZIP archive (bypasses git file I/O issues entirely)
- if (-not $cloneSuccess) {
- if (Test-Path $InstallDir) { Remove-Item -Recurse -Force $InstallDir -ErrorAction SilentlyContinue }
- Write-Warn "Git clone failed -- downloading ZIP archive instead..."
- try {
- # Pick the ZIP URL for the most-specific ref the caller asked
- # for. GitHub supports archive URLs for commits, tags, and
- # branches; we honour Commit > Tag > Branch.
- if ($Commit) {
- $zipUrl = "https://github.com/NousResearch/hermes-agent/archive/$Commit.zip"
- $zipLabel = $Commit
- } elseif ($Tag) {
- $zipUrl = "https://github.com/NousResearch/hermes-agent/archive/refs/tags/$Tag.zip"
- $zipLabel = $Tag
- } else {
- $zipUrl = "https://github.com/NousResearch/hermes-agent/archive/refs/heads/$Branch.zip"
- $zipLabel = $Branch
- }
- $zipPath = "$env:TEMP\hermes-agent-$zipLabel.zip"
- $extractPath = "$env:TEMP\hermes-agent-extract"
-
- Invoke-WebRequest -Uri $zipUrl -OutFile $zipPath -UseBasicParsing
- if (Test-Path $extractPath) { Remove-Item -Recurse -Force $extractPath }
- Expand-Archive -Path $zipPath -DestinationPath $extractPath -Force
-
- # GitHub ZIPs extract to repo-branch/ subdirectory
- $extractedDir = Get-ChildItem $extractPath -Directory | Select-Object -First 1
- if ($extractedDir) {
- New-Item -ItemType Directory -Force -Path (Split-Path $InstallDir) -ErrorAction SilentlyContinue | Out-Null
- Move-Item $extractedDir.FullName $InstallDir -Force
- Write-Success "Downloaded and extracted"
-
- # Initialize git repo so updates work later. A bare
- # `git init` leaves NO HEAD -- desktop's write-build-stamp
- # then hard-fails with "could not determine git commit"
- # (#50823 / #61657). Fetch the requested ref and force-check
- # it out (-f) so untracked ZIP files cannot block checkout.
- Push-Location $InstallDir
- git -c windows.appendAtomically=false init 2>$null
- git -c windows.appendAtomically=false config windows.appendAtomically false 2>$null
- # Pin autocrlf=false BEFORE the checkout below. Git for Windows
- # defaults to core.autocrlf=true, which would renormalize the
- # repo's LF text files to CRLF in the working tree during
- # `checkout -f FETCH_HEAD` -- leaving this freshly-created
- # managed checkout dirty vs HEAD and aborting the next
- # `hermes update` (see the notes at the shared clone-path
- # config below and install.ps1:1461-1469). The later pin on
- # the shared path is idempotent and still covers git clones.
- git -c windows.appendAtomically=false config core.autocrlf false 2>$null
- git remote add origin $RepoUrlHttps 2>$null
- $fetchRef = if ($Commit) { $Commit } elseif ($Tag) { "refs/tags/$Tag" } else { $Branch }
- Write-Info "Fetching $fetchRef so the ZIP checkout has a resolvable HEAD..."
- $prevZipEAP = $ErrorActionPreference
- $ErrorActionPreference = "Continue"
- try {
- git -c windows.appendAtomically=false fetch --depth 1 origin $fetchRef 2>&1 | Out-Null
- if ($LASTEXITCODE -eq 0) {
- if ($Commit -or $Tag) {
- git -c windows.appendAtomically=false checkout -f --detach FETCH_HEAD 2>&1 | Out-Null
- } else {
- git -c windows.appendAtomically=false checkout -f -B $Branch FETCH_HEAD 2>&1 | Out-Null
- }
- if ($LASTEXITCODE -eq 0) {
- Write-Success "ZIP checkout pinned to $fetchRef"
- } else {
- # Checkout blocked, but FETCH_HEAD still has a SHA we can stamp with.
- $fetchSha = & git -c windows.appendAtomically=false rev-parse FETCH_HEAD 2>$null
- if ($LASTEXITCODE -eq 0 -and $fetchSha) {
- if (-not $env:GITHUB_SHA) { $env:GITHUB_SHA = ("$fetchSha").Trim() }
- Write-Warn "ZIP checkout failed; seeded GITHUB_SHA from FETCH_HEAD for desktop stamp"
- } else {
- Write-Warn "ZIP extract succeeded but git checkout failed -- desktop build may need `$env:GITHUB_SHA"
- }
- }
- } else {
- Write-Warn "ZIP extract succeeded but git fetch of $fetchRef failed -- desktop build may need `$env:GITHUB_SHA"
- }
- } finally {
- $ErrorActionPreference = $prevZipEAP
- }
- Pop-Location
- Write-Success "Git repo initialized for future updates"
-
- $cloneSuccess = $true
- }
-
- # Cleanup temp files
- Remove-Item -Force $zipPath -ErrorAction SilentlyContinue
- Remove-Item -Recurse -Force $extractPath -ErrorAction SilentlyContinue
- } catch {
- Write-Err "ZIP download also failed: $_"
- }
- }
-
- if (-not $cloneSuccess) {
- throw "Failed to download repository (tried git clone SSH, HTTPS, and ZIP)"
- }
- }
-
- # Set per-repo config (harmless if it fails)
- Push-Location $InstallDir
- git -c windows.appendAtomically=false config windows.appendAtomically false 2>$null
- # Pin autocrlf=false on the managed clone so git never renormalizes the
- # repo's LF text files to CRLF in the working tree. Without this, the very
- # next `hermes update` checkout aborts on a "dirty" tree the user never
- # touched (see the update path above).
- git -c windows.appendAtomically=false config core.autocrlf false 2>$null
-
- # Post-clone pin: when a clone (or ZIP-fallback init) just landed us on
- # $Branch's tip, honour the higher-precedence $Commit / $Tag by checking
- # the exact ref out as a detached HEAD. Skipped for the in-place update
- # path (above) since that already routed via the same precedence.
- if (-not $didUpdate) {
- # Same EAP=Continue wrap as the update path -- git fetch's 'From <url>'
- # info line goes to stderr and would terminate the script under the
- # global EAP=Stop otherwise. We check $LASTEXITCODE for real errors.
- $prevEAP = $ErrorActionPreference
- $ErrorActionPreference = "Continue"
- try {
- if ($Commit) {
- Write-Info "Pinning to commit $Commit..."
- git -c windows.appendAtomically=false fetch origin $Commit
- git -c windows.appendAtomically=false checkout --detach $Commit
- if ($LASTEXITCODE -ne 0) {
- throw "git checkout $Commit failed (exit $LASTEXITCODE)"
- }
- } elseif ($Tag) {
- Write-Info "Pinning to tag $Tag..."
- git -c windows.appendAtomically=false fetch origin "refs/tags/${Tag}:refs/tags/${Tag}"
- git -c windows.appendAtomically=false checkout --detach "refs/tags/$Tag"
- if ($LASTEXITCODE -ne 0) {
- throw "git checkout tag $Tag failed (exit $LASTEXITCODE)"
- }
- }
- } finally {
- $ErrorActionPreference = $prevEAP
- }
- }
-
- Write-Success "Repository ready"
-}
-
-function Install-Venv {
- if ($NoVenv) {
- Write-Info "Skipping virtual environment (-NoVenv)"
- return
- }
-
- # Re-resolve the interpreter before creating the venv. Under Hermes-Setup.exe
- # each stage runs in its own powershell.exe, so the fallback the `python`
- # stage picked (e.g. 3.12 when 3.11 is absent) did NOT propagate into this
- # fresh process -- $PythonVersion is back at its "3.11" default. Trusting it
- # here made `uv venv venv --python 3.11` fail with exit 2 on machines without
- # 3.11 even though the `python` stage reported success (issue #50769).
- $resolved = Resolve-AvailablePythonVersion
- if ($resolved -and $resolved -ne $PythonVersion) {
- Write-Info "Python $PythonVersion not available; using detected Python $resolved"
- $script:PythonVersion = $resolved
- }
-
- Write-Info "Creating virtual environment with Python $PythonVersion..."
-
- Push-Location $InstallDir
-
- # Tasks we disabled below and must re-enable no matter how this stage
- # exits. Populated only with tasks that were ENABLED before we touched
- # them, so a task the user deliberately disabled is never re-armed.
- $gatewayTasksDisabled = @()
- $venvHadExistingVenv = $false
- $venvBackupName = $null
- $venvParked = $false
- try {
- if (Test-Path -LiteralPath "venv") {
- $venvHadExistingVenv = $true
- Write-Info "Virtual environment already exists, recreating..."
- # On Windows, native Python extensions (e.g. _bcrypt.pyd, tornado's
- # speedups.pyd) are loaded as DLLs by any running hermes process.
- # Windows denies deletion of loaded DLLs, so every process running out
- # of this venv must be stopped before retiring it. This keeps cleanup
- # from accumulating locked stale trees and avoids carrying a live
- # gateway into the replacement venv.
- if ($env:OS -eq "Windows_NT") {
- $myPid = $PID
- Write-Info "Stopping any running hermes processes before recreating venv..."
- # Disarm the respawner FIRST: the gateway autostart Scheduled Task
- # relaunches a killed gateway within seconds, and losing that race
- # re-locks the venv's .pyd files between our kill sweep and
- # venv parking/cleanup (the July 2026 _brotlicffi.pyd incident). schtasks
- # /End stops a running task instance; /Change /DISABLE stops it
- # from re-firing mid-install. (The Startup-folder .vbs fallback is
- # NOT touched: it only fires at logon, so it cannot respawn a
- # gateway mid-install.) Re-enabled in the finally below -- including
- # on failure -- but only for tasks that were enabled to begin with.
- # Best-effort: a missing task just errors quietly.
- try {
- schtasks /Query /FO CSV 2>$null | ConvertFrom-Csv | Where-Object { $_.TaskName -like '*Hermes_Gateway*' } | ForEach-Object {
- $tn = $_.TaskName
- if ($_.Status -eq 'Disabled') {
- Write-Info " gateway autostart task $tn is already disabled; leaving it that way"
- return
- }
- schtasks /End /TN $tn 2>$null | Out-Null
- schtasks /Change /TN $tn /DISABLE 2>$null | Out-Null
- $gatewayTasksDisabled += $tn
- Write-Info " disabled gateway autostart task $tn for the duration of the install"
- }
- } catch {
- Write-Warn "Could not enumerate gateway scheduled tasks: $($_.Exception.Message)"
- }
- # The launcher CLI (hermes.exe) plus its child tree.
- & taskkill /F /T /IM hermes.exe /FI "PID ne $myPid" 2>$null | Out-Null
- # taskkill /IM hermes.exe is NOT enough: the gateway/agent that a
- # scheduled task or watchdog autostarts runs as
- # `pythonw.exe -m hermes_cli.main gateway run` straight out of
- # venv\Scripts\, so its image name is python/pythonw, not hermes.exe.
- # That process holds the venv's .pyd files open and re-triggers the
- # access-denied failure. Select only roots whose executable lives
- # under this venv, then stop each root's whole process tree. Some
- # Hermes children re-exec through .hermes-runtime, so killing only
- # the selected venv process can leave its child holding the install
- # open. The path-prefix check still keeps unrelated Python processes
- # outside this venv untouched.
- #
- # The gateway autostart task registers with /RL LIMITED as the current
- # user (see hermes_cli/gateway_windows.py), so the installer always
- # runs at equal-or-higher integrity and can read its executable path.
- # Get-CimInstance is used over Get-Process because it returns a null
- # ExecutablePath for a process it cannot inspect (a different session)
- # instead of throwing, so an unreadable process is skipped rather than
- # aborting the whole sweep.
- #
- # The sweep is a bounded LOOP, not single-shot: supervised processes
- # (the Desktop app's backend, a watchdog-managed gateway) respawn in
- # the window between one kill pass and venv parking. Each pass re-
- # enumerates; three consecutive clean passes (or the attempt cap)
- # ends the loop.
- $venvPrefix = [System.IO.Path]::GetFullPath((Join-Path $InstallDir "venv")).TrimEnd('\') + '\'
- $cleanPasses = 0
- for ($sweep = 0; $sweep -lt 10 -and $cleanPasses -lt 3; $sweep++) {
- $found = 0
- try {
- Get-CimInstance Win32_Process -ErrorAction Stop |
- Where-Object { $_.ProcessId -ne $myPid -and $_.ExecutablePath -and $_.ExecutablePath.StartsWith($venvPrefix, [System.StringComparison]::OrdinalIgnoreCase) } |
- ForEach-Object {
- $found++
- $treePid = [string]$_.ProcessId
- Write-Info " stopping process tree at PID $treePid ($($_.Name)) running from venv"
- & taskkill /F /T /PID $treePid 2>$null | Out-Null
- }
- } catch {
- Write-Warn "Could not enumerate venv processes: $($_.Exception.Message)"
- break
- }
- if ($found -eq 0) { $cleanPasses++ } else { $cleanPasses = 0 }
- Start-Sleep -Milliseconds 400
- }
- }
- # Move the old venv aside before creating its replacement. A directory
- # rename is atomic on the same volume and does not require deleting
- # files mapped as DLLs. NEVER fall back to deleting the live venv
- # (#83149): Remove-Item -Recurse can delete most of site-packages and
- # then fail on one locked .pyd, leaving a gutted venv with no usable
- # interpreter and no rollback source. Abort with the previous install
- # intact so the user can close holders and retry.
- $venvBackupName = "venv.stale.{0}-{1}" -f (Get-Date -Format "yyyyMMddHHmmss"), ([Guid]::NewGuid().ToString("N"))
- try {
- Rename-Item -LiteralPath "venv" -NewName $venvBackupName -ErrorAction Stop
- $venvParked = $true
- } catch {
- $renameErr = $_.Exception.Message
- throw (
- "Could not move the existing venv aside ($renameErr). " +
- "A process still has the install directory open (often a non-Hermes " +
- "python.exe that resolved into this venv via PATH). Close those " +
- "processes and retry - the previous install was left intact."
- )
- }
- }
-
- # uv creates the venv and pins the Python version in one step. uv emits
- # normal progress such as "Using CPython ..." on stderr; under Windows
- # PowerShell 5.1 with EAP=Stop that stderr is a NativeCommandError unless
- # we temporarily relax EAP and trust $LASTEXITCODE for real failures.
- Invoke-NativeWithRelaxedErrorAction { & $UvCmd venv venv --python $PythonVersion }
- # Relaxing EAP above means a *genuine* uv-venv failure (exit != 0) no longer
- # aborts on its own. Capture $LASTEXITCODE immediately and fail fast, so the
- # `venv` stage can't falsely report success (and Invoke-Stage can't emit
- # ok=true) when the venv was never created.
- $venvExitCode = $LASTEXITCODE
- if ($venvExitCode -ne 0) {
- throw "Failed to create virtual environment (uv venv exited with $venvExitCode)"
- }
-
- # uv can return success without leaving the interpreter expected by the
- # installer (for example after an interrupted filesystem operation). Treat
- # that as a failed transaction so the previous venv can be restored.
- $venvPythonExe = Join-Path $InstallDir "venv\Scripts\python.exe"
- if (-not (Test-Path -LiteralPath $venvPythonExe -PathType Leaf)) {
- throw "uv reported success but venv interpreter is missing at $venvPythonExe"
- }
-
- # The replacement has a working interpreter, but the transaction is only
- # committed after Install-Dependencies' baseline-import gate passes -- the
- # bootstrap runs the stages as separate processes, and every dependency
- # tier (or the import validation) can still fail after this stage
- # succeeds. Record the parked backup so the dependency stage can restore
- # it on failure and commit its cleanup only after validation (#83149).
- if ($venvParked) {
- Set-Content -LiteralPath (Join-Path $InstallDir "venv.pending-backup") -Value $venvBackupName -Encoding ascii
- Write-Info "Previous venv parked at $venvBackupName until the dependency install is verified"
- }
-
- # Clean up parked venvs from previous installs whose handles have since
- # been released. Best-effort -- a still-held tree just stays for next time.
- # The backup parked THIS run is excluded: it is the rollback source until
- # Install-Dependencies commits the transaction.
- Get-ChildItem -Directory -Filter "venv.stale.*" -ErrorAction SilentlyContinue |
- Where-Object { $_.Name -ne $venvBackupName } | ForEach-Object {
- Remove-Item -Recurse -Force $_.FullName -ErrorAction SilentlyContinue
- }
-
- # Neutralize any inherited UV_PYTHON (e.g. $env:UV_PYTHON = "3.14" left in
- # the user's shell). uv honours UV_PYTHON over an existing venv for the
- # later `uv sync` / `uv pip install` tiers, so without this it would
- # silently delete this 3.11 venv and recreate it at the inherited version
- # -- building Rust transitives that have no wheel for that version from
- # source via maturin, which fails. Pinning UV_PYTHON to the interpreter we
- # just created forces every subsequent uv command onto it.
- $env:UV_PYTHON = $venvPythonExe
- } catch {
- $originalError = $_
- $rollbackError = $null
-
- if ($venvParked -and $venvBackupName -and (Test-Path -LiteralPath $venvBackupName)) {
- try {
- if (Test-Path -LiteralPath "venv") {
- $failedVenvName = "venv.failed.{0}-{1}" -f (Get-Date -Format "yyyyMMddHHmmss"), ([Guid]::NewGuid().ToString("N"))
- Rename-Item -LiteralPath "venv" -NewName $failedVenvName -ErrorAction Stop
- Write-Warn "Failed replacement parked at $failedVenvName"
- }
- Rename-Item -LiteralPath $venvBackupName -NewName "venv" -ErrorAction Stop
- Write-Warn "Restored previous virtual environment after failed recreate"
- } catch {
- $rollbackError = $_.Exception.Message
- }
-
- if ($rollbackError) {
- throw "Virtual environment recreate failed: $($originalError.Exception.Message). Rollback failed: $rollbackError. Previous venv remains at $venvBackupName."
- }
- } elseif (-not $venvHadExistingVenv -and (Test-Path -LiteralPath "venv")) {
- # Preserve a partial first install too. This branch must not touch a
- # pre-existing venv whose move-aside failed above.
- try {
- $failedVenvName = "venv.failed.{0}-{1}" -f (Get-Date -Format "yyyyMMddHHmmss"), ([Guid]::NewGuid().ToString("N"))
- Rename-Item -LiteralPath "venv" -NewName $failedVenvName -ErrorAction Stop
- Write-Warn "Partial virtual environment parked at $failedVenvName"
- } catch {
- $rollbackError = $_.Exception.Message
- }
- if ($rollbackError) {
- throw "Virtual environment creation failed: $($originalError.Exception.Message). Could not park partial venv: $rollbackError"
- }
- }
-
- throw $originalError
- } finally {
- Pop-Location
- # Re-arm the gateway autostart tasks disabled during the venv teardown
- # -- in a finally so a failed teardown/creation can never strand the
- # user's gateway autostart in the disabled state. Same function scope,
- # so the list survives even under the stage-per-process bootstrap.
- # Deliberately NOT started here -- dependencies aren't installed yet;
- # the task fires normally on next logon and `hermes update` / the
- # gateway resume path handles the immediate restart.
- if ($gatewayTasksDisabled -and $gatewayTasksDisabled.Count -gt 0) {
- foreach ($tn in $gatewayTasksDisabled) {
- schtasks /Change /TN $tn /ENABLE 2>$null | Out-Null
- }
- Write-Info "Re-enabled gateway autostart task(s): $($gatewayTasksDisabled -join ', ')"
- }
- }
-
- Write-Success "Virtual environment ready (Python $PythonVersion)"
-}
-
-function Get-PendingVenvBackup {
- # Rollback source recorded by Install-Venv (#83149). Returns the parked
- # directory name, or $null when there is nothing to roll back to. A marker
- # pointing at a directory that no longer exists is stale -- drop it.
- $markerPath = Join-Path $InstallDir "venv.pending-backup"
- if (-not (Test-Path -LiteralPath $markerPath -PathType Leaf)) { return $null }
- $name = (Get-Content -LiteralPath $markerPath -ErrorAction SilentlyContinue | Select-Object -First 1)
- if ($name) { $name = $name.Trim() }
- if (-not $name -or -not (Test-Path -LiteralPath (Join-Path $InstallDir $name))) {
- Remove-Item -LiteralPath $markerPath -Force -ErrorAction SilentlyContinue
- return $null
- }
- return $name
-}
-
-function Complete-VenvTransaction {
- # Commit: dependency install + baseline imports passed, so the previous
- # venv is no longer needed as a rollback source. Best-effort delete; a
- # tree still held open just stays parked for the next install's sweep.
- $backupName = Get-PendingVenvBackup
- if (-not $backupName) { return }
- $backupPath = Join-Path $InstallDir $backupName
- Remove-Item -LiteralPath $backupPath -Recurse -Force -ErrorAction SilentlyContinue
- if (Test-Path -LiteralPath $backupPath) {
- Write-Warn "Old venv parked at $backupName (a process still holds files in it); it will be cleaned up on the next install"
- }
- Remove-Item -LiteralPath (Join-Path $InstallDir "venv.pending-backup") -Force -ErrorAction SilentlyContinue
-}
-
-function Restore-VenvBackup {
- # Rollback: the dependency stage failed after Install-Venv replaced the
- # venv. Park the unusable replacement and restore the previous working
- # venv so Hermes (and the venv-blocker probe) stay usable (#83149).
- $backupName = Get-PendingVenvBackup
- if (-not $backupName) { return }
- try {
- if (Test-Path -LiteralPath (Join-Path $InstallDir "venv")) {
- $failedVenvName = "venv.failed.{0}-{1}" -f (Get-Date -Format "yyyyMMddHHmmss"), ([Guid]::NewGuid().ToString("N"))
- Rename-Item -LiteralPath (Join-Path $InstallDir "venv") -NewName $failedVenvName -ErrorAction Stop
- Write-Warn "Failed replacement parked at $failedVenvName"
- }
- Rename-Item -LiteralPath (Join-Path $InstallDir $backupName) -NewName "venv" -ErrorAction Stop
- Remove-Item -LiteralPath (Join-Path $InstallDir "venv.pending-backup") -Force -ErrorAction SilentlyContinue
- Write-Warn "Restored previous virtual environment after failed dependency install"
- } catch {
- Write-Warn "Could not restore previous venv (still parked at $backupName): $($_.Exception.Message)"
- }
-}
-
-function Install-Dependencies {
- Write-Info "Installing dependencies..."
-
- Push-Location $InstallDir
-
- if (-not $NoVenv) {
- # Tell uv to install into our venv (no activation needed)
- $env:VIRTUAL_ENV = "$InstallDir\venv"
- }
-
- # Re-pin UV_PYTHON to the venv interpreter. Install-Venv already does this,
- # but the bootstrap runs install stages (venv, python-deps) as separate
- # processes, so the env var set in Install-Venv does NOT survive into a
- # separate python-deps invocation. Re-deriving it here covers that path.
- # Without it, an inherited $env:UV_PYTHON = "3.14" makes the uv sync/pip
- # tiers below recreate the venv at 3.14 and fail the maturin source build
- # (no cp314 wheels yet).
- if (-not $NoVenv) {
- $venvPythonExe = Join-Path $InstallDir "venv\Scripts\python.exe"
- if (Test-Path $venvPythonExe) {
- $env:UV_PYTHON = $venvPythonExe
- }
- }
-
- # Hash-verified install (Tier 0) -- when uv.lock is present, prefer
- # `uv sync --locked`. The lockfile records SHA256 hashes for every
- # transitive dependency, so a compromised transitive (different hash
- # than what we shipped) is REJECTED by the resolver. This is the
- # *only* path that protects against the "direct dep is fine, but the
- # dep's dep got worm-poisoned overnight" failure mode. The
- # `uv pip install` tiers below re-resolve transitives fresh from PyPI
- # without any hash verification -- they exist to keep installs working
- # when the lockfile is stale, missing, or out-of-sync with the
- # current extras spec, NOT because they're equivalent in posture.
- #
- # Everything through the baseline-import gate runs inside the venv
- # transaction opened by Install-Venv (#83149): on any failure the parked
- # previous venv is restored before the error propagates, and the parked
- # tree is deleted only after the imports prove the replacement usable.
- try {
- if (Test-Path "uv.lock") {
- Write-Info "Trying tier: hash-verified (uv.lock) ..."
- # Critical flag choice: `--extra all`, NOT `--all-extras`.
- # --all-extras = every [project.optional-dependencies] key,
- # bypassing the curated [all] extra. On Windows
- # that means [matrix] -> python-olm (no wheel,
- # needs `make` to build from sdist) and the
- # install fails.
- # --extra all = just the [all] extra's contents (curated).
- #
- # UV_PROJECT_ENVIRONMENT pins the sync target to our venv\.
- # Without it, modern uv (>=0.5) ignores VIRTUAL_ENV for `sync`
- # and creates a sibling .venv\ inside the repo -- leaving venv\
- # empty and producing the broken state where `hermes.exe` exists
- # in the wrong directory and imports fail with ModuleNotFoundError.
- # (Mirrors the same flag in scripts/install.sh::install_deps.)
- $env:UV_PROJECT_ENVIRONMENT = "$InstallDir\venv"
- Invoke-NativeWithRelaxedErrorAction { & $UvCmd sync --extra all --locked }
- if ($LASTEXITCODE -eq 0) {
- Write-Success "Main package installed (hash-verified via uv.lock)"
- $script:InstalledTier = "hash-verified (uv.lock)"
- # Skip the rest of the tiered cascade -- we already have a
- # complete, hash-verified install.
- $skipPipFallback = $true
- } else {
- Write-Warn "uv.lock sync failed (lockfile may be stale), falling back to PyPI resolve..."
- $skipPipFallback = $false
- }
- } else {
- Write-Info "uv.lock not found -- falling back to PyPI resolve (no hash verification)"
- $skipPipFallback = $false
- }
-
- # Install main package. Tiered fallback so a single flaky transitive
- # doesn't silently drop everything. Each tier's stdout/stderr is
- # preserved -- no Out-Null swallowing -- so the user can see what failed.
- #
- # Tier 1: [all] -- the curated extra in pyproject.toml.
- # Tier 2: [all] minus the currently-broken extras list ($brokenExtras).
- # Edit $brokenExtras below when something on PyPI breaks; this
- # lets users keep the rest of [all] when one transitive is
- # unavailable. The list of [all]'s contents is parsed from
- # pyproject.toml at runtime -- there is NO hand-mirrored copy
- # to drift out of sync.
- # Tier 3: bare `.` -- last-resort so at least the core CLI launches.
-
- # Currently-broken extras. Edit this list when an upstream package
- # gets quarantined / yanked / breaks resolution. Empty means everything
- # in [all] should be installable; populate with the names of extras
- # whose deps are temporarily unavailable.
- $brokenExtras = @()
-
- # Parse [project.optional-dependencies].all from pyproject.toml.
- # tomllib is stdlib on Python 3.11+ which the bootstrap guarantees.
- $pythonExeForParse = if (-not $NoVenv) { "$InstallDir\venv\Scripts\python.exe" } else { (& $UvCmd python find $PythonVersion) }
- $allExtras = @()
- if (Test-Path $pythonExeForParse) {
- $parsed = & $pythonExeForParse -c @"
-import re, sys, tomllib
-try:
- with open('pyproject.toml', 'rb') as fh:
- data = tomllib.load(fh)
- specs = data['project']['optional-dependencies']['all']
- out = []
- for s in specs:
- m = re.search(r'hermes-agent\[([\w-]+)\]', s)
- if m: out.append(m.group(1))
- print(','.join(out))
-except Exception:
- sys.exit(1)
-"@ 2>$null
- if ($LASTEXITCODE -eq 0 -and $parsed) {
- $allExtras = $parsed.Trim().Split(',')
- }
- }
- if (-not $allExtras -or $allExtras.Count -eq 0) {
- Write-Warn "Could not parse [all] from pyproject.toml; Tier 2 will be a no-op."
- $safeAll = "all"
- } else {
- $safeAll = ($allExtras | Where-Object { $brokenExtras -notcontains $_ }) -join ","
- }
- $brokenLabel = if ($brokenExtras) { ($brokenExtras -join ", ") } else { "none" }
-
- $installTiers = @(
- @{ Name = "all"; Spec = ".[all]" },
- @{ Name = "all minus known-broken ($brokenLabel)"; Spec = ".[$safeAll]" },
- @{ Name = "core only (no extras)"; Spec = "." }
- )
- $installed = $skipPipFallback
- if (-not $skipPipFallback) {
- foreach ($tier in $installTiers) {
- Write-Info "Trying tier: $($tier.Name) ..."
- Invoke-NativeWithRelaxedErrorAction { & $UvCmd pip install -e $tier.Spec }
- if ($LASTEXITCODE -eq 0) {
- Write-Success "Main package installed ($($tier.Name))"
- $script:InstalledTier = $tier.Name
- $installed = $true
- break
- }
- Write-Warn "Tier '$($tier.Name)' failed (exit $LASTEXITCODE). Trying next tier..."
- }
- }
- if (-not $installed) {
- throw "Failed to install hermes-agent package even with no extras. Inspect the uv pip install output above."
- }
-
- # Baseline-import gate. Even if a tier reported success above, the
- # actual deps may have landed somewhere other than $InstallDir\venv\
- # (e.g. uv 0.5+ syncing into a sibling .venv\ when UV_PROJECT_ENVIRONMENT
- # isn't set, leaving venv\ empty and hermes.exe broken with
- # `ModuleNotFoundError: No module named 'dotenv'` on first run).
- # We probe via the venv's own python so a misdirected sync is caught
- # here, not 30 seconds later when the user runs `hermes`.
- if (-not $NoVenv) {
- $venvPython = "$InstallDir\venv\Scripts\python.exe"
- if (-not (Test-Path $venvPython)) {
- throw "Install reported success but $venvPython does not exist. The dependency sync likely landed in a sibling .venv\ directory. Re-run the installer; if it persists, close Hermes processes and preserve existing venv directories before retrying. Do not delete venv in place."
- }
- # Relax EAP=Stop while running the import probe. Python writes
- # deprecation warnings and import-system info to stderr; under
- # EAP=Stop the 2>&1 merge wraps those as ErrorRecord objects and
- # throws even when the imports succeed. $LASTEXITCODE is the
- # reliable signal (it's 0 iff the python invocation exited 0,
- # regardless of what was written to stderr).
- $prevEAP = $ErrorActionPreference
- $ErrorActionPreference = "Continue"
- & $venvPython -c "import dotenv, openai, rich, prompt_toolkit" 2>&1 | Out-Null
- $importExitCode = $LASTEXITCODE
- $ErrorActionPreference = $prevEAP
- if ($importExitCode -ne 0) {
- $sibling = "$InstallDir\.venv"
- $hint = if (Test-Path $sibling) {
- "Detected sibling .venv\ at $sibling -- uv synced there instead of venv\. Close Hermes processes, preserve the existing venv, and rerun the installer so the transactional recovery path can move directories safely."
- } else {
- "Recover with: cd '$InstallDir'; `$env:UV_PROJECT_ENVIRONMENT='$InstallDir\venv'; uv sync --extra all --locked"
- }
- throw "Baseline imports failed in $InstallDir\venv (dotenv/openai/rich/prompt_toolkit). The install completed but dependencies are not in the venv. $hint"
- }
- Write-Success "Baseline imports verified in venv"
- }
-
- # Commit the venv transaction: the dependency install completed and the
- # baseline imports passed, so the previous venv is no longer needed as a
- # rollback source (#83149).
- Complete-VenvTransaction
- } catch {
- # Dependency install or import validation failed: restore the previous
- # working venv (parked by Install-Venv) before surfacing the error, so
- # a failed update leaves Hermes and its blocker probe usable.
- Restore-VenvBackup
- Pop-Location
- throw
- }
-
- if (-not $NoVenv) {
- # uv on Windows can register hermes.exe in dist-info/RECORD but fail to
- # materialise the .exe (file lock during self-update, distlib edge case).
- # Catch it here so a fresh install/update does not finish with a broken
- # `hermes` command while hermes-agent.exe / hermes-acp.exe exist
- $scriptsDir = Join-Path $InstallDir "venv\Scripts"
- $pythonExe = Join-Path $scriptsDir "python.exe"
- if ((Test-Path $scriptsDir) -and (Test-Path $pythonExe)) {
- $scriptNames = & $pythonExe -c @"
-import tomllib
-with open('pyproject.toml', 'rb') as fh:
- scripts = tomllib.load(fh).get('project', {}).get('scripts', {}) or {}
-print(','.join(scripts))
-"@ 2>$null
- if ($LASTEXITCODE -eq 0 -and $scriptNames) {
- $expected = @($scriptNames.Trim().Split(',') | Where-Object { $_ })
- $missing = @()
- foreach ($name in $expected) {
- $exe = Join-Path $scriptsDir "$name.exe"
- if (-not (Test-Path $exe)) { $missing += "$name.exe" }
- }
- if ($missing.Count -gt 0) {
- Write-Warn "Console entry point(s) missing: $($missing -join ', ')"
- Write-Info "Reinstalling entry points..."
- $env:UV_PROJECT_ENVIRONMENT = "$InstallDir\venv"
- Invoke-NativeWithRelaxedErrorAction { & $UvCmd pip install --reinstall -e . }
- $stillMissing = @()
- foreach ($name in $expected) {
- $exe = Join-Path $scriptsDir "$name.exe"
- if (-not (Test-Path $exe)) { $stillMissing += "$name.exe" }
- }
- if ($stillMissing.Count -gt 0) {
- Write-Warn "Entry points still missing after repair: $($stillMissing -join ', ')"
- Write-Info "Workaround: `"$pythonExe`" -m hermes_cli.main <command>"
- } else {
- Write-Success "Console entry points restored"
- }
- }
- }
- }
- }
-
- # Verify the dashboard deps specifically -- they're the most common thing
- # users hit and lazy-import errors from `hermes dashboard` are confusing.
- # If tier 1 failed (the common case), [web] was still picked up by tiers
- # 2-3; only tier 4 leaves you without it.
- $pythonExe = if (-not $NoVenv) { "$InstallDir\venv\Scripts\python.exe" } else { (& $UvCmd python find $PythonVersion) }
- if (Test-Path $pythonExe) {
- $webOk = $false
- $webServerSyntaxOk = $false
- # Relax EAP=Stop while running the import probe; see the matching
- # comment on the baseline-imports check above. Python writes
- # deprecation warnings to stderr and we don't want those wrapped
- # as ErrorRecords that silently force the "not importable" path
- # even when fastapi/uvicorn are actually installed.
- $prevEAP = $ErrorActionPreference
- $ErrorActionPreference = "Continue"
- try {
- & $pythonExe -c "import fastapi, uvicorn" 2>&1 | Out-Null
- if ($LASTEXITCODE -eq 0) { $webOk = $true }
- } catch { }
- try {
- & $pythonExe -m py_compile "$InstallDir\hermes_cli\web_server.py" 2>&1 | Out-Null
- if ($LASTEXITCODE -eq 0) { $webServerSyntaxOk = $true }
- } catch { }
- $ErrorActionPreference = $prevEAP
- if (-not $webOk) {
- Write-Warn "fastapi/uvicorn not importable -- `hermes dashboard` will not work."
- Write-Info "Attempting targeted install of [web] extra as last resort..."
- & $UvCmd pip install -e ".[web]"
- if ($LASTEXITCODE -eq 0) {
- Write-Success "[web] extra installed; `hermes dashboard` should now work."
- } else {
- Write-Warn "Could not install [web] extra. Run manually: uv pip install --python `"$pythonExe`" `"fastapi>=0.104,<1`" `"uvicorn[standard]>=0.24,<1`""
- }
- }
- if (-not $webServerSyntaxOk) {
- throw "dashboard backend source failed syntax check: hermes_cli/web_server.py"
- }
- }
-
- Pop-Location
-
- Write-Success "All dependencies installed"
-}
-
-function Install-HermesCommandLaunchers {
- param(
- [Parameter(Mandatory=$true)] [string]$Root,
- [Parameter(Mandatory=$true)] [string]$Destination
- )
-
- # Expose ONLY the hermes launchers on PATH -- never the whole
- # venv\Scripts directory, which contains python.exe / pip.exe and
- # silently hijacks the `python` command in every terminal (#83797).
- # Requiring hermes.exe before creating the destination keeps the PATH
- # stage from reporting success with an unusable command (PR #92092).
- $scriptsDir = Join-Path $Root "venv\Scripts"
- $requiredSource = Join-Path $scriptsDir "hermes.exe"
- if (-not (Test-Path -LiteralPath $requiredSource -PathType Leaf)) {
- throw "Cannot set up the hermes command: required launcher not found: $requiredSource"
- }
-
- New-Item -ItemType Directory -Force -Path $Destination | Out-Null
-
- # Launcher form depends on the venv (keep in lockstep with
- # hermes_cli/_install_repair.py): a normal venv's exe trampoline
- # embeds an absolute interpreter path and survives copying; a
- # relocatable venv's trampoline (managed_uv rebuilds use
- # --relocatable) resolves relative to its own location, and a copy
- # dies with 'uv trampoline failed to canonicalize script path' --
- # those get a .cmd delegator invoking the in-venv exe instead.
- $pyvenvCfg = Join-Path $Root "venv\pyvenv.cfg"
- $venvRelocatable = $false
- if (Test-Path -LiteralPath $pyvenvCfg) {
- $venvRelocatable = [bool](Select-String -Path $pyvenvCfg -Pattern '^\s*relocatable\s*=\s*true\s*$' -Quiet)
- }
- foreach ($launcher in @("hermes", "hermes-acp")) {
- $src = Join-Path $scriptsDir "$launcher.exe"
- if (-not (Test-Path -LiteralPath $src -PathType Leaf)) { continue }
- if ($venvRelocatable) {
- Remove-Item (Join-Path $Destination "$launcher.exe") -Force -ErrorAction SilentlyContinue
- Set-Content -Path (Join-Path $Destination "$launcher.cmd") -Value "@echo off`r`n`"$src`" %*" -Encoding Ascii
- } else {
- Remove-Item (Join-Path $Destination "$launcher.cmd") -Force -ErrorAction SilentlyContinue
- Copy-Item -Force -LiteralPath $src -Destination (Join-Path $Destination "$launcher.exe")
- }
- }
-
- # Verify either staged form before the caller mutates PATH.
- $requiredExe = Join-Path $Destination "hermes.exe"
- $requiredCmd = Join-Path $Destination "hermes.cmd"
- if (-not ((Test-Path -LiteralPath $requiredExe -PathType Leaf) -or
- (Test-Path -LiteralPath $requiredCmd -PathType Leaf))) {
- throw "Cannot set up the hermes command: launcher was not installed: $requiredExe"
- }
- return $Destination
-}
-
-function Set-PathVariable {
- Write-Info "Setting up hermes command..."
-
- if ($NoVenv) {
- $hermesBin = "$InstallDir"
- } else {
- # $HermesHome\bin is the managed binary dir (shared with the managed
- # uv), OUTSIDE the git checkout: `hermes update`'s autostash
- # (git stash push --include-untracked) deletes untracked files from
- # the working tree, which silently removed the launchers an earlier
- # installer staged under hermes-agent\bin. No git operation can ever
- # touch this dir. Staging and verification live in
- # Install-HermesCommandLaunchers, which throws BEFORE any PATH
- # mutation when the launchers cannot be staged.
- $hermesBin = "$HermesHome\bin"
- Install-HermesCommandLaunchers -Root $InstallDir -Destination $hermesBin | Out-Null
- }
-
- $currentPath = [Environment]::GetEnvironmentVariable("Path", "User")
-
- # Migrate older layouts off the user PATH:
- # venv\Scripts -- shadowed the user's python (#83797)
- # hermes-agent\bin -- lived inside the git checkout, where the update
- # autostash could sweep the launchers off disk
- # The hermes-agent\bin FILES are left in place on purpose: editor/ACP
- # configs that captured absolute launcher paths keep working, and the
- # dir is git-ignored so it cannot dirty the checkout.
- if (-not $NoVenv) {
- $legacyEntries = @("$InstallDir\venv\Scripts", "$InstallDir\bin")
- $items = @(($currentPath -split ';') | Where-Object { $_ })
- $cleaned = @($items | Where-Object { $legacyEntries -notcontains $_ })
- if ($cleaned.Count -ne $items.Count) {
- $currentPath = $cleaned -join ";"
- [Environment]::SetEnvironmentVariable("Path", $currentPath, "User")
- Write-Info "Removed legacy launcher entries from user PATH (kept hermes via $hermesBin)"
- }
- }
-
- if ($currentPath -notlike "*$hermesBin*") {
- [Environment]::SetEnvironmentVariable(
- "Path",
- "$hermesBin;$currentPath",
- "User"
- )
- Write-Success "Added to user PATH: $hermesBin"
- } else {
- Write-Info "PATH already configured"
- }
-
- # Set HERMES_HOME so the Python code finds config/data in the right place.
- # Only needed on Windows where we install to %LOCALAPPDATA%\hermes instead
- # of the Unix default ~/.hermes
- $currentHermesHome = [Environment]::GetEnvironmentVariable("HERMES_HOME", "User")
- if (-not $currentHermesHome -or $currentHermesHome -ne $HermesHome) {
- [Environment]::SetEnvironmentVariable("HERMES_HOME", $HermesHome, "User")
- Write-Success "Set HERMES_HOME=$HermesHome"
- }
- $env:HERMES_HOME = $HermesHome
-
- # Update current session
- $env:Path = "$hermesBin;$env:Path"
-
- Write-Success "hermes command ready"
-}
-
-function Write-BootstrapMarker {
- # Writes $InstallDir\.hermes-bootstrap-complete which tells the Hermes
- # desktop app (apps/desktop/electron/main.ts) "install.ps1 ran
- # successfully -- DON'T trigger the legacy first-launch bootstrap
- # runner."
- #
- # Schema mirrors what main.ts's writeBootstrapMarker() / isBootstrap
- # Complete() expect. Keep this in lockstep when either side changes:
- # apps/desktop/electron/main.ts lines 1199-1222
- # BOOTSTRAP_MARKER_SCHEMA_VERSION = 1 (line 187)
- #
- # Pinned commit/branch come from -Commit + -Branch flags (passed by
- # Hermes-Setup.exe) or fall back to whatever git resolves in the
- # checkout. The desktop validates schemaVersion + pinnedCommit
- # length but doesn't enforce that HEAD matches the pin (users
- # update via `hermes update` which moves HEAD legitimately).
- if (-not (Test-Path $InstallDir)) {
- Write-Warn "Skipping bootstrap marker: $InstallDir doesn't exist"
- return
- }
-
- # Resolve the pinned commit: explicit -Commit wins, otherwise read
- # the checkout's HEAD via git. If git can't run, leave commit empty
- # and the marker will fail desktop validation (pinnedCommit.length
- # >= 7) -- better to be invalid than wrong.
- $pinnedCommit = $Commit
- if (-not $pinnedCommit) {
- # PS 5.1 doesn't support the ?. null-conditional operator, so
- # check Get-Command's result explicitly before reading .Source.
- $gitCmd = Get-Command git -ErrorAction SilentlyContinue
- $gitExe = if ($gitCmd) { $gitCmd.Source } else { $null }
- if ($gitExe) {
- Push-Location $InstallDir
- try {
- $resolved = & $gitExe rev-parse HEAD 2>$null
- if ($LASTEXITCODE -eq 0 -and $resolved) {
- $pinnedCommit = $resolved.Trim()
- }
- } catch {
- # Ignore -- pinnedCommit stays empty, marker stays invalid,
- # desktop falls through to its legacy bootstrap path.
- } finally {
- Pop-Location
- }
- }
- }
-
- $pinnedBranch = $Branch
- if (-not $pinnedBranch) {
- $pinnedBranch = "main" # install.ps1's own default for -Branch
- }
-
- $markerPath = Join-Path $InstallDir ".hermes-bootstrap-complete"
- $marker = [ordered]@{
- schemaVersion = 1
- pinnedCommit = $pinnedCommit
- pinnedBranch = $pinnedBranch
- completedAt = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ")
- # desktopVersion field intentionally omitted -- only the desktop
- # app knows its own version, and the marker validator doesn't
- # require it. The desktop fills it in if/when it writes its
- # own marker (e.g. after a future in-app upgrade).
- }
- $json = $marker | ConvertTo-Json -Compress:$false
-
- # Write WITHOUT a UTF-8 BOM. PowerShell 5.1's `Set-Content -Encoding UTF8`
- # always emits a BOM, and Node's plain JSON.parse rejects the BOM as an
- # unexpected character -- so a BOM'd marker would silently fail the
- # desktop's readJson(), make isBootstrapComplete() return null, and the
- # desktop would re-run the legacy bootstrap runner anyway. Defeats the
- # whole point. Use the .NET API directly for BOM-less UTF-8.
- $utf8NoBom = New-Object System.Text.UTF8Encoding $false
- [System.IO.File]::WriteAllText($markerPath, $json, $utf8NoBom)
-
- Write-Success "Bootstrap marker written: $markerPath"
-}
-
-function Copy-ConfigTemplates {
- Write-Info "Setting up configuration files..."
-
- # Create the HERMES_HOME directory structure ($HermesHome, default %LOCALAPPDATA%\hermes)
- New-Item -ItemType Directory -Force -Path "$HermesHome\cron" | Out-Null
- New-Item -ItemType Directory -Force -Path "$HermesHome\sessions" | Out-Null
- New-Item -ItemType Directory -Force -Path "$HermesHome\logs" | Out-Null
- New-Item -ItemType Directory -Force -Path "$HermesHome\pairing" | Out-Null
- New-Item -ItemType Directory -Force -Path "$HermesHome\hooks" | Out-Null
- New-Item -ItemType Directory -Force -Path "$HermesHome\image_cache" | Out-Null
- New-Item -ItemType Directory -Force -Path "$HermesHome\audio_cache" | Out-Null
- New-Item -ItemType Directory -Force -Path "$HermesHome\memories" | Out-Null
- New-Item -ItemType Directory -Force -Path "$HermesHome\skills" | Out-Null
-
-
- # Create .env
- $envPath = "$HermesHome\.env"
- if (-not (Test-Path $envPath)) {
- $examplePath = "$InstallDir\.env.example"
- if (Test-Path $examplePath) {
- Copy-Item $examplePath $envPath
- Write-Success "Created $envPath from template"
- } else {
- New-Item -ItemType File -Force -Path $envPath | Out-Null
- Write-Success "Created $envPath"
- }
- } else {
- Write-Info "$envPath already exists, keeping it"
- }
-
- # Create config.yaml
- $configPath = "$HermesHome\config.yaml"
- if (-not (Test-Path $configPath)) {
- $examplePath = "$InstallDir\cli-config.yaml.example"
- if (Test-Path $examplePath) {
- Copy-Item $examplePath $configPath
- Write-Success "Created $configPath from template"
- }
- } else {
- Write-Info "$configPath already exists, keeping it"
- }
-
- # Create SOUL.md if it doesn't exist (global persona file).
- # IMPORTANT: write without a BOM. Windows PowerShell 5.1's
- # ``Set-Content -Encoding UTF8`` writes UTF-8 WITH a byte-order-mark
- # (the default PS5 behaviour), and Hermes's prompt-injection scanner
- # flags the BOM as an invisible unicode character and refuses to
- # load the file. PS7's ``-Encoding utf8NoBOM`` fixes that but we
- # don't control which PowerShell version the user has. Go direct
- # to .NET with an explicit UTF8Encoding($false) -- BOM-free on every
- # PowerShell version.
- $soulPath = "$HermesHome\SOUL.md"
- if (-not (Test-Path $soulPath)) {
- # MUST match DEFAULT_SOUL_MD in hermes_cli/default_soul.py. The runtime
- # upgrades the old comment-only scaffold to this text on next run, so
- # drift is self-healing, but keep them in sync to avoid first-run churn.
- $soulContent = @"
-You are Hermes Agent, an intelligent AI assistant created by Nous Research. You are helpful, knowledgeable, and direct. You assist users with a wide range of tasks including answering questions, writing and editing code, analyzing information, creative work, and executing actions via your tools. You communicate clearly, admit uncertainty when appropriate, and prioritize being genuinely useful over being verbose unless otherwise directed below. Be targeted and efficient in your exploration and investigations.
-"@
- $utf8NoBom = New-Object System.Text.UTF8Encoding($false)
- [System.IO.File]::WriteAllText($soulPath, $soulContent, $utf8NoBom)
- Write-Success "Created $soulPath (edit to customize personality)"
- }
-
- Write-Success "Configuration directory ready: $HermesHome"
-
- # Seed bundled skills into $HermesHome\skills (manifest-based, one-time per skill)
- Write-Info "Syncing bundled skills to $HermesHome\skills ..."
- $pythonExe = "$InstallDir\venv\Scripts\python.exe"
- if (Test-Path $pythonExe) {
- try {
- # Force the child python.exe to emit UTF-8 on its stdout/stderr.
- # On non-UTF-8 Windows locales (CP936/GBK zh-CN) Python defaults
- # its stream encoding to the active codepage and crashes on glyphs
- # like the checkmark (U+2713) that the codepage can't encode; the
- # resulting non-UTF-8 bytes break this script's JSON result frame on
- # stdout and abort the config-templates stage. Scope to this call
- # only. (Comment kept ASCII per this file's PS 5.1 contract above.)
- $prevPythonioencoding = $env:PYTHONIOENCODING
- $prevPythonutf8 = $env:PYTHONUTF8
- $env:PYTHONIOENCODING = "utf-8"
- $env:PYTHONUTF8 = "1"
- try {
- & $pythonExe "$InstallDir\tools\skills_sync.py" 2>$null
- } finally {
- $env:PYTHONIOENCODING = $prevPythonioencoding
- $env:PYTHONUTF8 = $prevPythonutf8
- }
- Write-Success "Skills synced to $HermesHome\skills"
- } catch {
- # Fallback: simple directory copy
- $bundledSkills = "$InstallDir\skills"
- $userSkills = "$HermesHome\skills"
- if ((Test-Path $bundledSkills) -and -not (Get-ChildItem $userSkills -Exclude '.bundled_manifest' -ErrorAction SilentlyContinue)) {
- Copy-Item -Path "$bundledSkills\*" -Destination $userSkills -Recurse -Force -ErrorAction SilentlyContinue
- Write-Success "Skills copied to $HermesHome\skills"
- }
- }
- }
-}
-
-function Install-NodeDeps {
- if (-not $HasNode) {
- # Cross-process driver mode (Hermes-Setup.exe runs each -Stage NAME
- # in a fresh powershell.exe) means $script:HasNode set by Stage-Node
- # in the previous process isn't visible here. Re-probe rather than
- # trust the stale global -- Stage-Node already ran successfully or
- # the bootstrap would've aborted, so npm is reachable.
- if (-not (Get-Command npm -ErrorAction SilentlyContinue)) {
- Write-Info "Skipping Node.js dependencies (Node not installed)"
- return
- }
- }
-
- # npm lifecycle scripts need node.exe on the PATH visible to child
- # cmd.exe processes. Stage-Node may have run in a prior process, so
- # re-apply here before any npm install (regression #48130).
- Ensure-NodeExeOnPath | Out-Null
-
- # Resolve npm explicitly to npm.cmd, NOT npm.ps1. Node.js on Windows
- # ships BOTH npm.cmd (a batch shim) and npm.ps1 (a PowerShell shim).
- # Get-Command's default ordering picks whichever comes first in PATHEXT,
- # and on many systems that's .ps1 -- but .ps1 requires scripts to be
- # enabled in PowerShell's execution policy, which most Windows users
- # don't have (the Restricted / RemoteSigned default blocks unsigned
- # .ps1 files). .cmd has no such restriction and works on every box.
- #
- # Strategy: look next to the npm shim we found and prefer npm.cmd if
- # it exists in the same directory. Fall back to whatever Get-Command
- # returned if we can't find a .cmd sibling.
- $npmCmd = Get-Command npm -ErrorAction SilentlyContinue
- if (-not $npmCmd) {
- Write-Warn "npm not found on PATH -- skipping Node.js dependencies."
- Write-Info "Open a new PowerShell window and re-run 'hermes setup tools' later."
- return
- }
- $npmExe = $npmCmd.Source
- if ($npmExe -like "*.ps1") {
- $npmCmdSibling = Join-Path (Split-Path $npmExe -Parent) "npm.cmd"
- if (Test-Path $npmCmdSibling) {
- Write-Info "Using npm.cmd (PowerShell execution policy blocks npm.ps1)"
- $npmExe = $npmCmdSibling
- } else {
- Write-Warn "Only npm.ps1 available -- install may fail if script execution is disabled."
- Write-Info " If it fails, either enable PS script execution or install Node via winget."
- }
- }
-
- # Wall-clock ceiling for each npm / Playwright invocation in this stage.
- # scripts/install.sh has time-boxed the same work with
- # ``run_with_timeout "$NODE_DEPS_TIMEOUT"`` (600s default) since #39219;
- # Windows never got the guard, so a stalled registry fetch or a wedged
- # Chromium extraction (#76222, #84614) froze the installer forever -- one
- # user left it running 12+ hours overnight. Same env override as bash
- # for very slow links.
- $nodeDepsTimeoutSec = 600
- if ($env:NODE_DEPS_TIMEOUT -match '^\d+$') {
- $nodeDepsTimeoutSec = [int]$env:NODE_DEPS_TIMEOUT
- }
-
- # Helper: run a native command with a hard wall-clock timeout while
- # still streaming its output live. Returns the exit code, or 124 on
- # timeout (the same convention as coreutils ``timeout`` and bash's
- # run_with_timeout).
- #
- # Launcher notes: ``Start-Process -FilePath npm.cmd`` fails with
- # ``%1 is not a valid Win32 application`` on some PowerShell versions
- # because Start-Process bypasses cmd.exe / PATHEXT and expects a real
- # PE file -- so route through cmd.exe, which IS a real PE, honours .cmd
- # batch shims, and performs the stdout+stderr merge into the log file
- # natively. The parent then tails the log into the console each poll
- # tick, preserving the live progress that makes a 3-minute download
- # distinguishable from a hang (the whole reason _Run-NpmInstall streams
- # output in the first place). ``Wait-Job -Timeout`` was rejected: jobs
- # swallow live output, and Stop-Job leaves the npm child running.
- # taskkill /T kills the real process tree. Works on Windows PowerShell
- # 5.1 -- no pwsh-only primitives.
- function _Invoke-NativeWithTimeout(
- [string]$exePath, [string]$argLine, [string]$workDir,
- [string]$logPath, [int]$timeoutSec
- ) {
- $cmdLine = "/d /s /c "" ""$exePath"" $argLine > ""$logPath"" 2>&1 """
- $proc = Start-Process -FilePath $env:ComSpec -ArgumentList $cmdLine `
- -WorkingDirectory $workDir -NoNewWindow -PassThru
- $deadline = [DateTime]::UtcNow.AddSeconds($timeoutSec)
- $shown = 0
- function _Drain-NewLines([string]$path, [ref]$count) {
- $lines = @(Get-Content $path -ErrorAction SilentlyContinue)
- if ($lines.Count -gt $count.Value) {
- $lines[$count.Value..($lines.Count - 1)] | ForEach-Object {
- Write-Host " $_" -ForegroundColor DarkGray
- }
- $count.Value = $lines.Count
- }
- }
- while (-not $proc.HasExited) {
- if ([DateTime]::UtcNow -gt $deadline) {
- & taskkill /T /F /PID $proc.Id 2>&1 | Out-Null
- return 124
- }
- Start-Sleep -Milliseconds 750
- _Drain-NewLines $logPath ([ref]$shown)
- }
- _Drain-NewLines $logPath ([ref]$shown)
- return $proc.ExitCode
- }
-
- # Helper: run "npm install" in a given directory and surface the real
- # error when it fails. Returns $true on success.
- function _Run-NpmInstall([string]$label, [string]$installDir, [string]$logPath, [string]$npmPath) {
- Push-Location $installDir
- # Capture EAP outside the try block so the catch's restore call always
- # has a meaningful value (see Install-Uv for the full rationale).
- $prevEAP = $ErrorActionPreference
- try {
- # The helper streams npm's output to BOTH the console and the log
- # file, so the user watches real progress instead of a frozen
- # "Installing..." line (on a fresh VM the install is 1-3 minutes;
- # total silence is indistinguishable from a hang) -- and the
- # wall-clock ceiling turns a genuinely stalled install (#76222
- # class) into a diagnosable failure instead of an overnight freeze.
- #
- # Relax EAP around the invocation: with EAP=Stop (set at the top
- # of this script), PowerShell can wrap stray stderr from the
- # launcher plumbing as ErrorRecord objects and throw even though
- # npm exited 0. This is the same issue Test-Python and Install-Uv
- # work around for uv's stderr-emitting installer. Check success
- # via the returned exit code, which is reliable regardless of
- # stderr noise.
- $ErrorActionPreference = "Continue"
- $code = _Invoke-NativeWithTimeout $npmPath "install --silent" `
- $installDir $logPath $nodeDepsTimeoutSec
- $ErrorActionPreference = $prevEAP
- if ($code -eq 0) {
- Write-Success "$label dependencies installed"
- Remove-Item -Force $logPath -ErrorAction SilentlyContinue
- return $true
- }
- if ($code -eq 124) {
- Write-Warn "$label npm install timed out after $([math]::Round($nodeDepsTimeoutSec / 60)) minutes -- a stalled download, wedged extraction, or file lock is the usual cause."
- Write-Info " Re-run the installer to retry (completed stages are skipped)."
- Write-Info " Slow connection? Raise the ceiling: set NODE_DEPS_TIMEOUT to seconds (default 600)."
- } else {
- Write-Warn "$label npm install failed -- exit code $code"
- }
- if (Test-Path $logPath) {
- $errText = (Get-Content $logPath -Raw -ErrorAction SilentlyContinue)
- if ($errText) {
- $snippet = if ($errText.Length -gt 1200) { $errText.Substring(0, 1200) + "..." } else { $errText }
- Write-Info " npm output:"
- foreach ($line in $snippet -split "`n") {
- Write-Host " $line" -ForegroundColor DarkGray
- }
- Write-Info " Full log: $logPath"
- Show-NpmCertHint $errText | Out-Null
- Write-NpmDebugLogTail -NpmOutput $errText
- }
- }
- Write-Info "Run manually later: cd `"$installDir`"; npm install"
- return $false
- } catch {
- if ($prevEAP) { $ErrorActionPreference = $prevEAP }
- Write-Warn "$label npm install could not be launched: $_"
- return $false
- } finally {
- Pop-Location
- }
- }
-
- # Browser tools
- if (Test-Path "$InstallDir\package.json") {
- Write-Info "Installing Node.js dependencies (browser tools)..."
- $browserLog = "$env:TEMP\hermes-npm-browser-$(Get-Random).log"
- $browserNpmOk = _Run-NpmInstall "Browser tools" $InstallDir $browserLog $npmExe
-
- # Install Playwright Chromium (mirrors scripts/install.sh behaviour for
- # Linux). Without this, tools/browser_tool.py::check_browser_requirements
- # returns False (no Chromium under %LOCALAPPDATA%\ms-playwright), and the
- # browser_* tools are silently filtered out of the agent's tool schema.
- # System Chrome at "C:\Program Files\Google\Chrome\..." is NOT used by
- # agent-browser -- it expects a Playwright-managed Chromium.
- if ($browserNpmOk) {
- Write-Info "Installing browser engine (Playwright Chromium)..."
- # npx lives next to npm in the same bin dir. Prefer .cmd to dodge
- # the same execution-policy gotcha that affects npm.ps1 (see above).
- $npmDir = Split-Path $npmExe -Parent
- $npxExe = $null
- foreach ($cand in @("npx.cmd", "npx.exe", "npx")) {
- $try = Join-Path $npmDir $cand
- if (Test-Path $try) { $npxExe = $try; break }
- }
- if (-not $npxExe) {
- $npxCmd = Get-Command npx -ErrorAction SilentlyContinue
- if ($npxCmd) { $npxExe = $npxCmd.Source }
- }
- if (-not $npxExe) {
- Write-Warn "npx not found -- cannot install Playwright Chromium."
- Write-Info "Run manually later: cd `"$InstallDir`"; npx playwright install chromium"
- } else {
- $pwLog = "$env:TEMP\hermes-playwright-install-$(Get-Random).log"
- Push-Location $InstallDir
- # Capture EAP outside the try block so the catch's restore call
- # always has a meaningful value (see Install-Uv for the full
- # rationale).
- $prevEAP = $ErrorActionPreference
- try {
- # Playwright Chromium is ~170MB compressed and the
- # download regularly takes 3-10 minutes on a fresh
- # VM. Tee the output to console + log so the user
- # sees download progress in real time instead of
- # staring at a silent prompt that looks hung. See
- # _Run-NpmInstall above for the same pattern and
- # the rationale behind 2>&1 before the pipe.
- Write-Info "(this can take several minutes -- streaming progress below)"
- # --yes auto-accepts npx's "Need to install [email protected]"
- # confirmation prompt. Without it, npx 7+ blocks on stdin
- # waiting for a y/N answer that never comes when this is
- # invoked through a pipeline (Tee-Object disconnects stdin
- # from the user's TTY), and the install hangs indefinitely
- # after printing "Need to install the following packages:
- #
- # Relax EAP around the playwright invocation: playwright
- # emits a "Chromium downloaded to ..." success banner to
- # stderr after a successful install. The launcher merges
- # stderr into the log natively, but keep EAP relaxed so
- # stray plumbing stderr can't fire the catch block with a
- # mangled banner even though the install succeeded. Check
- # the returned exit code instead, which is the reliable
- # signal.
- #
- # The wall-clock ceiling is the #76222 / #84614 fix: the
- # Chromium download reaches 100% and the extraction wedges
- # (or the registry fetch stalls), and without a bound the
- # installer sits on this line forever. bash has carried
- # the same 600s guard via run_playwright_install since
- # #39219.
- $ErrorActionPreference = "Continue"
- $pwCode = _Invoke-NativeWithTimeout $npxExe "--yes playwright install chromium" `
- $InstallDir $pwLog $nodeDepsTimeoutSec
- $ErrorActionPreference = $prevEAP
- if ($pwCode -eq 0) {
- Write-Success "Playwright Chromium installed (browser tools ready)"
- Remove-Item -Force $pwLog -ErrorAction SilentlyContinue
- } elseif ($pwCode -eq 124) {
- Write-Warn "Playwright Chromium install timed out after $([math]::Round($nodeDepsTimeoutSec / 60)) minutes."
- Write-Warn "This usually means a stalled download or a wedged archive extraction (a locked previous browser version can also cause it)."
- Write-Warn "Browser tools will not work until Chromium is installed."
- if (Test-Path $pwLog) { Write-Info " Partial log: $pwLog" }
- Write-Info "Run manually later: cd `"$InstallDir`"; npx playwright install chromium"
- } else {
- Write-Warn "Playwright Chromium install failed -- exit code $pwCode"
- Write-Warn "Browser tools will not work until Chromium is installed."
- if (Test-Path $pwLog) {
- $pwErr = Get-Content $pwLog -Raw -ErrorAction SilentlyContinue
- if ($pwErr) {
- $snippet = if ($pwErr.Length -gt 1200) { $pwErr.Substring(0, 1200) + "..." } else { $pwErr }
- Write-Info " playwright output:"
- foreach ($line in $snippet -split "`n") {
- Write-Host " $line" -ForegroundColor DarkGray
- }
- Write-Info " Full log: $pwLog"
- }
- }
- Write-Info "Run manually later: cd `"$InstallDir`"; npx playwright install chromium"
- }
- } catch {
- if ($prevEAP) { $ErrorActionPreference = $prevEAP }
- Write-Warn "Playwright Chromium install could not be launched: $_"
- Write-Info "Run manually later: cd `"$InstallDir`"; npx playwright install chromium"
- } finally {
- Pop-Location
- }
- }
- }
- }
-
- # TUI
- $tuiDir = "$InstallDir\ui-tui"
- if (Test-Path "$tuiDir\package.json") {
- Write-Info "Installing TUI dependencies..."
- $tuiLog = "$env:TEMP\hermes-npm-tui-$(Get-Random).log"
- [void](_Run-NpmInstall "TUI" $tuiDir $tuiLog $npmExe)
- }
-
- Install-BrowserUseCli
- Install-CuaDriver
-}
-
-# The Browser Use CLI is the default browser backend when it is runnable
-# (tools/browser_use_cli.py). Provision it at install time so fresh installs
-# don't silently fall back to the built-in browser tools. Best-effort: any
-# failure is non-fatal (browser_exec can still run via uvx, and `hermes tools`
-# can install it later).
-function Install-BrowserUseCli {
- if (-not $script:UvCmd) { Resolve-UvCmd }
- if (-not $script:UvCmd) {
- Write-Info "Skipping Browser Use CLI install (uv unavailable)"
- return
- }
- $managedBin = Join-Path $HermesHome "bin"
- $managedBu = Join-Path $managedBin "browser-use.exe"
- # MANAGED-FIRST: only Hermes' managed copy short-circuits. A browser-use
- # on the user's PATH is a side install -- resolution prefers the managed
- # copy, so it must be provisioned regardless.
- if (Test-Path $managedBu) {
- Write-Success "Browser Use CLI already installed"
- return
- }
-
- Write-Info "Installing Browser Use CLI (default browser backend)..."
- $prevEAP = $ErrorActionPreference
- $ErrorActionPreference = "Continue"
- try {
- # UV_TOOL_BIN_DIR keeps the binary inside Hermes' managed bin dir,
- # where the browser tool resolves it -- no reliance on the user PATH.
- $env:UV_TOOL_BIN_DIR = $managedBin
- $env:UV_NO_CONFIG = "1"
- & $script:UvCmd tool install browser-use 2>&1 | Out-Null
- if ($LASTEXITCODE -eq 0) {
- Write-Success "Browser Use CLI installed"
- } else {
- Write-Warn "Browser Use CLI install failed (exit $LASTEXITCODE) -- browser automation falls back to built-in tools."
- Write-Info "Install later with: uv tool install browser-use (or via 'hermes tools')"
- }
- } catch {
- Write-Warn "Browser Use CLI install failed: $_"
- } finally {
- $ErrorActionPreference = $prevEAP
- Remove-Item Env:\UV_TOOL_BIN_DIR -ErrorAction SilentlyContinue
- Remove-Item Env:\UV_NO_CONFIG -ErrorAction SilentlyContinue
- }
-}
-
-function Test-CuaDriverRuntimeContract {
- param([Parameter(Mandatory = $true)][string]$DriverPath)
-
- try {
- $versionOutput = (& $DriverPath --version 2>$null | Out-String).Trim()
- if ($LASTEXITCODE -ne 0) {
- return $false
- }
- $versionMatch = [regex]::Match($versionOutput, '(\d+\.\d+\.\d+)')
- if (-not $versionMatch.Success) {
- return $false
- }
- if ([version]($versionMatch.Groups[1].Value) -lt [version]'0.20.0') {
- return $false
- }
-
- $manifestOutput = (& $DriverPath manifest 2>$null | Out-String).Trim()
- if ($LASTEXITCODE -ne 0 -or -not $manifestOutput) {
- return $false
- }
- $manifest = $manifestOutput | ConvertFrom-Json
- if (-not $manifest.mcp_invocation.args) {
- return $false
- }
-
- $required = @{
- mcp = @('--socket', '--grant')
- serve = @(
- '--socket', '--permission-mode', '--capability-manifest',
- '--approve-capability-manifest', '--embedded'
- )
- stop = @('--socket')
- }
- foreach ($commandName in $required.Keys) {
- $command = $manifest.subcommands | Where-Object { $_.name -eq $commandName }
- if (-not $command) {
- return $false
- }
- $argNames = @($command.args | ForEach-Object { $_.name })
- foreach ($requiredArg in $required[$commandName]) {
- if ($requiredArg -notin $argNames) {
- return $false
- }
- }
- }
- return $true
- } catch {
- return $false
- }
-}
-
-# cua-driver powers the computer_use toolset (background desktop control).
-# Provision it at install time so enabling the tool later -- via `hermes
-# tools`, the dashboard, or the desktop app -- is a config flip, not a
-# surprise multi-minute binary fetch. Best-effort and non-fatal: the enable
-# paths still lazy-install via install_cua_driver() (hermes_cli/tools_config)
-# when this step was skipped or failed.
-function Install-CuaDriver {
- if ($SkipComputerUse) {
- Write-Info "Skipping Computer Use (cua-driver) install (-SkipComputerUse)"
- return
- }
- $existingCuaDriver = Get-Command cua-driver -ErrorAction SilentlyContinue
- if ($existingCuaDriver) {
- if (Test-CuaDriverRuntimeContract -DriverPath $existingCuaDriver.Source) {
- Write-Success "Computer Use driver (cua-driver) already installed and compatible"
- return
- }
- Write-Warn "Existing cua-driver is old or incomplete; repairing it"
- }
-
- Write-Info "Installing Computer Use driver (cua-driver)..."
- $prevEAP = $ErrorActionPreference
- $ErrorActionPreference = "Continue"
- try {
- # Same upstream installer `hermes computer-use install` runs. Bounded
- # via a background job: the upstream installer serializes with its own
- # lock (600s stale window), so the ceiling sits above that -- matching
- # Hermes' _CUA_INSTALLER_TIMEOUT (660s).
- $job = Start-Job -ScriptBlock {
- Invoke-RestMethod -UseBasicParsing "https://raw.githubusercontent.com/trycua/cua/main/libs/cua-driver/scripts/install.ps1" | Invoke-Expression
- }
- if (Wait-Job $job -Timeout 660) {
- Receive-Job $job -ErrorAction SilentlyContinue | Out-Null
- Remove-Job $job -Force -ErrorAction SilentlyContinue
- $installedCuaDriver = Get-Command cua-driver -ErrorAction SilentlyContinue
- if ($installedCuaDriver -and (Test-CuaDriverRuntimeContract -DriverPath $installedCuaDriver.Source)) {
- Write-Success "Computer Use driver installed (enable via 'hermes tools' -> Computer Use)"
- } else {
- Write-Warn "Computer Use driver install did not produce a compatible runtime -- repair it before enabling the tool."
- Write-Info "Install later with: hermes computer-use install"
- }
- } else {
- Stop-Job $job -ErrorAction SilentlyContinue
- Remove-Job $job -Force -ErrorAction SilentlyContinue
- Write-Warn "Computer Use driver install timed out -- it will install on demand when you enable the tool."
- Write-Info "Install later with: hermes computer-use install"
- }
- } catch {
- Write-Warn "Computer Use driver install failed: $_"
- Write-Info "Install later with: hermes computer-use install"
- } finally {
- $ErrorActionPreference = $prevEAP
- }
-}
-
-# Clear the cached Electron download + any half-written unpacked output so the
-# next `npm run pack` re-downloads and re-stages from scratch. A corrupt zip in
-# the per-user Electron download cache - most often a partial download resumed
-# into the same file, leaving concatenated junk - makes electron-builder's
-# `app-builder unpack-electron` extract a tree MISSING the electron binary, so
-# the final `electron` -> `Hermes` rename dies with ENOENT and every re-run
-# repeats the broken extraction forever.
-#
-# We deliberately do not validate the zip ourselves: the common
-# prepended/concatenated-junk corruption slips past naive checks, so a
-# self-rolled gate would skip the real-world case. We unconditionally drop the
-# cached electron-*.zip (loose copy and any @electron/get hash-subdir copy) plus
-# the stale unpacked dir, then let the caller retry once - @electron/get
-# re-downloads with its own SHASUM verification, the real source of truth.
-#
-# Returns the removed paths. Best-effort: never throws.
-function Clear-ElectronBuildCache {
- param([string]$DesktopDir)
- $removed = @()
-
- # Per-user Electron download cache dirs, honoring the overrides @electron/get
- # respects, then the Windows default (%LOCALAPPDATA%\electron\Cache).
- $cacheDirs = @()
- if ($env:electron_config_cache) { $cacheDirs += $env:electron_config_cache }
- if ($env:ELECTRON_CACHE) { $cacheDirs += $env:ELECTRON_CACHE }
- if ($env:LOCALAPPDATA) { $cacheDirs += (Join-Path $env:LOCALAPPDATA 'electron\Cache') }
- $cacheDirs += (Join-Path $HOME 'AppData\Local\electron\Cache')
-
- foreach ($dir in $cacheDirs) {
- if (-not (Test-Path -LiteralPath $dir)) { continue }
- # Recurse: the bad copy may be the top-level zip OR a copy inside an
- # @electron/get hash subdir.
- $removed += @(Get-ChildItem -LiteralPath $dir -Recurse -Filter 'electron-*.zip' -File -ErrorAction SilentlyContinue | ForEach-Object {
- try { Remove-Item -LiteralPath $_.FullName -Force -ErrorAction Stop; $_.FullName } catch { }
- })
- }
-
- # A half-written unpacked dir from an interrupted prior pack poisons the
- # rename even after the zip is fixed (win-unpacked / win-arm64-unpacked).
- $releaseDir = Join-Path $DesktopDir 'release'
- if (Test-Path -LiteralPath $releaseDir) {
- $removed += @(Get-ChildItem -LiteralPath $releaseDir -Directory -Filter '*-unpacked' -ErrorAction SilentlyContinue | ForEach-Object {
- try { Remove-Item -LiteralPath $_.FullName -Recurse -Force -ErrorAction Stop; $_.FullName } catch { }
- })
- }
-
- return $removed
-}
-
-# Last-resort Electron mirror after GitHub download fails (#47266).
-$script:DesktopElectronFallbackMirror = "https://npmmirror.com/mirrors/electron/"
-
-# Electron package dir -- workspace-local nest first, then root hoist.
-function Get-ElectronDir {
- param([string]$InstallDir)
- $desktopLocal = Join-Path $InstallDir 'apps\desktop\node_modules\electron'
- if (Test-Path -LiteralPath $desktopLocal) { return $desktopLocal }
- return (Join-Path $InstallDir 'node_modules\electron')
-}
-
-# True when dist/ holds a usable Electron binary (#38673 / run-electron-builder.mjs).
-function Test-ElectronDist {
- param([string]$InstallDir)
- $electronDir = Get-ElectronDir -InstallDir $InstallDir
- $distExe = Join-Path $electronDir 'dist\electron.exe'
- return (Test-Path -LiteralPath $distExe)
-}
-
-# Best-effort: run electron/install.js to populate dist/ (optional mirror).
-function Restore-ElectronDist {
- param([string]$InstallDir, [string]$Mirror)
- if (Test-ElectronDist -InstallDir $InstallDir) { return $true }
-
- $electronDir = Get-ElectronDir -InstallDir $InstallDir
- $distExe = Join-Path $electronDir 'dist\electron.exe'
- $installer = Join-Path $electronDir 'install.js'
- if (-not (Test-Path -LiteralPath $installer)) { return $false }
- $node = Get-Command node -ErrorAction SilentlyContinue
- if (-not $node) { return $false }
-
- $distDir = Join-Path $electronDir 'dist'
- if (Test-Path -LiteralPath $distDir) {
- Remove-Item -LiteralPath $distDir -Recurse -Force -ErrorAction SilentlyContinue
- }
- Remove-Item -LiteralPath (Join-Path $electronDir 'path.txt') -Force -ErrorAction SilentlyContinue
-
- $prevMirror = $env:ELECTRON_MIRROR
- if ($Mirror) { $env:ELECTRON_MIRROR = $Mirror }
- try {
- # Out-Host so the downloader's progress shows on the console WITHOUT
- # leaking into this function's return value (PowerShell returns every
- # object left on the output stream, so a bare pipe here would make the
- # boolean below ambiguous).
- & $node.Source $installer 2>&1 | ForEach-Object { "$_" } | Out-Host
- } catch {
- } finally {
- $env:ELECTRON_MIRROR = $prevMirror
- }
- return (Test-Path -LiteralPath $distExe)
-}
-
-function Test-ElectronPkgStagedMissingDist {
- param([string]$InstallDir)
- $electronDir = Get-ElectronDir -InstallDir $InstallDir
- return (
- (Test-Path -LiteralPath (Join-Path $electronDir 'package.json')) -and
- (Test-Path -LiteralPath (Join-Path $electronDir 'install.js')) -and
- (-not (Test-ElectronDist -InstallDir $InstallDir))
- )
-}
-
-function Try-RestoreElectronDist {
- param([string]$InstallDir)
- if (Restore-ElectronDist -InstallDir $InstallDir) { return $true }
- if ($env:ELECTRON_MIRROR) { return $false }
- return Restore-ElectronDist -InstallDir $InstallDir -Mirror $script:DesktopElectronFallbackMirror
-}
-
-function Install-DesktopVoiceDeps {
- # Desktop ships with working voice out of the box: eagerly install the
- # wake-word + local-STT stacks ([wake] + [voice] extras) instead of
- # leaving them to lazy first-use install. Policy change (Teknium, July
- # 2026, #70509 testing): the first ear-click used to trigger a
- # multi-minute onnxruntime pip install that froze the UI and blew RPC
- # timeouts. Best-effort -- lazy install remains the fallback for anything
- # this step fails to fetch.
- if (-not $script:UvCmd) { Resolve-UvCmd }
- if (-not $script:UvCmd) {
- Write-Warn "uv unavailable -- voice/wake deps will lazy-install at first use instead"
- return
- }
- $env:VIRTUAL_ENV = "$InstallDir\venv"
- Write-Info "Installing voice + wake-word dependencies (onnxruntime, faster-whisper -- 1-3min)..."
- Push-Location $InstallDir
- try {
- Invoke-NativeWithRelaxedErrorAction { & $UvCmd pip install -e ".[wake,voice]" }
- if ($LASTEXITCODE -eq 0) {
- Write-Success "Voice + wake-word dependencies installed"
- } else {
- Write-Warn "Voice/wake dependency install failed (exit $LASTEXITCODE) -- they will lazy-install at first use"
- }
- } finally {
- Pop-Location
- }
-}
-
-function Install-Desktop {
- # Build apps/desktop into a launchable Hermes.exe. Only called from
- # Stage-Desktop, which is itself only included in the manifest when
- # -IncludeDesktop was passed to install.ps1.
- #
- # The workspace npm install at repo root (done by Install-NodeDeps for
- # browser tools) does NOT pull apps/desktop's dependencies, because the
- # browser-tools workspace at $InstallDir\package.json is a separate
- # workspace from apps/*. We do a full root-level `npm install` here
- # so the workspace resolves apps/desktop's deps (including Electron
- # itself, ~150MB), then run `npm run pack` in apps/desktop which
- # produces the unpacked binary at apps/desktop/release/<os>-unpacked/.
- #
- # The Tauri bootstrap installer's launch_hermes_desktop command
- # resolves apps/desktop/release/win-unpacked/Hermes.exe directly,
- # so an "unpacked" build (electron-builder --dir) is enough -- we
- # don't need to produce an NSIS/MSI artifact here.
-
- # Always re-resolve Node here. Stages run in separate PowerShell processes,
- # so $script:HasNode from Stage-Node isn't visible; more importantly Test-Node
- # enforces the supported Node lines and prepends the Hermes-managed Node to
- # PATH, so the build never runs on an unsupported system Node -- the cause
- # of the opaque "Build desktop app ... exit code 1" failure (Vite crashes on
- # old Node).
- Test-Node | Out-Null
- if (-not (Get-Command npm -ErrorAction SilentlyContinue)) {
- Write-Warn "Skipping desktop build (Node.js / npm not on PATH)"
- $script:_StageSkippedReason = "Node.js not available"
- return
- }
-
- $desktopDir = "$InstallDir\apps\desktop"
- if (-not (Test-Path "$desktopDir\package.json")) {
- Write-Warn "Skipping desktop build (apps/desktop not present in checkout)"
- $script:_StageSkippedReason = "apps/desktop not present"
- return
- }
-
- $npmCmd = Get-Command npm -ErrorAction SilentlyContinue
- if (-not $npmCmd) {
- Write-Warn "Skipping desktop build (npm not on PATH)"
- $script:_StageSkippedReason = "npm not found"
- return
- }
- $npmExe = $npmCmd.Source
- if ($npmExe -like "*.ps1") {
- $sibling = Join-Path (Split-Path $npmExe -Parent) "npm.cmd"
- if (Test-Path $sibling) { $npmExe = $sibling }
- }
-
- # 1. Workspace-level install so apps/desktop's deps (Electron, Vite,
- # node-pty prebuilds, etc.) actually land in node_modules. This is
- # the SAME `npm install` Install-NodeDeps does for browser tools,
- # but at the root rather than the browser-tools workspace, so all
- # apps/* workspaces resolve.
- Write-Info "Installing desktop workspace dependencies (this includes Electron ~150MB, takes 1-3min)..."
- Push-Location $InstallDir
- $prevEAP = $ErrorActionPreference
- try {
- $ErrorActionPreference = "Continue"
- # Drop --silent so npm emits its full progress + error trail.
- # When this fails on a non-dev box (e.g. native-module build
- # without VS Build Tools, ETARGET on a transitive, etc.), the
- # actual reason needs to reach the Tauri installer's log; with
- # --silent it was completely suppressed and the user just saw
- # "exit 1" with no actionable detail.
- #
- # The streaming sink in bootstrap.rs's run_install_script
- # captures every stdout/stderr line as it's emitted, so we don't
- # need a side TEMP log file -- the installer's bootstrap log
- # IS the artifact a support engineer reads.
- #
- # Prefer `npm ci`: it wipes node_modules and reinstalls from the
- # lockfile, always producing a complete tree. Bare `npm install`
- # can report "up to date" against a stale
- # node_modules\.package-lock.json marker while node_modules is
- # actually empty (Windows workspace-hoisting flake), leaving
- # tsc/typescript unresolved so `npm run pack`'s `tsc -b` dies with
- # no obvious cause. Fall back to `npm install` only if `npm ci`
- # fails (lockfile out of sync / very old npm without ci).
- #
- # Tee the merged output into $npmOut while still emitting every line
- # live. We don't need a side log file (the bootstrap streaming sink
- # is the artifact), but on failure we scan $npmOut for the TLS-trust
- # signature so corporate-proxy users get the NODE_EXTRA_CA_CERTS hint
- # instead of an opaque "exit 1" (issue #38016).
- & $npmExe ci 2>&1 | ForEach-Object { "$_" } | Tee-Object -Variable npmOut
- $code = $LASTEXITCODE
- if ($code -ne 0) {
- Write-Info " npm ci failed (exit $code) -- retrying with npm install..."
- & $npmExe install 2>&1 | ForEach-Object { "$_" } | Tee-Object -Variable npmOut
- $code = $LASTEXITCODE
- }
- $ErrorActionPreference = $prevEAP
- if ($code -ne 0) {
- if (Test-ElectronPkgStagedMissingDist -InstallDir $InstallDir) {
- Write-Warn "Desktop dependency install failed with a missing Electron dist; attempting self-heal..."
- Try-RestoreElectronDist -InstallDir $InstallDir | Out-Null
- } else {
- Show-NpmCertHint ($npmOut -join "`n") | Out-Null
- # Replay npm's own debug log into our stream: the terse
- # summary above rarely contains the postinstall stderr
- # (e.g. Electron's install.js) that explains the failure.
- Write-NpmDebugLogTail -NpmOutput ($npmOut -join "`n")
- throw "desktop workspace npm install failed (exit $code) -- see lines above for cause"
- }
- } else {
- Write-Success "Desktop workspace dependencies installed"
- }
- } catch {
- if ($prevEAP) { $ErrorActionPreference = $prevEAP }
- Pop-Location
- throw
- }
- Pop-Location
-
- # 2. Build apps/desktop. `npm run pack` runs:
- # assert-root-install + write-build-stamp + stage-native-deps +
- # tsc -b + vite build + electron-builder --dir
- # The --dir mode produces an unpacked Hermes.exe in
- # apps/desktop/release/win-unpacked/ without bundling NSIS/MSI;
- # we don't need a distributable installer artifact, just a
- # launchable binary the Tauri installer can spawn.
- #
- # CSC_IDENTITY_AUTO_DISCOVERY=false tells electron-builder we are
- # NOT signing the output. Combined with signAndEditExecutable=false in
- # apps/desktop/package.json's build.win block, electron-builder never
- # invokes signtool and therefore never fetches/extracts winCodeSign
- # (whose macOS symlinks crash 7-Zip on non-admin Windows -- a dead end we
- # are NOT trying to work around). The Hermes icon + product name are
- # stamped onto Hermes.exe by our own rcedit step (Set-DesktopExeIdentity)
- # AFTER this build, completely decoupled from electron-builder signing.
- #
- # WIN_CSC_LINK and WIN_CSC_KEY_PASSWORD explicitly cleared as
- # belt-and-suspenders: if the user's environment has them set
- # for some other tool, electron-builder would still try to sign.
- Write-Info "Building desktop app (this takes 1-3 minutes)..."
- $buildLog = "$env:TEMP\hermes-desktop-build-$(Get-Random).log"
- # Seed GITHUB_SHA for write-build-stamp.mjs. The stamp prefers CI env vars
- # over `git rev-parse`, so this covers: (1) node can't find git.exe on PATH
- # even though this PowerShell session can, (2) ZIP/init trees that still
- # lack a HEAD after a failed post-extract fetch. Without it the desktop
- # pack dies with "could not determine git commit" (#50823).
- if (-not $env:GITHUB_SHA) {
- if ($Commit) {
- $env:GITHUB_SHA = $Commit
- } else {
- Push-Location $InstallDir
- try {
- $global:LASTEXITCODE = 0
- $resolvedSha = & git -c windows.appendAtomically=false rev-parse HEAD 2>$null
- if ($LASTEXITCODE -ne 0 -or -not $resolvedSha) {
- # ZIP path may have FETCH_HEAD after a fetch even when HEAD is unset.
- $global:LASTEXITCODE = 0
- $resolvedSha = & git -c windows.appendAtomically=false rev-parse FETCH_HEAD 2>$null
- }
- if ($LASTEXITCODE -eq 0 -and $resolvedSha) {
- $env:GITHUB_SHA = ("$resolvedSha").Trim()
- }
- } catch { } finally {
- Pop-Location
- }
- }
- }
- if (-not $env:GITHUB_REF_NAME) {
- $env:GITHUB_REF_NAME = if ($Branch) { $Branch } else { "main" }
- }
- if ($env:GITHUB_SHA) {
- $shaPreview = if ($env:GITHUB_SHA.Length -ge 12) { $env:GITHUB_SHA.Substring(0, 12) } else { $env:GITHUB_SHA }
- Write-Info "Desktop build stamp: $shaPreview ($($env:GITHUB_REF_NAME))"
- } else {
- Write-Warn "Could not resolve a git commit for the desktop stamp -- write-build-stamp will use its non-git fallback"
- }
- Push-Location $desktopDir
- $prevEAP = $ErrorActionPreference
- $prevCSCAuto = $env:CSC_IDENTITY_AUTO_DISCOVERY
- $prevWinCscLink = $env:WIN_CSC_LINK
- $prevWinCscKeyPassword = $env:WIN_CSC_KEY_PASSWORD
- try {
- $ErrorActionPreference = "Continue"
- $env:CSC_IDENTITY_AUTO_DISCOVERY = "false"
- $env:WIN_CSC_LINK = ""
- $env:WIN_CSC_KEY_PASSWORD = ""
- & $npmExe run pack 2>&1 | ForEach-Object { "$_" } | Tee-Object -FilePath $buildLog
- $code = $LASTEXITCODE
- if ($code -ne 0) {
- $purged = @()
- $restored = $false
- if (-not (Test-ElectronDist -InstallDir $InstallDir)) {
- $purged = @(Clear-ElectronBuildCache -DesktopDir $desktopDir)
- $restored = Restore-ElectronDist -InstallDir $InstallDir
- }
- if ($restored) {
- Write-Warn "Desktop build failed - refreshed the Electron download, retrying once:"
- foreach ($p in $purged) { Write-Info " - $p" }
- & $npmExe run pack 2>&1 | ForEach-Object { "$_" } | Tee-Object -FilePath $buildLog
- $code = $LASTEXITCODE
- }
- }
- if ($code -ne 0 -and -not $env:ELECTRON_MIRROR) {
- $mirror = $script:DesktopElectronFallbackMirror
- Write-Warn "Desktop build still failing - the Electron download from GitHub looks blocked."
- Write-Warn "Re-downloading Electron via a public mirror ($mirror), then rebuilding:"
- Write-Info " (set ELECTRON_MIRROR yourself to use a different/trusted mirror)"
- if (-not (Test-ElectronDist -InstallDir $InstallDir)) {
- Restore-ElectronDist -InstallDir $InstallDir -Mirror $mirror | Out-Null
- }
- $prevMirror = $env:ELECTRON_MIRROR
- $env:ELECTRON_MIRROR = $mirror
- try {
- & $npmExe run pack 2>&1 | ForEach-Object { "$_" } | Tee-Object -FilePath $buildLog
- $code = $LASTEXITCODE
- } finally {
- $env:ELECTRON_MIRROR = $prevMirror
- }
- }
- $ErrorActionPreference = $prevEAP
- if ($code -ne 0) {
- $errText = Get-Content $buildLog -Raw -ErrorAction SilentlyContinue
- if ($errText) {
- $snippet = if ($errText.Length -gt 1800) { $errText.Substring(0, 1800) + "..." } else { $errText }
- Write-Info " desktop build output:"
- foreach ($line in $snippet -split "`n") { Write-Host " $line" -ForegroundColor DarkGray }
- Write-Info " Full log: $buildLog"
- }
- # `npm run pack` failures (lifecycle script exits) also land in
- # npm's debug log; replay it so the bootstrap log carries the
- # full evidence even when $buildLog's tail cuts off the cause.
- Write-NpmDebugLogTail -NpmOutput $errText
- throw "apps/desktop build failed (exit $code)"
- }
- Write-Success "Desktop app built"
- Remove-Item -LiteralPath $buildLog -Force -ErrorAction SilentlyContinue
- } catch {
- if ($prevEAP) { $ErrorActionPreference = $prevEAP }
- Pop-Location
- throw
- } finally {
- # Restore env to whatever the caller had -- don't leak our
- # signing-off override into anything install.ps1 invokes later
- # (Stage-PlatformSdks, etc.).
- $env:CSC_IDENTITY_AUTO_DISCOVERY = $prevCSCAuto
- $env:WIN_CSC_LINK = $prevWinCscLink
- $env:WIN_CSC_KEY_PASSWORD = $prevWinCscKeyPassword
- }
- Pop-Location
-
- # 3. Sanity-check the produced binary. Probe both arches so this works
- # on x64 and arm64 build machines.
- $exeCandidates = @(
- "$desktopDir\release\win-unpacked\Hermes.exe",
- "$desktopDir\release\win-arm64-unpacked\Hermes.exe"
- )
- $found = $false
- $desktopExe = $null
- foreach ($cand in $exeCandidates) {
- if (Test-Path $cand) {
- Write-Success "Desktop ready: $cand"
- $desktopExe = $cand
- $found = $true
- break
- }
- }
- if (-not $found) {
- throw "Desktop build completed but no Hermes.exe was found under $desktopDir\release\*-unpacked\"
- }
-
- # 3b. The Hermes icon + identity are stamped onto Hermes.exe by the
- # electron-builder `afterPack` hook (apps/desktop/scripts/after-pack.mjs)
- # during `npm run pack` above -- for every build, so the installer's
- # --update rebuild stays branded too. No separate stamp step needed here.
- # electron-builder's own rcedit step stays disabled (signAndEditExecutable
- # =false) because enabling it drags in signtool -> winCodeSign -> the
- # unfixable symlink crash; the afterPack hook runs rcedit directly.
-
- # 3c. Grant ALL APPLICATION PACKAGES (S-1-15-2-2) RX on the unpacked app
- # directory. Chromium's GPU/renderer sandboxes CHECK-fail with
- # 0x80000003 when this ACE is missing alongside orphan AppContainer
- # SIDs under %LOCALAPPDATA% (electron/electron#51761, hermes-agent#38216).
- # Best-effort -- never fail an otherwise-good install over ACL repair.
- try {
- $appDir = Split-Path -Parent $desktopExe
- & icacls $appDir /grant "*S-1-15-2-2:(OI)(CI)(RX)" /T /C /Q | Out-Null
- if ($LASTEXITCODE -eq 0) {
- Write-Success "Granted AppContainer read access on $appDir"
- } else {
- Write-Warn "icacls AppContainer grant returned exit $LASTEXITCODE for $appDir"
- }
- } catch {
- Write-Warn "Could not grant AppContainer ACL: $($_.Exception.Message)"
- }
-
- # 4. Create Start Menu + Desktop shortcuts pointing DIRECTLY at the packed
- # Hermes.exe. We deliberately do NOT point them at `hermes desktop`: that
- # command rebuilds (npm install + electron-builder) on every launch,
- # which would cost minutes each time. The packed exe is the consumer --
- # launching it directly is instant, and updates flow through the
- # installer's --update path (which rebuilds once, then relaunches).
- New-DesktopShortcuts -TargetExe $desktopExe
-}
-
-function New-DesktopShortcuts {
- param([Parameter(Mandatory = $true)][string]$TargetExe)
-
- # Best-effort: a shortcut failure must never fail an otherwise-good install.
- try {
- $shell = New-Object -ComObject WScript.Shell
- $workDir = Split-Path -Parent $TargetExe
-
- # Prefer the standalone icon.ico (shipped beside the exe via
- # electron-builder extraResources -> resources/icon.ico) over the exe's
- # embedded resource. An explicit .ico path is more stable across update
- # cycles: pointing at "$TargetExe,0" makes Windows cache the icon it
- # extracted from the exe at shortcut-creation time, and that cached
- # bitmap can persist (showing the OLD/Electron icon) even after the exe
- # is re-stamped on update. A dedicated .ico sidesteps that extraction.
- $iconIco = Join-Path $workDir 'resources\icon.ico'
- if (Test-Path $iconIco) {
- $iconLocation = "$iconIco,0"
- } else {
- $iconLocation = "$TargetExe,0"
- }
-
- $targets = @(
- (Join-Path ([Environment]::GetFolderPath('Programs')) 'Hermes.lnk'),
- (Join-Path ([Environment]::GetFolderPath('Desktop')) 'Hermes.lnk')
- )
-
- foreach ($lnkPath in $targets) {
- try {
- $parent = Split-Path -Parent $lnkPath
- if (-not (Test-Path $parent)) {
- New-Item -ItemType Directory -Force -Path $parent | Out-Null
- }
- $sc = $shell.CreateShortcut($lnkPath)
- $sc.TargetPath = $TargetExe
- $sc.WorkingDirectory = $workDir
- $sc.IconLocation = $iconLocation
- $sc.Description = 'Hermes Agent'
- $sc.Save()
- Write-Success "Shortcut created: $lnkPath"
- } catch {
- Write-Warn "Could not create shortcut $lnkPath : $($_.Exception.Message)"
- }
- }
-
- # Bust the Windows shell icon cache so the desktop/Start-Menu shortcut
- # repaints with the (possibly newly-stamped) icon instead of a stale
- # cached bitmap. Critical on the --update path: the exe was re-stamped
- # with the Hermes icon, but without this the shortcut can keep drawing
- # the old Electron icon until the user manually refreshes / reboots.
- # Best-effort and silent -- never fail the install over a cosmetic cache.
- try {
- & ie4uinit.exe -show 2>$null
- } catch {
- # ie4uinit may be absent/renamed on some SKUs -- ignore.
- }
- } catch {
- Write-Warn "Skipping shortcut creation: $($_.Exception.Message)"
- }
-}
-
-function Install-PlatformSdks {
- # Ensure messaging-platform SDKs matching tokens the user added to
- # ~/.hermes/.env are importable. Two problems this solves:
- #
- # 1. The tiered `uv pip install` cascade above can fall through to a
- # lower tier when the first fails (common when RL git deps choke),
- # which silently skips some messaging SDKs from [messaging].
- # 2. `uv` creates the venv without pip. If a messaging SDK ends up
- # missing, the user can't `pip install python-telegram-bot` to
- # recover -- pip simply isn't in their venv.
- #
- # Strategy: bootstrap pip via `python -m ensurepip` (idempotent), then
- # for each token set in .env, verify the matching SDK imports. If not,
- # run one targeted `pip install` as last-chance recovery. Keeps fresh
- # Windows installs from hitting silent "python-telegram-bot not installed"
- # at runtime.
- if ($NoVenv) {
- Write-Info "Skipping platform-SDK verification (-NoVenv: no venv to bootstrap)"
- return
- }
-
- $pythonExe = "$InstallDir\venv\Scripts\python.exe"
- if (-not (Test-Path $pythonExe)) {
- Write-Warn "Skipping platform-SDK verification: $pythonExe not found"
- return
- }
-
- $envPath = "$HermesHome\.env"
- if (-not (Test-Path $envPath)) { return }
- $envLines = Get-Content $envPath -ErrorAction SilentlyContinue
-
- # Map: env var set in .env -> (import name, pip spec matching [messaging] extra).
- # Specs mirror pyproject.toml to avoid version drift.
- $sdkMap = @(
- @{ Var = "TELEGRAM_BOT_TOKEN"; Import = "telegram"; Spec = "python-telegram-bot[webhooks]>=22.6,<23" },
- @{ Var = "DISCORD_BOT_TOKEN"; Import = "discord"; Spec = "discord.py[voice]>=2.7.1,<3" },
- @{ Var = "SLACK_BOT_TOKEN"; Import = "slack_sdk"; Spec = "slack-sdk>=3.27.0,<4" },
- @{ Var = "SLACK_APP_TOKEN"; Import = "slack_bolt";Spec = "slack-bolt>=1.18.0,<2" },
- @{ Var = "WHATSAPP_ENABLED"; Import = "qrcode"; Spec = "qrcode>=7.0,<8" }
- )
-
- # Which tokens are actually set (not placeholder)?
- $needed = @()
- foreach ($sdk in $sdkMap) {
- $match = $envLines | Where-Object {
- $_ -match ("^" + [regex]::Escape($sdk.Var) + "=.+") `
- -and $_ -notmatch "your-token-here" `
- -and $_ -notmatch "^\s*#"
- }
- if ($match) { $needed += $sdk }
- }
- if ($needed.Count -eq 0) { return }
-
- Write-Host ""
- Write-Info "Verifying platform SDKs for tokens found in $envPath ..."
-
- # Verify each SDK's import without triggering side-effect imports.
- # Quirk: PowerShell wraps non-zero-exit native stderr as a
- # NativeCommandError that prints even with `2>$null` / `*> $null`
- # unless we set $ErrorActionPreference to SilentlyContinue for the
- # span. Save + restore rather than nuking globally.
- $prevEAP = $ErrorActionPreference
- $ErrorActionPreference = "SilentlyContinue"
- try {
- $missing = @()
- foreach ($sdk in $needed) {
- & $pythonExe -c "import $($sdk.Import)" 2>&1 | Out-Null
- if ($LASTEXITCODE -ne 0) {
- $missing += $sdk
- Write-Warn " $($sdk.Import) NOT importable (needed for $($sdk.Var))"
- } else {
- Write-Success " $($sdk.Import) OK"
- }
- }
- } finally {
- $ErrorActionPreference = $prevEAP
- }
- if ($missing.Count -eq 0) { return }
-
- # Bootstrap pip into the venv if it isn't there. `uv` creates venvs
- # without pip; ensurepip is the stdlib-blessed way to add it.
- $prevEAP = $ErrorActionPreference
- $ErrorActionPreference = "SilentlyContinue"
- try {
- & $pythonExe -m pip --version 2>&1 | Out-Null
- if ($LASTEXITCODE -ne 0) {
- Write-Info "Bootstrapping pip into venv (uv doesn't ship pip)..."
- & $pythonExe -m ensurepip --upgrade 2>&1 | Out-Null
- if ($LASTEXITCODE -ne 0) {
- Write-Warn "ensurepip failed -- can't auto-install missing SDKs."
- Write-Info "Manual recovery: $UvCmd pip install `"$($missing[0].Spec)`""
- return
- }
- }
-
- foreach ($sdk in $missing) {
- Write-Info " Installing $($sdk.Spec) ..."
- & $pythonExe -m pip install $sdk.Spec 2>&1 | ForEach-Object { Write-Host " $_" }
- if ($LASTEXITCODE -eq 0) {
- Write-Success " Installed $($sdk.Import)"
- } else {
- Write-Warn " Failed to install $($sdk.Spec). Recover manually: $pythonExe -m pip install `"$($sdk.Spec)`""
- }
- }
- } finally {
- $ErrorActionPreference = $prevEAP
- }
-}
-
-function Invoke-SetupWizard {
- if ($SkipSetup) {
- Write-Info "Skipping setup wizard (-SkipSetup)"
- return
- }
-
- if ($NonInteractive) {
- # The setup wizard prompts for API keys, model choice, persona, etc.
- # Non-interactive callers (GUI installer) own that UX themselves; let
- # them drive it after install.ps1 returns.
- Write-Info "Skipping setup wizard (non-interactive). Configure via the GUI or 'hermes setup'."
- return
- }
-
- Write-Host ""
- Write-Info "Starting setup wizard..."
- Write-Host ""
-
- Push-Location $InstallDir
-
- # Run hermes setup using the venv Python directly (no activation needed)
- if (-not $NoVenv) {
- & ".\venv\Scripts\python.exe" -m hermes_cli.main setup
- } else {
- python -m hermes_cli.main setup
- }
-
- Pop-Location
-}
-
-function Start-GatewayIfConfigured {
- $envPath = "$HermesHome\.env"
- if (-not (Test-Path $envPath)) { return }
-
- $hasMessaging = $false
- $content = Get-Content $envPath -ErrorAction SilentlyContinue
- foreach ($var in @("TELEGRAM_BOT_TOKEN", "DISCORD_BOT_TOKEN", "SLACK_BOT_TOKEN", "SLACK_APP_TOKEN", "WHATSAPP_ENABLED")) {
- $match = $content | Where-Object { $_ -match "^${var}=.+" -and $_ -notmatch "your-token-here" }
- if ($match) { $hasMessaging = $true; break }
- }
-
- if (-not $hasMessaging) { return }
-
- $hermesCmd = "$InstallDir\venv\Scripts\hermes.exe"
- if (-not (Test-Path $hermesCmd)) {
- $hermesCmd = "hermes"
- }
-
- # If WhatsApp is enabled but not yet paired, run foreground for QR scan
- $whatsappEnabled = $content | Where-Object { $_ -match "^WHATSAPP_ENABLED=true" }
- $whatsappSession = "$HermesHome\whatsapp\session\creds.json"
- if ($whatsappEnabled -and -not (Test-Path $whatsappSession)) {
- Write-Host ""
- Write-Info "WhatsApp is enabled but not yet paired."
- Write-Info "Running 'hermes whatsapp' to pair via QR code..."
- Write-Host ""
- # Non-interactive callers (GUI installer, CI) skip the QR-pair prompt;
- # WhatsApp pairing requires a human looking at a phone camera, so the
- # downstream UI is responsible for surfacing this when it makes sense.
- if (-not $NonInteractive) {
- $response = Read-Host "Pair WhatsApp now? [Y/n]"
- if ($response -eq "" -or $response -match "^[Yy]") {
- try {
- & $hermesCmd whatsapp
- } catch {
- # Expected after pairing completes
- }
- }
- } else {
- Write-Info "Skipping WhatsApp pairing prompt (non-interactive)."
- }
- }
-
- Write-Host ""
- Write-Info "Messaging platform token detected!"
- Write-Info "The gateway handles messaging platforms and cron job execution."
- Write-Host ""
-
- # In non-interactive mode the gateway lifecycle is the caller's problem
- # (the GUI manages its own gateway process, CI doesn't want background
- # services on the build agent, etc.). Treat it like the user declined.
- if ($NonInteractive) {
- Write-Info "Skipping gateway autostart prompt (non-interactive)."
- Write-Info "Start the gateway later with: hermes gateway"
- return
- }
-
- $response = Read-Host "Would you like to start the gateway now? [Y/n]"
-
- if ($response -eq "" -or $response -match "^[Yy]") {
- Write-Info "Starting gateway in background..."
- try {
- $logFile = "$HermesHome\logs\gateway.log"
- Start-Process -FilePath $hermesCmd -ArgumentList "gateway" `
- -RedirectStandardOutput $logFile `
- -RedirectStandardError "$HermesHome\logs\gateway-error.log" `
- -WindowStyle Hidden
- Write-Success "Gateway started! Your bot is now online."
- Write-Info "Logs: $logFile"
- Write-Info "To stop: close the gateway process from Task Manager"
- } catch {
- Write-Warn "Failed to start gateway. Run manually: hermes gateway"
- }
- } else {
- Write-Info "Skipped. Start the gateway later with: hermes gateway"
- }
-}
-
-function Write-Completion {
- Write-Host ""
- Write-Host "+---------------------------------------------------------+" -ForegroundColor Green
- Write-Host "| [OK] Installation Complete! |" -ForegroundColor Green
- Write-Host "+---------------------------------------------------------+" -ForegroundColor Green
- Write-Host ""
-
- # Show file locations
- Write-Host "* Your files:" -ForegroundColor Cyan
- Write-Host ""
- Write-Host " Config: " -NoNewline -ForegroundColor Yellow
- Write-Host "$HermesHome\config.yaml"
- Write-Host " API Keys: " -NoNewline -ForegroundColor Yellow
- Write-Host "$HermesHome\.env"
- Write-Host " Data: " -NoNewline -ForegroundColor Yellow
- Write-Host "$HermesHome\cron\, sessions\, logs\"
- Write-Host " Code: " -NoNewline -ForegroundColor Yellow
- Write-Host "$HermesHome\hermes-agent\"
- Write-Host ""
-
- Write-Host "---------------------------------------------------------" -ForegroundColor Cyan
- Write-Host ""
- Write-Host "* Commands:" -ForegroundColor Cyan
- Write-Host ""
- Write-Host " hermes " -NoNewline -ForegroundColor Green
- Write-Host "Start chatting"
- Write-Host " hermes setup " -NoNewline -ForegroundColor Green
- Write-Host "Configure API keys & settings"
- Write-Host " hermes config " -NoNewline -ForegroundColor Green
- Write-Host "View/edit configuration"
- Write-Host " hermes config edit " -NoNewline -ForegroundColor Green
- Write-Host "Open config in editor"
- Write-Host " hermes gateway " -NoNewline -ForegroundColor Green
- Write-Host "Start messaging gateway (Telegram, Discord, etc.)"
- Write-Host " hermes update " -NoNewline -ForegroundColor Green
- Write-Host "Update to latest version"
- Write-Host ""
-
- Write-Host "---------------------------------------------------------" -ForegroundColor Cyan
- Write-Host ""
- Write-Host "[*] Restart your terminal for PATH changes to take effect" -ForegroundColor Yellow
- Write-Host ""
-
- if (-not $HasNode) {
- Write-Host "Note: Node.js could not be installed automatically." -ForegroundColor Yellow
- Write-Host "Browser tools need Node.js. Install manually:" -ForegroundColor Yellow
- Write-Host " https://nodejs.org/en/download/" -ForegroundColor Yellow
- Write-Host ""
- }
-
- if (-not $HasRipgrep) {
- Write-Host "Note: ripgrep (rg) was not installed. For faster file search:" -ForegroundColor Yellow
- Write-Host " winget install BurntSushi.ripgrep.MSVC" -ForegroundColor Yellow
- Write-Host ""
- }
-}
-
-# ============================================================================
-# Stage protocol
-# ============================================================================
-#
-# install.ps1 supports a small, stable "stage protocol" that lets programmatic
-# callers (the desktop GUI's onboarding wizard, CI, future install.sh, etc.)
-# drive the install one step at a time and surface progress/errors with their
-# own UI. CLI users running the canonical `irm | iex` one-liner never
-# encounter this -- default invocation behaves exactly as before.
-#
-# Entry points:
-#
-# install.ps1 Interactive install (today's behavior).
-# install.ps1 -ProtocolVersion Emit the protocol version integer.
-# install.ps1 -Manifest Emit the stage manifest as JSON.
-# install.ps1 -Stage <name> Run one stage and emit its result.
-# install.ps1 -NonInteractive Disable all Read-Host prompts (also
-# skips the setup wizard and the gateway
-# autostart prompt). Can be combined
-# with default invocation to do a full
-# non-interactive install.
-# install.ps1 -Json Emit machine-readable JSON instead of
-# the human-readable success banner at
-# the end of a full install.
-#
-# Manifest schema (the JSON returned by -Manifest):
-#
-# {
-# "protocol_version": 1,
-# "stages": [
-# {
-# "name": "uv",
-# "title": "Installing uv package manager",
-# "category": "prereqs",
-# "needs_user_input": false
-# },
-# ...
-# ]
-# }
-#
-# Stage result (the JSON written by -Stage <name>):
-#
-# {
-# "stage": "uv",
-# "ok": true,
-# "skipped": false,
-# "reason": null,
-# "duration_ms": 1234
-# }
-#
-# Exit codes:
-#
-# 0 -- success (stage ran, or stage was deliberately skipped).
-# 1 -- generic failure; the stage threw.
-# 2 -- unknown stage name passed to -Stage.
-#
-# Adding a stage:
-#
-# 1. Append an entry to $InstallStages below.
-# 2. Make sure the worker function it points at is idempotent and respects
-# $NonInteractive when it has prompts. Add it before "configure"
-# (the wizard) or "gateway" (autostart) if it should run unconditionally;
-# after those if it's optional post-install glue.
-# 3. Do NOT bump $InstallStageProtocolVersion -- adding stages is additive.
-# Drivers iterate the manifest dynamically.
-#
-# ============================================================================
-
-# Stage definitions -- the single source of truth. Each entry maps a stable
-# stage name (the API contract drivers depend on) to the worker function that
-# implements it. ``Title`` is what UIs show; ``Category`` lets UIs group
-# stages; ``NeedsUserInput`` tells UIs "this stage prompts -- either skip it
-# or arrange to provide answers another way."
-$InstallStages = @(
- @{ Name = "uv"; Title = "Installing uv package manager"; Category = "prereqs"; NeedsUserInput = $false; Worker = "Stage-Uv" }
- @{ Name = "python"; Title = "Verifying Python $PythonVersion"; Category = "prereqs"; NeedsUserInput = $false; Worker = "Stage-Python" }
- @{ Name = "git"; Title = "Installing Git"; Category = "prereqs"; NeedsUserInput = $false; Worker = "Stage-Git" }
- @{ Name = "node"; Title = "Detecting Node.js"; Category = "prereqs"; NeedsUserInput = $false; Worker = "Stage-Node" }
- @{ Name = "system-packages"; Title = "Installing ripgrep and ffmpeg"; Category = "prereqs"; NeedsUserInput = $false; Worker = "Stage-SystemPackages" }
- @{ Name = "repository"; Title = "Cloning Hermes repository"; Category = "install"; NeedsUserInput = $false; Worker = "Stage-Repository" }
- @{ Name = "venv"; Title = "Creating Python virtual environment"; Category = "install"; NeedsUserInput = $false; Worker = "Stage-Venv" }
- @{ Name = "dependencies"; Title = "Installing Python dependencies"; Category = "install"; NeedsUserInput = $false; Worker = "Stage-Dependencies" }
- @{ Name = "node-deps"; Title = "Installing Node.js dependencies"; Category = "install"; NeedsUserInput = $false; Worker = "Stage-NodeDeps" }
-)
-if ($IncludeDesktop) {
- # Insert AFTER node-deps so workspace npm is already installed when
- # the desktop build runs. Inserted only when explicitly requested
- # (Hermes-Setup.exe), never via the irm|iex CLI one-liner.
- $InstallStages += @{ Name = "desktop"; Title = "Building desktop app"; Category = "install"; NeedsUserInput = $false; Worker = "Stage-Desktop" }
-}
-$InstallStages += @(
- @{ Name = "path"; Title = "Adding Hermes to PATH"; Category = "finalize"; NeedsUserInput = $false; Worker = "Stage-Path" }
- @{ Name = "config-templates"; Title = "Writing configuration templates"; Category = "finalize"; NeedsUserInput = $false; Worker = "Stage-ConfigTemplates" }
- @{ Name = "platform-sdks"; Title = "Installing messaging platform SDKs"; Category = "finalize"; NeedsUserInput = $false; Worker = "Stage-PlatformSdks" }
- @{ Name = "bootstrap-marker"; Title = "Marking install complete"; Category = "finalize"; NeedsUserInput = $false; Worker = "Stage-BootstrapMarker" }
- # Interactive stages. In non-interactive mode these become no-ops; the
- # caller (GUI / CI) handles the equivalent UX themselves.
- @{ Name = "configure"; Title = "Configuring API keys and models"; Category = "post-install"; NeedsUserInput = $true; Worker = "Stage-Configure" }
- @{ Name = "gateway"; Title = "Starting messaging gateway"; Category = "post-install"; NeedsUserInput = $true; Worker = "Stage-Gateway" }
-)
-
-# Stage workers -- thin wrappers that delegate to the existing Install-* /
-# Test-* / Invoke-* functions while preserving their error semantics. Kept
-# as a separate layer so the existing functions remain callable directly
-# (helpful for one-off recovery: ``. install.ps1; Install-Venv``).
-#
-# Stages that depend on uv (anything after Stage-Uv) call Resolve-UvCmd
-# first so they work in cross-process driver mode where $script:UvCmd
-# set by Stage-Uv in a sibling powershell process is not visible here.
-# Resolve-UvCmd is a fast no-op when $script:UvCmd is already populated
-# (the default-invocation case where Main runs everything in one
-# process), and throws cleanly if uv truly isn't installed yet.
-function Stage-Uv { if (-not (Install-Uv)) { throw "uv installation failed" } }
-function Stage-Python { Resolve-UvCmd; if (-not (Test-Python)) { throw "Python $PythonVersion not available" } }
-function Stage-Git {
- if (-not (Install-Git)) {
- if ($script:GitInstallFailureReason) { throw $script:GitInstallFailureReason }
- throw "Git not available and auto-install failed -- install from https://git-scm.com/download/win then re-run"
- }
-}
-# Node is optional (browser tools degrade gracefully without it). Surface
-# failure to the JSON contract as skipped=true / reason rather than ok=true,
-# so a GUI driver consuming the manifest can distinguish "node ready" from
-# "node missing". Install flow continues either way -- matches the
-# existing Write-Completion behavior that prints a "Note: Node.js could
-# not be installed" hint instead of aborting.
-function Stage-Node {
- if (-not (Test-Node)) {
- $script:_StageSkippedReason = "Node.js not available; browser tools will be unavailable until node is installed manually from https://nodejs.org/en/download/"
- }
-}
-function Stage-SystemPackages { Install-SystemPackages }
-function Stage-Repository { Install-Repository }
-function Stage-Venv { Resolve-UvCmd; Install-Venv }
-function Stage-Dependencies { Resolve-UvCmd; Install-Dependencies }
-function Stage-NodeDeps { Install-NodeDeps }
-function Stage-Desktop { Install-DesktopVoiceDeps; Install-Desktop }
-function Stage-Path { Set-PathVariable }
-function Stage-ConfigTemplates { Copy-ConfigTemplates }
-function Stage-PlatformSdks { Resolve-UvCmd; Install-PlatformSdks }
-function Stage-BootstrapMarker { Write-BootstrapMarker }
-function Stage-Configure { Invoke-SetupWizard }
-function Stage-Gateway { Start-GatewayIfConfigured }
-
-function Get-InstallStage {
- param([string]$Name)
- foreach ($s in $InstallStages) {
- if ($s.Name -eq $Name) { return $s }
- }
- return $null
-}
-
-function Step-OutOfInstallDir {
- # Windows refuses to delete a directory any shell is currently cd'd
- # inside -- and silently leaves orphan files behind, which then wedge
- # "is this a valid git repo" probes on re-install. Harmless when the
- # caller ran the installer from somewhere else.
- try {
- $currentResolved = (Get-Location).ProviderPath
- $installResolved = $null
- if (Test-Path $InstallDir) {
- $installResolved = (Resolve-Path $InstallDir -ErrorAction SilentlyContinue).ProviderPath
- }
- if ($installResolved -and $currentResolved.ToLower().StartsWith($installResolved.ToLower())) {
- Write-Info "Stepping out of $InstallDir so Windows can replace files there if needed..."
- Set-Location $env:USERPROFILE
- }
- } catch {}
-}
-
-function Invoke-Stage {
- param(
- [Parameter(Mandatory=$true)] [hashtable]$StageDef
- )
-
- # Refresh PATH from registry so this stage sees binaries installed by
- # prior stages, even when each stage runs in its own powershell process.
- # No-op in cost-relevant cases (default invocation path syncs once per
- # foreach pass; cross-process drivers get the necessary freshening).
- Sync-EnvPath
-
- # Per-stage soft-skip channel. A worker can populate
- # $script:_StageSkippedReason to surface "ran, but the thing it was
- # supposed to set up is not available" as skipped=true in the JSON
- # frame, without throwing. Used by Stage-Node so the install flow
- # doesn't abort when an optional capability is missing while still
- # being honest in the protocol contract. Reset before each stage so
- # a prior stage's reason can never leak into a later stage's frame.
- $script:_StageSkippedReason = $null
-
- $start = [DateTime]::UtcNow
- $result = @{
- stage = $StageDef.Name
- ok = $false
- skipped = $false
- reason = $null
- duration_ms = 0
- }
-
- try {
- & $StageDef.Worker
- $result.ok = $true
- if ($script:_StageSkippedReason) {
- $result.skipped = $true
- $result.reason = $script:_StageSkippedReason
- }
- } catch {
- $result.ok = $false
- $result.reason = "$_"
- throw
- } finally {
- $result.duration_ms = [int]([DateTime]::UtcNow - $start).TotalMilliseconds
- if ($Json -or $Stage) {
- # In stage-driver mode every stage emits a JSON line so the
- # caller can stream progress. In default interactive mode we
- # stay silent here (the worker already wrote human output).
- $result | ConvertTo-Json -Compress | Write-Output
- # Tell the entry-point catch that we've already emitted a
- # frame for this failure (when $result.ok = $false), so it
- # doesn't double-emit a second JSON object and break the
- # one-line-per-stage contract the driver protocol promises.
- if (-not $result.ok) {
- $script:_StageEmittedErrorFrame = $true
- }
- }
- }
-}
-
-# ============================================================================
-# Main
-# ============================================================================
-
-function Invoke-AllStages {
- Step-OutOfInstallDir
- foreach ($s in $InstallStages) {
- Invoke-Stage -StageDef $s
- }
-}
-
-function Invoke-EnsureMode {
- param([string]$Deps)
- $depList = $Deps -split ","
- foreach ($dep in $depList) {
- $dep = $dep.Trim()
- switch ($dep) {
- "node" {
- [void](Test-Node)
- if (-not $script:HasNode) {
- Write-Err "Node.js could not be installed"
- exit 1
- }
- }
- "browser" {
- [void](Test-Node)
- if ($script:HasNode) {
- Install-AgentBrowser
- } else {
- Write-Err "Node.js is required for browser tools but could not be installed"
- exit 1
- }
- }
- "ripgrep" {
- Write-Info "ripgrep: install manually on Windows (scoop install ripgrep)"
- }
- "ffmpeg" {
- Write-Info "ffmpeg: install manually on Windows (scoop install ffmpeg)"
- }
- default {
- Write-Err "Unknown dependency: $dep"
- exit 1
- }
- }
- }
-}
-
-function Invoke-PostInstallMode {
- Write-Info "Running post-install setup..."
- Invoke-EnsureMode -Deps "node,browser"
- Write-Info "Post-install complete"
-}
-
-function Main {
- Write-Banner
- Invoke-AllStages
- if (-not $Json) {
- Write-Completion
- } else {
- @{ ok = $true; protocol_version = $InstallStageProtocolVersion } | ConvertTo-Json -Compress | Write-Output
- }
-}
-
-# ----------------------------------------------------------------------------
-# Entry-point dispatch
-# ----------------------------------------------------------------------------
-#
-# All branches funnel through one try/catch so errors don't kill an `irm |
-# iex` PowerShell session, and so failures in stage-driver mode produce a
-# structured JSON error frame instead of a bare exception.
-
-# Dot-sourcing loads the installer's real functions for isolated behavioral
-# tests without running an install. Normal script and `irm | iex` entry points
-# are unchanged.
-if ($MyInvocation.InvocationName -eq ".") {
- return
-}
-
-try {
- if ($Ensure -ne "") {
- if ($PSBoundParameters.ContainsKey("Stage")) {
- Write-Err "Cannot use -Ensure and -Stage simultaneously"
- exit 1
- }
- Invoke-EnsureMode -Deps $Ensure
- exit 0
- }
- if ($PostInstall) {
- Invoke-PostInstallMode
- exit 0
- }
-
- if ($ProtocolVersion) {
- Write-Output $InstallStageProtocolVersion
- exit 0
- }
-
- if ($ShowResolvedPaths) {
- $script:ResolvedPathReport | ConvertTo-Json -Depth 5 -Compress | Write-Output
- exit 0
- }
-
- if ($Manifest) {
- $payload = @{
- protocol_version = $InstallStageProtocolVersion
- stages = @($InstallStages | ForEach-Object {
- @{
- name = $_.Name
- title = $_.Title
- category = $_.Category
- needs_user_input = $_.NeedsUserInput
- }
- })
- }
- $payload | ConvertTo-Json -Depth 5 -Compress | Write-Output
- exit 0
- }
-
- # Use PSBoundParameters rather than $Stage truthiness so that an
- # explicit `-Stage ""` from a misbehaving driver doesn't fall through
- # to the full-install Main path and silently kick off a destructive
- # operation. Empty string is a contract violation; surface it as
- # unknown-stage exit 2 with a structured JSON frame.
- if ($PSBoundParameters.ContainsKey("Stage")) {
- $def = Get-InstallStage -Name $Stage
- if (-not $def) {
- $err = @{
- ok = $false
- stage = $Stage
- reason = "unknown stage: $Stage. Run install.ps1 -Manifest to list valid stages."
- }
- $err | ConvertTo-Json -Compress | Write-Output
- exit 2
- }
- Step-OutOfInstallDir
- Invoke-Stage -StageDef $def
- exit 0
- }
-
- # Default: full install (today's behavior, plus optional -NonInteractive
- # and -Json layered on by the params above).
- Main
-} catch {
- if ($Json -or $Stage) {
- # Stage-driver mode: caller wants JSON they can parse. Emit a
- # structured error frame and exit non-zero -- BUT only if
- # Invoke-Stage didn't already emit one for this same failure.
- # The inner finally emits the authoritative per-stage frame
- # (with duration_ms + skipped fields); a second emit here
- # would produce two concatenated JSON objects on stdout and
- # break drivers that parse one-line-per-invocation.
- if (-not $script:_StageEmittedErrorFrame) {
- $err = @{
- ok = $false
- stage = if ($Stage) { $Stage } else { $null }
- reason = "$_"
- }
- $err | ConvertTo-Json -Compress | Write-Output
- }
- exit 1
- }
-
- # Interactive mode: keep today's friendly recovery hint.
- Write-Host ""
- Write-Err "Installation failed: $_"
- Write-Host ""
- Write-Info "If the error is unclear, try downloading and running the script directly:"
- Write-Host " Invoke-WebRequest -Uri 'https://hermes-agent.nousresearch.com/install.ps1' -OutFile install.ps1" -ForegroundColor Yellow
- Write-Host " .\install.ps1" -ForegroundColor Yellow
- Write-Host ""
+# No -Stage: run the whole ladder.
+foreach ($s in @("prerequisites","repository","venv","python-deps","node-deps","path","config","setup","gateway","complete")) {
+ Invoke-StageByName $s
}
diff --git a/scripts/msix-shared.mjs b/scripts/msix-shared.mjs
new file mode 100644
index 00000000000..77804d6a896
--- /dev/null
+++ b/scripts/msix-shared.mjs
@@ -0,0 +1,168 @@
+// msix-shared.mjs — the shared MSIX-distribution building blocks used by
+// BOTH the out-of-store feed generator (apps/desktop/scripts/gen-appinstaller.mjs)
+// and the release job that stages the feed (scripts/stage-msixbundle.mjs).
+//
+// The two call sites must agree on every name/URL that Windows keys on — the
+// .appinstaller's MainPackage identity and the bundle URI — so the XML
+// builder and the version/filename derivations live here, once.
+
+import fs from 'node:fs'
+import path from 'node:path'
+import { execFileSync } from 'node:child_process'
+import { createRequire } from 'node:module'
+
+const require = createRequire(import.meta.url)
+
+// The out-of-store MSIX publisher — the ATS signing cert subject, which is
+// what Windows compares against the package manifest publisher at install.
+// Mirrored from electron-builder.config.cjs so the .appinstaller and the
+// manifest can never drift.
+export const OUT_OF_STORE_PUBLISHER =
+ 'CN=Nous Research Inc., O=Nous Research Inc., L=Austin, S=Texas, C=US'
+
+// Content-Type for MSIX / App Installer artifacts. Without the right MIME the
+// browser cannot hand a clicked .appinstaller / .msixbundle to the OS App
+// Installer (it would download as octet-stream instead). Everything else
+// stays octet-stream (R2's default) unchanged. Keys match by filename suffix,
+// case-insensitively.
+const CONTENT_TYPES = {
+ '.appinstaller': 'application/appinstaller',
+ '.msixbundle': 'application/msixbundle',
+ '.msix': 'application/msix'
+}
+
+/** The Content-Type to store for a staged release artifact, if any. */
+export function contentTypeFor(filename) {
+ const lower = String(filename).toLowerCase()
+ for (const [suffix, mime] of Object.entries(CONTENT_TYPES)) {
+ if (lower.endsWith(suffix)) return mime
+ }
+ return undefined
+}
+
+function escapeAttr(value) {
+ return String(value).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
+}
+
+/**
+ * Build an .appinstaller document for a channel.
+ *
+ * @param {{
+ * baseUrl: string // feed host root (no trailing slash)
+ * variantChannelPath: string // e.g. "win32/", "win32/light/", "win32/nightly/"
+ * identityName: string // package Identity Name (e.g. "NousResearch.HermesBundled")
+ * version: string // 4-part MSIX version, e.g. "1.2.3.0"
+ * bundleFilename: string // the universal .msixbundle filename in the feed dir
+ * }} o
+ * @returns {string} the .appinstaller XML
+ */
+export function buildAppInstaller(o) {
+ const bundleUrl = `${o.baseUrl}/${o.variantChannelPath.replace(/\/+$/, '')}/${o.bundleFilename}`
+ const appinstallerUri = bundleUrl.replace(/\.msixbundle$/, '.appinstaller')
+
+ return [
+ '<?xml version="1.0" encoding="utf-8"?>',
+ '<AppInstaller',
+ ` Uri="${escapeAttr(appinstallerUri)}"`,
+ ` Version="${escapeAttr(o.version)}"`,
+ ' xmlns="http://schemas.microsoft.com/appx/appinstaller/2017/2">',
+ ' <MainPackage',
+ ` Name="${escapeAttr(o.identityName)}"`,
+ ` Publisher="${escapeAttr(OUT_OF_STORE_PUBLISHER)}"`,
+ ` Version="${escapeAttr(o.version)}"`,
+ ` Uri="${escapeAttr(bundleUrl)}" />`,
+ ' <UpdateSettings>',
+ ' <OnLaunch HoursBetweenUpdateChecks="12" ShowPrompt="false" />',
+ ' </UpdateSettings>',
+ '</AppInstaller>',
+ ''
+ ].join('\n')
+}
+
+// The nightly tag base + embedded UTC stamp: v0.27.2-nightly.20260829034013
+// (8- or 14-digit; the shorter legacy form is midnight of that day). The
+// base is the next PATCH over the newest stable, so the first three MSIX
+// components come from it (0.27.2) and outversion the stable line
+// structurally — cross-line monotonicity is free.
+const NIGHTLY_TAG_RE = /^v(\d+\.\d+\.\d+)-nightly\.(20\d{6}(?:\d{6})?)$/
+const STABLE_TAG_RE = /^v\d+\.\d+\.\d+$/
+
+// MSIX version components are 16-bit (makeappx rejects >65535). Minutes
+// since the last stable cross it at 45.5 days; a nightly cut more than 45
+// days after its stable is a process failure worth surfacing loudly, not a
+// number to clamp (a clamped number would break monotonicity).
+const MAX_BUILD_MINUTES = 45 * 24 * 60
+
+function stampToEpoch(stamp) {
+ const parts = /^(\d{4})(\d{2})(\d{2})(\d{2})?(\d{2})?(\d{2})?$/.exec(stamp)
+ if (!parts) return 0
+ const [, y, mo, d, h, mi, s] = parts
+ return Date.UTC(Number(y), Number(mo) - 1, Number(d), Number(h ?? 0), Number(mi ?? 0), Number(s ?? 0)) / 1000
+}
+
+export function listGitTags(gitRoot, pattern) {
+ return execFileSync('git', ['tag', '--list', pattern, '--sort=-v:refname'], { cwd: gitRoot, encoding: 'utf8' })
+ .split('\n').filter(Boolean)
+}
+
+export function gitTagCommitTime(gitRoot, tag) {
+ return Number(execFileSync('git', ['log', '-1', '--format=%ct', tag], { cwd: gitRoot, encoding: 'utf8' }).trim())
+}
+
+export function nightlyBuildMinutesFor(tag, stableEpoch) {
+ const m = NIGHTLY_TAG_RE.exec(String(tag || ''))
+ if (!m) return null
+ const minutes = Math.floor((stampToEpoch(m[2]) - stableEpoch) / 60)
+ if (minutes < 0) return 0
+ if (minutes > MAX_BUILD_MINUTES) {
+ throw new Error(
+ `nightly ${tag} is ${Math.floor(minutes / 1440)} days past its stable base — ` +
+ `MSIX versions cap at 16 bits (45 days); cut a stable first`
+ )
+ }
+ return minutes
+}
+
+export function nightlyBuildMinutes(tag, gitRoot) {
+ const m = NIGHTLY_TAG_RE.exec(String(tag || ''))
+ if (!m) return null
+ const majorMinor = m[1].split('.').slice(0, 2).join('.')
+ const stable = listGitTags(gitRoot, `v${majorMinor}.*`).find(t => STABLE_TAG_RE.test(t))
+ if (!stable) return 0 // degenerate: no stable on this line; build number restarts
+ return nightlyBuildMinutesFor(tag, gitTagCommitTime(gitRoot, stable))
+}
+
+/**
+ * Resolve the app identity for a desktop build from the app dir: the product
+ * identity + package version. Pure-ish (reads product-identity.cjs and
+ * package.json from the app dir) so callers on any runner can derive the
+ * exact feed filename/identity without duplicating the derivation.
+ *
+ * @param {string} desktopDir absolute apps/desktop path
+ * @param {string} [tag] the release tag (defaults to HERMES_PAYLOAD_TAG)
+ * @returns {{ identity: object, version: string, name: string, fileVersion: string }}
+ */
+export function appIdentity(desktopDir, tag = process.env.HERMES_PAYLOAD_TAG || '') {
+ const identity = require(path.join(desktopDir, 'product-identity.cjs'))
+ const pkg = JSON.parse(fs.readFileSync(path.join(desktopDir, 'package.json'), 'utf8'))
+ const repoRoot = path.resolve(desktopDir, '..', '..')
+ const nightly = NIGHTLY_TAG_RE.exec(String(tag))
+ if (nightly) {
+ // Manifest + feed version: tag base (0.27.2) + minutes-since-stable.
+ // The artifact FILENAME carries electron-builder's appInfo.version — the
+ // full nightly string (HermesBundled-0.27.2-nightly.X-win-x64.msix) — so
+ // callers that look files up by name need that string separately.
+ return {
+ identity,
+ version: `${nightly[1]}.${nightlyBuildMinutes(String(tag), repoRoot)}`,
+ fileVersion: String(tag).slice(1),
+ name: identity.appNamePascal,
+ }
+ }
+ return {
+ identity,
+ version: `${pkg.version}.0`,
+ fileVersion: pkg.version,
+ name: identity.appNamePascal,
+ }
+}
diff --git a/scripts/r2-release.mjs b/scripts/r2-release.mjs
new file mode 100644
index 00000000000..42e902b9d51
--- /dev/null
+++ b/scripts/r2-release.mjs
@@ -0,0 +1,570 @@
+#!/usr/bin/env node
+// scripts/r2-release.mjs — zero-dependency Cloudflare R2 (S3 API) client for
+// release artifacts. Runs on every release runner (node is guaranteed there
+// via pm/lock.json; the notes + prune jobs need no npm ci), so the only
+// dependency is node's own fetch + crypto. SigV4 signed exactly per the
+// botocore-generated vectors in tests-js/r2-release.test.mjs.
+//
+// node scripts/r2-release.mjs put --tag vX.Y.Z --key <filename> --file <path>
+// node scripts/r2-release.mjs finalize --tag vX.Y.Z --dir <staging-dir>
+// node scripts/r2-release.mjs list [--prefix <p>]
+// node scripts/r2-release.mjs prune-nightlies --keep-days 14 [--dry-run]
+//
+// Env (all required except where noted):
+// CLOUDFLARE_R2_ACCOUNT_ID → S3 endpoint https://<account>.r2.cloudflarestorage.com
+// CLOUDFLARE_R2_ACCESS_KEY_ID R2 API token (S3-compatible)
+// CLOUDFLARE_R2_SECRET_ACCESS_KEY
+// CLOUDFLARE_R2_BUCKET
+//
+// Bucket layout (matches app-updater.ts's D1-settled arms):
+// releases/tag/<tag>/<filename> immutable per-release staging/archive
+// releases/win32/<channel>/<channel>.appinstaller App Installer feed
+// releases/win32/<channel>/*.msixbundle (produced by the
+// msixbundle job)
+// releases/darwin/<channel>/<channel>-mac.yml electron-updater feed
+// releases/darwin/<channel>/*.{dmg,zip,blockmap}
+// where <channel> is stable | nightly (from the tag: -nightly. → nightly).
+// The finalize job merges the matrix legs' staging into these feeds.
+
+import { createHash, createHmac } from 'node:crypto'
+import fs from 'node:fs'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+import { contentTypeFor } from './msix-shared.mjs'
+
+// Re-exported for the r2 test (the Content-Type mapping is shared with the
+// stage job; msix-shared.mjs is the single source).
+export { contentTypeFor } from './msix-shared.mjs'
+
+const REGION = 'auto'
+const SERVICE = 's3'
+const EMPTY_SHA = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
+
+// ---------------------------------------------------------------------------
+// SigV4 (pure; the test file pins these against botocore-generated vectors)
+// ---------------------------------------------------------------------------
+
+/** RFC3986 encode: everything except unreserved [A-Za-z0-9-_.~]. */
+export function rfc3986Encode(value) {
+ return encodeURIComponent(value).replace(/[!'()*]/g, (c) =>
+ '%' + c.charCodeAt(0).toString(16).toUpperCase(),
+ )
+}
+
+/** Canonical query string: params sorted by encoded key (then encoded value). */
+export function canonicalQuery(params) {
+ return Object.entries(params)
+ .map(([k, v]) => [rfc3986Encode(k), rfc3986Encode(String(v))])
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
+ .map(([k, v]) => `${k}=${v}`)
+ .join('&')
+}
+
+/**
+ * Canonical request for one S3-style request.
+ * `headers` is the exact header set that will be sent (host, x-amz-date,
+ * x-amz-content-sha256); canonicalization lowercases + sorts them.
+ */
+export function canonicalRequest(method, path, query, headers, payloadHash) {
+ const names = Object.keys(headers).map((n) => n.toLowerCase()).sort()
+ // Header values are read case-insensitively: keys may be mixed-case
+ // ('Content-Type'), but SigV4 canonicalizes the NAME to lowercase, so
+ // `headers[lowerName]` would miss the value. Find the original-key match.
+ const valueFor = (name) => {
+ const key = Object.keys(headers).find((k) => k.toLowerCase() === name)
+ return key == null ? undefined : headers[key]
+ }
+ const canonicalHeaders = names
+ .map((n) => `${n}:${String(valueFor(n)).trim().replace(/\s+/g, ' ')}`)
+ .join('\n')
+ return [
+ method,
+ path,
+ query,
+ canonicalHeaders,
+ '',
+ names.join(';'),
+ payloadHash,
+ ].join('\n')
+}
+
+/** The AWS4 string-to-sign for a canonical request. */
+export function stringToSign(canonical, date, scope) {
+ return ['AWS4-HMAC-SHA256', date, scope, createHash('sha256').update(canonical).digest('hex')].join('\n')
+}
+
+function hmac(key, msg) {
+ return createHmac('sha256', key).update(msg).digest()
+}
+
+/** Signature for a string-to-sign, given secret key + credential scope parts. */
+export function signature(stringToSignText, secretKey, date, region, service) {
+ const kDate = hmac(`AWS4${secretKey}`, date)
+ const kRegion = hmac(kDate, region)
+ const kService = hmac(kRegion, service)
+ const kSigning = hmac(kService, 'aws4_request')
+ return hmac(kSigning, stringToSignText).toString('hex')
+}
+
+/**
+ * Full AWS4-HMAC-SHA256 Authorization header value for one request.
+ * `now` is 'YYYYMMDDTHHMMSSZ' (injectable for tests); scope date is its
+ * first 8 chars. `payloadHash` is hex sha256 of the body (or the empty
+ * string hash for bodyless requests).
+ */
+export function authHeader({ method, host, path, query, headers, payloadHash, accessKeyId, secretKey, now, region = REGION, service = SERVICE }) {
+ const date = now.slice(0, 8)
+ const canonical = canonicalRequest(method, path, query, headers, payloadHash)
+ const sts = stringToSign(canonical, now, `${date}/${region}/${service}/aws4_request`)
+ const sig = signature(sts, secretKey, date, region, service)
+ const signedHeaders = Object.keys(headers).map((n) => n.toLowerCase()).sort().join(';')
+ return (
+ `AWS4-HMAC-SHA256 Credential=${accessKeyId}/${date}/${region}/${service}/aws4_request, ` +
+ `SignedHeaders=${signedHeaders}, Signature=${sig}`
+ )
+}
+
+// ---------------------------------------------------------------------------
+// R2 request plumbing
+// ---------------------------------------------------------------------------
+
+export function s3Endpoint(accountId) {
+ return `https://${accountId}.r2.cloudflarestorage.com`
+}
+
+/** Encode an object key into the URI path, segment by segment. */
+export function encodeKeyPath(key) {
+ return key.split('/').map(rfc3986Encode).join('/')
+}
+
+function requiredEnv(name) {
+ const value = process.env[name]
+ if (!value) {
+ console.error(`::error::missing env ${name} — see the header comment in scripts/r2-release.mjs`)
+ process.exit(2)
+ }
+ return value
+}
+
+function r2Headers(method, host, path, query, bodyHash, now, creds, contentType, contentLength) {
+ const headers = {
+ host,
+ 'x-amz-date': now,
+ 'x-amz-content-sha256': bodyHash,
+ }
+ // Optional Content-Type for binary artifacts (App Installer / MSIX). It is
+ // added BEFORE the Authorization header is computed, so it lands in the
+ // SigV4 canonical headers + SignedHeaders exactly like host / x-amz-*.
+ if (contentType) headers['Content-Type'] = contentType
+ // Stream bodies (files >2GiB) need an explicit Content-Length — R2
+ // rejects a bodyless-length PUT with 411 MissingContentLength.
+ if (contentLength != null) headers['Content-Length'] = String(contentLength)
+ headers.authorization = authHeader({
+ method,
+ host,
+ path,
+ query,
+ headers,
+ payloadHash: bodyHash,
+ accessKeyId: creds.accessKeyId,
+ secretKey: creds.secretKey,
+ now,
+ })
+ return headers
+}
+
+async function signedFetch(method, url, { body, bodyHash, creds, now, contentType, contentLength }) {
+ const { host, pathname, search } = new URL(url)
+ const query = search.replace(/^\?/, '')
+ const headers = r2Headers(method, host, pathname, query, bodyHash, now, creds, contentType, contentLength)
+ const res = await fetch(url, {
+ method,
+ headers,
+ body: body ?? undefined,
+ // Stream bodies (files >2GiB) require the duplex option on Node's fetch.
+ ...(body != null && typeof body.pipe === 'function' ? { duplex: 'half' } : {}),
+ })
+ const text = await res.text()
+ if (!res.ok) {
+ console.error(`::error::R2 ${method} ${pathname} -> ${res.status}`)
+ if (text) console.error(text.slice(0, 2000))
+ }
+ return { res, text }
+}
+
+async function retry(fn, tries = 3) {
+ let lastError
+ for (let attempt = 1; attempt <= tries; attempt++) {
+ try {
+ return await fn()
+ } catch (err) {
+ lastError = err
+ if (attempt < tries) await new Promise((r) => setTimeout(r, 1000 * attempt))
+ }
+ }
+ throw lastError
+}
+
+// ---------------------------------------------------------------------------
+// Layout helpers (pure)
+// ---------------------------------------------------------------------------
+
+/** 'stable' for a stable tag, 'nightly' for a -nightly.<ts> tag. */
+export function channelForTag(tag) {
+ return /-nightly\.20\d{6}(?:\d{6})?$/.test(tag) ? 'nightly' : 'stable'
+}
+
+// Content-Type for MSIX / App Installer artifacts lives in msix-shared.mjs
+// (single source — the same suffixes must drive the stage job's uploads).
+
+/** Immutable per-release staging key. */
+export function stagingKeyFor(tag, filename) {
+ return `releases/tag/${tag}/${filename}`
+}
+
+/** The feed directory key for a platform arm + channel, e.g. releases/win32/stable/. */
+export function feedDirFor(platform, channel) {
+ return `releases/${platform}/${channel}`
+}
+
+/**
+ * Merge per-leg electron-updater feed ymls (same channel + platform) into one.
+ * Each leg's yml (mac: latest-mac.yml / nightly-mac.yml) lists only its own
+ * arch's files[]; the merged yml keeps the top-level fields of the first leg
+ * (version/releaseDate) and the trailing top-level path/sha512, with the
+ * files[] entries concatenated and deduped by url. Idempotent: merging an
+ * already-merged yml is a no-op.
+ *
+ * Structure of a feed yml (electron-builder):
+ * version: ...
+ * files:
+ * - url: ... ← entries (indented list items)
+ * sha512: ...
+ * size: ...
+ * path: ... ← trailing top-level fields
+ * sha512: ...
+ * releaseDate: ...
+ */
+export function mergeFeedYmls(ymls) {
+ if (ymls.length === 0) return ''
+ const seen = new Set()
+ const entries = []
+
+ for (const yml of ymls) {
+ // Split at the files: marker. Entries are the indented list items
+ // (lines starting with whitespace + '- url:'); the tail is everything
+ // after the last entry (top-level path/sha512/releaseDate).
+ const filesIdx = yml.indexOf('\nfiles:')
+ if (filesIdx === -1) continue
+ const body = yml.slice(filesIdx + 1) // starts right after '\nfiles:'
+ const lines = body.split('\n')
+ let i = 0
+ // Skip the 'files:' line itself.
+ if (lines[0].trim() === '') i = 1
+ // Collect entry blocks: lines starting with '- url:' plus their
+ // following indented sha512/size lines.
+ while (i < lines.length) {
+ const line = lines[i]
+ if (/^\s*-\s+url:/.test(line)) {
+ const block = [line]
+ let j = i + 1
+ while (j < lines.length && /^\s+(?:sha512|size):/.test(lines[j])) {
+ block.push(lines[j])
+ j++
+ }
+ const urlMatch = line.match(/url:\s*([^\s]+)/)
+ if (urlMatch && !seen.has(urlMatch[1])) {
+ seen.add(urlMatch[1])
+ entries.push(block.join('\n'))
+ }
+ i = j
+ } else {
+ i++
+ }
+ }
+ }
+
+ const first = ymls[0]
+ const firstFilesIdx = first.indexOf('\nfiles:')
+ const head = firstFilesIdx === -1 ? first : first.slice(0, firstFilesIdx)
+
+ // Tail: everything after the LAST entry block in the FIRST yml (the
+ // top-level path/sha512/releaseDate lines).
+ let tail = ''
+ {
+ const body = first.slice(firstFilesIdx + 1)
+ const lines = body.split('\n')
+ let lastEntryEnd = -1
+ for (let i = 0; i < lines.length; i++) {
+ if (/^\s*-\s+url:/.test(lines[i])) {
+ let j = i + 1
+ while (j < lines.length && /^\s+(?:sha512|size):/.test(lines[j])) j++
+ lastEntryEnd = j
+ i = j - 1
+ }
+ }
+ if (lastEntryEnd !== -1) {
+ tail = lines.slice(lastEntryEnd).join('\n').replace(/^\n+/, '')
+ }
+ }
+
+ const body = ['files:', ...entries].join('\n')
+ const parts = [head, body]
+ if (tail.trim() !== '') parts.push(tail)
+ return parts.join('\n').replace(/\n{3,}/g, '\n\n').trimEnd() + '\n'
+}
+
+/**
+ * Rewrite a feed yml's path:/url: entries to ABSOLUTE /releases/tag/<tag>/
+ * object keys. The feed manifest lives in releases/darwin/<channel>/ but the
+ * binaries live once in the tag archive; both updater mechanisms resolve the
+ * value against the feed host root (electron-updater: new URL(path, baseUrl)).
+ * `absKey` maps a filename to its absolute key (e.g. /releases/tag/v0.28.0/x).
+ * Values that already start with '/' are left alone (idempotent).
+ */
+export function rewriteFeedPaths(ymlText, absKey) {
+ return ymlText.replace(/^(\s*(?:-\s+)?(?:path|url)):\s*([^\s#]+)\s*$/gm, (_m, key, value) => {
+ if (value.startsWith('/')) return _m
+ return `${key}: ${absKey(value)}`
+ })
+}
+
+// ---------------------------------------------------------------------------
+// Commands
+// ---------------------------------------------------------------------------
+
+async function putObject(creds, base, bucket, key, payload, now, contentType) {
+ // `payload` is either a small in-memory Buffer (feed manifests from
+ // finalize) or a FILE PATH (binaries via `put`). The msixbundle is
+ // ~2.7GB so path payloads stream from disk (fs.readFileSync throws
+ // ERR_FS_FILE_TOO_LARGE past 2GiB); buffers upload directly.
+ const isPath = typeof payload === 'string'
+ const size = isPath ? (await fs.promises.stat(payload)).size : payload.length
+ const bodyHash = isPath
+ ? await new Promise((resolve, reject) => {
+ const hash = createHash('sha256')
+ const stream = fs.createReadStream(payload)
+ stream.on('data', (c) => hash.update(c))
+ stream.on('end', () => resolve(hash.digest('hex')))
+ stream.on('error', reject)
+ })
+ : createHash('sha256').update(payload).digest('hex')
+ const url = `${base}/${bucket}/${encodeKeyPath(key)}`
+ await retry(async () => {
+ // Path payloads get a fresh stream per attempt: a consumed
+ // ReadableStream cannot be replayed for the retry ("body object
+ // should not be disturbed").
+ const body = isPath ? fs.createReadStream(payload) : payload
+ const { res, text } = await signedFetch('PUT', url, { body, bodyHash, contentLength: size, creds, now, contentType })
+ if (!res.ok) throw new Error(`PUT ${key} -> ${res.status}${text ? `: ${text.slice(0, 300)}` : ''}`)
+ })
+ const { res: headRes, text: headText } = await retry(async () => {
+ const r = await signedFetch('HEAD', url, { bodyHash: EMPTY_SHA, creds, now })
+ if (!r.res.ok) throw new Error(`HEAD ${key} -> ${r.res.status}`)
+ return r
+ })
+ const remoteSize = headRes.headers.get('content-length')
+ if (remoteSize === null || String(remoteSize) !== String(size)) {
+ console.error(`::error::R2 HEAD ${key}: size mismatch (remote ${remoteSize}, local ${size})`)
+ process.exit(1)
+ }
+ console.log(`✓ r2: ${key} (${size} bytes)`)
+}
+
+async function cmdPut({ tag, key, file, keyIsFull = false }) {
+ const accountId = requiredEnv('CLOUDFLARE_R2_ACCOUNT_ID')
+ const accessKeyId = requiredEnv('CLOUDFLARE_R2_ACCESS_KEY_ID')
+ const secretKey = requiredEnv('CLOUDFLARE_R2_SECRET_ACCESS_KEY')
+ const bucket = requiredEnv('CLOUDFLARE_R2_BUCKET')
+ const creds = { accessKeyId, secretKey }
+ const base = s3Endpoint(accountId)
+
+ const now = new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '')
+ const keyPath = keyIsFull ? key : stagingKeyFor(tag, key)
+ await putObject(creds, base, bucket, keyPath, file, now, contentTypeFor(key))
+}
+
+/**
+ * finalize: write the per-channel feed MANIFESTS that point at the staged
+ * binaries. Binaries live ONCE under releases/tag/<tag>/ (staged by the
+ * matrix legs); the feed dirs carry only the manifests:
+ *
+ * releases/darwin/<channel>/<channel>-mac.yml
+ * merged electron-updater feed; path:/url: entries rewritten to the
+ * absolute /releases/tag/<tag>/<file> locations (electron-updater
+ * resolves them with new URL(path, baseUrl)).
+ *
+ * The win32 App Installer feed (.appinstaller + .msixbundle per channel
+ * dir) is produced by the msixbundle job (scripts/stage-msixbundle.mjs),
+ * which uploads the manifests directly — nothing for finalize to merge.
+ *
+ * Expects --dir to contain the merged METADATA for ONE tag (the build
+ * matrix uploads only this — the binaries go straight to R2 from each
+ * leg and are never round-tripped through artifacts):
+ * *-mac.yml the per-leg electron-updater feed files
+ */
+async function cmdFinalize({ tag, dir }) {
+ const accountId = requiredEnv('CLOUDFLARE_R2_ACCOUNT_ID')
+ const accessKeyId = requiredEnv('CLOUDFLARE_R2_ACCESS_KEY_ID')
+ const secretKey = requiredEnv('CLOUDFLARE_R2_SECRET_ACCESS_KEY')
+ const bucket = requiredEnv('CLOUDFLARE_R2_BUCKET')
+ const creds = { accessKeyId, secretKey }
+ const base = s3Endpoint(accountId)
+ const channel = channelForTag(tag)
+ const now = new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '')
+
+ const files = fs.readdirSync(dir).filter((f) => fs.statSync(path.join(dir, f)).isFile())
+ // Absolute key of a staged artifact — the feed manifests reference these.
+ const absKey = (filename) => `/${stagingKeyFor(tag, filename)}`
+
+ // --- darwin: merged feed yml only (dmg/zip/blockmap stay in the tag dir) ---
+ const macYmls = files.filter((f) => f.endsWith(`-mac.yml`))
+ if (macYmls.length > 0) {
+ const darDir = feedDirFor('darwin', channel)
+ const macFeedName = `${channel}-mac.yml`
+ // Rewrite path:/url: to absolute /releases/tag/<tag>/ locations so the
+ // client fetches binaries from the archive, not the feed dir.
+ const merged = rewriteFeedPaths(mergeFeedYmls(macYmls.map((f) => fs.readFileSync(path.join(dir, f), 'utf8'))), absKey)
+ await putObject(creds, base, bucket, `${darDir}/${macFeedName}`, Buffer.from(merged, 'utf8'), now)
+ }
+
+ console.log(`✓ r2: finalized ${tag} → ${channel} feed manifests`)
+}
+
+/** Parse a ListObjectsV2 XML body into { keys: string[], truncated, nextToken }. */
+export function parseListXml(xml) {
+ const unescape = (s) =>
+ s.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&amp;/g, '&')
+ const keys = [...xml.matchAll(/<Key>([^<]+)<\/Key>/g)].map((m) => unescape(m[1]))
+ const truncated = /<IsTruncated>true<\/IsTruncated>/.test(xml)
+ const tokenMatch = xml.match(/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/)
+ return { keys, truncated, nextToken: tokenMatch ? unescape(tokenMatch[1]) : null }
+}
+
+async function listObjects(prefix = '') {
+ const accountId = requiredEnv('CLOUDFLARE_R2_ACCOUNT_ID')
+ const accessKeyId = requiredEnv('CLOUDFLARE_R2_ACCESS_KEY_ID')
+ const secretKey = requiredEnv('CLOUDFLARE_R2_SECRET_ACCESS_KEY')
+ const bucket = requiredEnv('CLOUDFLARE_R2_BUCKET')
+ const creds = { accessKeyId, secretKey }
+ const base = s3Endpoint(accountId)
+
+ const keys = []
+ let token = null
+ for (;;) {
+ const params = { 'list-type': '2', 'max-keys': '1000' }
+ if (prefix) params.prefix = prefix
+ if (token) params['continuation-token'] = token
+ const query = canonicalQuery(params)
+ const now = new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '')
+ const url = `${base}/${bucket}?${query}`
+ const { res, text } = await signedFetch('GET', url, { bodyHash: EMPTY_SHA, creds, now })
+ if (!res.ok) process.exit(1)
+ const parsed = parseListXml(text)
+ keys.push(...parsed.keys)
+ if (!parsed.truncated || !parsed.nextToken) break
+ token = parsed.nextToken
+ }
+ return keys
+}
+
+async function cmdList({ prefix }) {
+ for (const key of await listObjects(prefix)) console.log(key)
+}
+
+/** Keys whose own nightly date (YYYYMMDD in the name) is before `cutoff`. */
+export function nightlyDoomedKeys(keys, cutoff) {
+ return keys.filter((key) => {
+ const m = key.match(/-nightly\.(\d{8})/)
+ return m && m[1] < cutoff
+ })
+}
+
+async function cmdPrune({ keepDays, dryRun }) {
+ const accountId = requiredEnv('CLOUDFLARE_R2_ACCOUNT_ID')
+ const accessKeyId = requiredEnv('CLOUDFLARE_R2_ACCESS_KEY_ID')
+ const secretKey = requiredEnv('CLOUDFLARE_R2_SECRET_ACCESS_KEY')
+ const bucket = requiredEnv('CLOUDFLARE_R2_BUCKET')
+ const creds = { accessKeyId, secretKey }
+ const base = s3Endpoint(accountId)
+
+ // Cutoff dated by the nightly suffix in the KEY (like release.py's
+ // --prune-nightlies: a re-uploaded old tag never resets its clock).
+ const cutoff = new Date(Date.now() - keepDays * 86400_000).toISOString().slice(0, 10).replace(/-/g, '')
+ const keys = await listObjects()
+ const doomed = nightlyDoomedKeys(keys, cutoff)
+ if (doomed.length === 0) {
+ console.log(`✓ r2: no nightly objects older than ${keepDays} days`)
+ return
+ }
+ const now = new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '')
+ for (const key of doomed.sort()) {
+ if (dryRun) {
+ console.log(`(dry-run) would delete r2:${key}`)
+ continue
+ }
+ const url = `${base}/${bucket}/${encodeKeyPath(key)}`
+ const { res } = await signedFetch('DELETE', url, { bodyHash: EMPTY_SHA, creds, now })
+ if (!res.ok) process.exit(1)
+ console.log(`deleted r2:${key}`)
+ }
+}
+
+// ---------------------------------------------------------------------------
+// CLI
+// ---------------------------------------------------------------------------
+
+function usage() {
+ console.error(`usage:
+ node scripts/r2-release.mjs put --tag vX.Y.Z --key <filename> --file <path> [--key-is-full]
+ node scripts/r2-release.mjs finalize --tag vX.Y.Z --dir <staging-dir>
+ node scripts/r2-release.mjs list [--prefix <p>]
+ node scripts/r2-release.mjs prune-nightlies --keep-days <n> [--dry-run]
+
+ --key-is-full: the --key is a FULL object key (e.g. releases/win32/stable/…),
+ not a filename to archive under releases/tag/<tag>/.`)
+ process.exit(2)
+}
+
+export function isMain() {
+ return process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]
+}
+
+export async function main(argv = process.argv.slice(2)) {
+ const [cmd, ...rest] = argv
+ const args = {}
+ for (let i = 0; i < rest.length; i++) {
+ const flag = rest[i]
+ if (['--tag', '--key', '--file', '--prefix', '--keep-days', '--dir'].includes(flag)) {
+ args[flag.slice(2)] = rest[++i]
+ } else if (flag === '--dry-run' || flag === '--key-is-full') {
+ args[flag.slice(2)] = true
+ } else {
+ usage()
+ }
+ }
+ if (cmd === 'put') {
+ const tag = args.tag || process.env.HERMES_PAYLOAD_TAG
+ if (!tag || !args.key || !args.file) usage()
+ await cmdPut({ tag, key: args.key, file: args.file, keyIsFull: Boolean(args['key-is-full']) })
+ } else if (cmd === 'finalize') {
+ if (!args.tag || !args.dir) usage()
+ await cmdFinalize({ tag: args.tag, dir: args.dir })
+ } else if (cmd === 'list') {
+ await cmdList({ prefix: args.prefix ?? '' })
+ } else if (cmd === 'prune-nightlies') {
+ const keepDays = Number(args['keep-days'])
+ if (!Number.isFinite(keepDays) || keepDays <= 0) usage()
+ await cmdPrune({ keepDays, dryRun: Boolean(args.dryRun) })
+ } else {
+ usage()
+ }
+}
+
+if (isMain()) {
+ main().catch((err) => {
+ console.error(`::error::${err?.stack ?? err}`)
+ process.exit(1)
+ })
+}
diff --git a/scripts/release.py b/scripts/release.py
index 8bd98eeb2fa..0de000c1d4c 100755
--- a/scripts/release.py
+++ b/scripts/release.py
@@ -2174,10 +2174,9 @@ def dispatch_desktop_build(tag: str, gh_repo: str | None) -> bool:
(the workflow checks out ${{ inputs.tag }}), so an old-tag rebuild
builds the old snapshot with the current workflow.
"""
- dispatch_ref = _default_branch(gh_repo) or "main"
cmd = [
"gh", "workflow", "run", "desktop-bundled-release.yml",
- "--ref", dispatch_ref,
+ "--ref", "main", # placeholder — replaced after the which-guard below
"-f", f"tag={tag}",
"-f", "upload_release=true",
]
@@ -2189,6 +2188,9 @@ def dispatch_desktop_build(tag: str, gh_repo: str | None) -> bool:
print(f" Start it manually: {' '.join(cmd)}")
return False
+ dispatch_ref = _default_branch(gh_repo) or "main"
+ cmd[cmd.index("--ref") + 1] = dispatch_ref
+
result = subprocess.run(
cmd, capture_output=True, text=True, encoding="utf-8",
errors="replace", cwd=str(REPO_ROOT),
diff --git a/scripts/render-builds-table.py b/scripts/render-builds-table.py
new file mode 100644
index 00000000000..9cb8c859c69
--- /dev/null
+++ b/scripts/render-builds-table.py
@@ -0,0 +1,213 @@
+#!/usr/bin/env python3
+"""Render the release download tables into <!-- HERMES_BUILDS_TABLE -->.
+
+Runs as the LAST job of desktop-bundled-release.yml, after every matrix
+leg has uploaded, and edits the GitHub release body in place. The tables
+are built from the bucket's ACTUAL object names (scripts/r2-release.mjs
+list --prefix releases/tag/<tag>/), filtered to the tag's exact version —
+a missing artifact shows up as a missing row, never a dead link. The
+GitHub release carries the notes only; the binaries live in the R2 bucket
+under releases/tag/<tag>/, and the download links point at the R2 public
+URL (CLOUDFLARE_R2_PUBLIC_URL / --r2-base-url).
+
+Tables: Hermes Desktop (bundled) and Hermes Light, one row per (OS,
+arch). Feed manifests (latest*/light*/nightly*.yml), blockmaps and mac .zip
+(an electron-updater delta target, not a user download) stay out of the
+tables on purpose; they still live in the bucket for the updater to
+consume.
+
+With --pending-run-url, renders a "builds in progress" link to the
+workflow run instead of the tables. The builds-pending job runs this
+mode as the first job of the run, so the draft body points at the live
+run while the matrix builds. The link block keeps the marker wrapper,
+so the final render replaces it.
+
+Usage: render-builds-table.py --tag vX.Y.Z [--repo owner/repo] [--r2-base-url URL] [--dry-run]
+Idempotent: re-running replaces the previously rendered block (the
+marker is kept as an HTML comment wrapper around the tables).
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import re
+import subprocess
+import sys
+
+MARKER = "<!-- HERMES_BUILDS_TABLE -->"
+END_MARKER = "<!-- /HERMES_BUILDS_TABLE -->"
+
+# Asset name shapes (electron-builder artifactName in
+# apps/desktop/electron-builder.config.cjs):
+# Hermes-0.28.0-mac-arm64.dmg (bundled)
+# HermesBundled-0.28.0-win-x64.msix (bundled)
+_ASSET_RE = re.compile(
+ r"^(?P<app>HermesBundled|HermesLight)-(?P<version>[^-]+(?:-nightly\.\d{8}(?:\d{6})?)?)"
+ r"-(?P<os>mac|win|linux)-(?P<arch>x64|arm64)\.(?P<ext>dmg|msix|AppImage)$"
+)
+
+_OS_LABEL = {"mac": "macOS", "win": "Windows", "linux": "Linux"}
+_ARCH_LABEL = {"x64": "x64 (Intel/AMD)", "arm64": "arm64 (Apple Silicon/ARM)"}
+_KIND_LABEL = {"dmg": "DMG", "msix": "MSIX", "AppImage": "AppImage"}
+_ROW_ORDER = [("mac", "arm64"), ("mac", "x64"), ("win", "x64"), ("win", "arm64"),
+ ("linux", "x64"), ("linux", "arm64")]
+
+
+def parse_assets(names: list[str]) -> dict[str, dict[tuple[str, str], tuple[str, str]]]:
+ """{app: {(os, arch): (full_key, ext)}} for table-shaped assets only.
+
+ Object keys are releases/tag/<tag>/<filename>; the shape match runs on
+ the basename, but the stored name keeps the full key so the download
+ link points at the object's real location.
+ """
+ out: dict[str, dict[tuple[str, str], tuple[str, str]]] = {"HermesBundled": {}, "HermesLight": {}}
+ for name in names:
+ base = name.rsplit("/", 1)[-1]
+ m = _ASSET_RE.match(base)
+ if m:
+ out[m.group("app")][(m.group("os"), m.group("arch"))] = (name, m.group("ext"))
+ return out
+
+
+def render_tables(assets_by_app: dict, base_url: str) -> str:
+ """The replacement block: marker + tables + end marker."""
+ base = base_url.rstrip("/")
+ sections = []
+ for app, title in (("HermesBundled", "Hermes Desktop"), ("HermesLight", "Hermes Light (remote-only client)")):
+ rows = []
+ for key in _ROW_ORDER:
+ entry = assets_by_app.get(app, {}).get(key)
+ if not entry:
+ continue
+ name, ext = entry
+ os_name, arch = key
+ rows.append(
+ f"| {_OS_LABEL[os_name]} | {_ARCH_LABEL[arch]} "
+ f"| [{_KIND_LABEL[ext]}]({base}/{name}) |"
+ )
+ if rows:
+ sections.append(
+ f"### {title}\n\n| OS | Architecture | Download |\n|---|---|---|\n"
+ + "\n".join(rows)
+ )
+ if not sections:
+ return ""
+ return MARKER + "\n## Downloads\n\n" + "\n\n".join(sections) + "\n" + END_MARKER
+
+
+def render_pending(run_url: str) -> str:
+ """The placeholder block: a link to the run, in the same marker wrapper."""
+ return (
+ MARKER
+ + f"\n> 🚧 [Builds in progress]({run_url}) — the download links"
+ + " appear here when the build matrix finishes.\n"
+ + END_MARKER
+ )
+
+
+def filter_names_for_version(names: list[str], version: str) -> list[str]:
+ """Table-shaped names whose embedded version equals `version` (exact, not prefix).
+
+ Matches on the basename (keys carry the releases/tag/<tag>/ prefix) and
+ returns the full keys.
+ """
+ out = []
+ for name in names:
+ base = name.rsplit("/", 1)[-1]
+ m = _ASSET_RE.match(base)
+ if m and m.group("version") == version:
+ out.append(name)
+ return out
+
+
+def r2_object_names(tag: str) -> list[str]:
+ """Object keys in the R2 staging dir for `tag`, under releases/tag/<tag>/.
+
+ Exact version match, never prefix: 'v0.28.0' must not pick up
+ '0.28.0-nightly.20260818...' objects (they live under their own tag
+ directory, and the basename filter would reject them anyway). The list
+ call shells out to scripts/r2-release.mjs, which reads the R2 env vars
+ and needs only node (no npm ci in this job).
+ """
+ run = subprocess.run(
+ ["node", "scripts/r2-release.mjs", "list", "--prefix", f"releases/tag/{tag}/"],
+ capture_output=True, text=True, encoding="utf-8", errors="replace",
+ )
+ if run.returncode != 0:
+ print(f"::error::r2 list failed: {run.stderr.strip() or run.stdout.strip()}")
+ raise SystemExit(1)
+ keys = [line.strip() for line in run.stdout.splitlines() if line.strip()]
+ return filter_names_for_version(keys, tag.lstrip("v"))
+
+
+def splice(body: str, block: str) -> str:
+ """Replace the marker (or a previously rendered block) with `block`."""
+ if END_MARKER in body:
+ pattern = re.compile(re.escape(MARKER) + r".*?" + re.escape(END_MARKER), re.DOTALL)
+ return pattern.sub(lambda _m: block, body, count=1)
+ return body.replace(MARKER, block, 1)
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--tag", required=True)
+ parser.add_argument("--repo", default="NousResearch/hermes-agent")
+ parser.add_argument("--r2-base-url", default=os.environ.get("CLOUDFLARE_R2_PUBLIC_URL"),
+ help="Public base URL of the R2 bucket (default: $CLOUDFLARE_R2_PUBLIC_URL)")
+ parser.add_argument("--dry-run", action="store_true",
+ help="Print the spliced body instead of editing the release")
+ parser.add_argument("--pending-run-url", default=None,
+ help="Render a 'builds in progress' link to this workflow run "
+ "instead of the tables")
+ args = parser.parse_args()
+
+ view = subprocess.run(
+ ["gh", "release", "view", args.tag, "--repo", args.repo,
+ "--json", "body"],
+ capture_output=True, text=True, encoding="utf-8", errors="replace",
+ )
+ if view.returncode != 0:
+ print(f"::error::gh release view failed: {view.stderr.strip()}")
+ return 1
+ release = json.loads(view.stdout)
+ body = release.get("body") or ""
+
+ if args.pending_run_url:
+ block = render_pending(args.pending_run_url)
+ names: list[str] = []
+ else:
+ if not args.r2_base_url:
+ print("::error::--r2-base-url (or CLOUDFLARE_R2_PUBLIC_URL) is required to render the tables")
+ return 1
+ names = r2_object_names(args.tag)
+ block = render_tables(parse_assets(names), args.r2_base_url)
+ if not block:
+ print("::warning::no table-shaped assets for this tag in the bucket; leaving the body unchanged")
+ return 0
+ if MARKER not in body:
+ print("::warning::release body has no HERMES_BUILDS_TABLE marker; leaving it unchanged")
+ return 0
+
+ new_body = splice(body, block)
+ if args.dry_run:
+ print(new_body)
+ return 0
+
+ edit = subprocess.run(
+ ["gh", "release", "edit", args.tag, "--repo", args.repo,
+ "--notes-file", "-"],
+ input=new_body, capture_output=True, text=True, encoding="utf-8",
+ errors="replace",
+ )
+ if edit.returncode != 0:
+ print(f"::error::gh release edit failed: {edit.stderr.strip()}")
+ return 1
+ what = "Builds-in-progress link" if args.pending_run_url else "Builds table"
+ print(f"✓ {what} rendered into {args.tag} ({len(names)} assets scanned)")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/run_tests.sh b/scripts/run_tests.sh
index 4445d6d5428..9e32af19698 100755
--- a/scripts/run_tests.sh
+++ b/scripts/run_tests.sh
@@ -135,7 +135,7 @@ done
# the build step just loaded; stripping it made every per-file pytest
# subprocess rebuild the 5GB image from a cold builder cache instead
# (~4 min per worker per run, and the rebuilt image lacked the
-# HERMES_GIT_SHA build-arg the workflow bakes in).
+# install stamp the workflow bakes in).
#
# These are test-infrastructure knobs, not credentials — same class as the
# HERMES_RUN_SLOW_PET_TESTS / HERMES_E2E_BROWSER opt-ins already forwarded.
@@ -152,6 +152,17 @@ done
# ── Run in hermetic env ──────────────────────────────────────────────────────
# env -i: start with empty environment, opt-in only what we need.
# No credential var can leak — you'd have to explicitly add it here.
+#
+# __NIXOS_SET_ENVIRONMENT_DONE is a NixOS platform guard, not a credential:
+# without it, every login shell (bash -l) that a test spawns re-runs
+# /etc/set-environment and rebuilds PATH from the system profile — which
+# evicts the dev shell's python3/rg and makes terminal, process-registry,
+# and ripgrep-backed search tests fail with exit 127 on NixOS hosts.
+#
+# HERMES_PYTHON_SRC_ROOT is the Nix dev shell's editable-install root: the
+# venv's editable finder reads it at runtime to locate first-party modules.
+# Stripping it breaks "import tools" in every test subprocess whose cwd is
+# not the repo root (the import-guard probe runs from a tempdir).
echo "▶ running per-file parallel test suite via run_tests_parallel.py"
echo " (TZ=UTC LANG=C.UTF-8 PYTHONHASHSEED=0; clean env)"
@@ -178,6 +189,8 @@ exec env -i \
PYTHONUTF8=1 \
${HERMES_RUN_SLOW_PET_TESTS:+HERMES_RUN_SLOW_PET_TESTS="$HERMES_RUN_SLOW_PET_TESTS"} \
${HERMES_E2E_BROWSER:+HERMES_E2E_BROWSER="$HERMES_E2E_BROWSER"} \
+ ${__NIXOS_SET_ENVIRONMENT_DONE:+__NIXOS_SET_ENVIRONMENT_DONE="$__NIXOS_SET_ENVIRONMENT_DONE"} \
+ ${HERMES_PYTHON_SRC_ROOT:+HERMES_PYTHON_SRC_ROOT="$HERMES_PYTHON_SRC_ROOT"} \
${EXTRA_PYTHONPATH:+PYTHONPATH="$EXTRA_PYTHONPATH"} \
${EXTRA_PYTEST_PLUGINS:+PYTEST_PLUGINS="$EXTRA_PYTEST_PLUGINS"} \
"$PYTHON" "$SCRIPT_DIR/run_tests_parallel.py" "$@"
diff --git a/scripts/stage-msixbundle.mjs b/scripts/stage-msixbundle.mjs
new file mode 100644
index 00000000000..6cb91903b82
--- /dev/null
+++ b/scripts/stage-msixbundle.mjs
@@ -0,0 +1,320 @@
+#!/usr/bin/env node
+// stage-msixbundle.mjs — the out-of-store MSIX distribution job.
+//
+// Runs on a Windows runner of the release workflow AFTER all legs built
+// (needs: build). Two responsibilities:
+//
+// 1. OUT-OF-STORE FEED: bundle the x64 + arm64 per-arch .msix into one
+// universal .msixbundle, sign the bundle envelope, write the per-channel
+// .appinstaller, and upload both to the win32 feed dirs:
+// releases/win32/<stable|nightly>/<name>-<ver>.win.msixbundle
+// releases/win32/<stable|nightly>/stable.appinstaller (or nightly.*)
+// The .appinstaller is the install + auto-update entry point; the bundle
+// is what the OS installs and swaps on update. Per-arch .msix files stay
+// in the immutable releases/tag/<tag>/ archive (uploaded by the legs).
+//
+// 2. STORE ARCHIVE: re-upload the Store-submission .msix files (built by
+// the win legs, prefixed Store-) to the tag archive. The Store is the
+// distribution for those — they never touch a feed dir.
+//
+// Usage (win runner, bash):
+// node scripts/stage-msixbundle.mjs --tag vX.Y.Z [--variant bundled|light]
+// Reads HERMES_DESKTOP_VARIANT (bundled|light) from the environment; the
+// workflow runs this job once per variant.
+import { createHash } from 'node:crypto'
+import { execFileSync } from 'node:child_process'
+import fs from 'node:fs'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+import { appIdentity, buildAppInstaller } from './msix-shared.mjs'
+
+const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
+
+// node strips the first '--' (and an immediately-following option) for its
+// own use; parse space-separated flag pairs, not --flag=value.
+const args = process.argv.slice(2)
+const flagValue = (name) => {
+ for (let i = 0; i < args.length - 1; i += 1) {
+ if (args[i] === name) return args[i + 1]
+ }
+ return undefined
+}
+const tag = flagValue('--tag')
+const variant = flagValue('--variant') || process.env.HERMES_DESKTOP_VARIANT || 'bundled'
+
+// product-identity.cjs keys the app name off HERMES_DESKTOP_VARIANT — the
+// artifact filenames (HermesBundled-*-win-x64.msix) carry the bundled
+// identity, so the env var MUST match the variant or the msix lookup
+// fails. Set it before anything requires the identity.
+process.env.HERMES_DESKTOP_VARIANT = variant
+
+if (!tag) {
+ console.error('[stage-msixbundle] --tag=<vX.Y.Z> is required')
+ process.exit(1)
+}
+if (!['bundled', 'light'].includes(variant)) {
+ console.error(`[stage-msixbundle] --variant must be 'bundled' or 'light', got '${variant}'`)
+ process.exit(1)
+}
+if (process.platform !== 'win32') {
+ console.error('[stage-msixbundle] this job must run on a Windows runner (makeappx + signtool)')
+ process.exit(1)
+}
+
+const nightly = /-nightly\./.test(tag)
+const channel = nightly ? 'nightly' : 'stable'
+const channelDir = `releases/win32/${variant === 'light' ? 'light/' : ''}${channel}`
+
+const desktop = path.join(REPO_ROOT, 'apps', 'desktop')
+const releaseDir = path.join(desktop, 'release')
+const { identity, version, name, fileVersion } = appIdentity(desktop, tag)
+
+// Per-arch .msix files are found by the name electron-builder gave them
+// (appInfo.version = the 3-part or full-nightly string, NOT the 4-part feed
+// version). The bundle /bv, .appinstaller Version and feed filenames all use
+// the 4-part `version` — what Windows compares for updates.
+function msixFile(arch) {
+ return path.join(releaseDir, `${name}-${fileVersion}-win-${arch}.msix`)
+}
+function bundleFile() {
+ return path.join(releaseDir, `${name}-${version}-win.msixbundle`)
+}
+
+// ── makeappx / signtool resolution (SDK BuildTools nuget) ──────────────────
+// electron-builder downloads Microsoft.Windows.SDK.BuildTools into its winCodeSign
+// cache; this job uses the SAME pin so makeappx/signtool match the builder's.
+function resolveWinSdkTools() {
+ const candidates = []
+ // electron-builder downloads its signing toolsets into the cache root
+ // (ELECTRON_BUILDER_CACHE on CI, %LOCALAPPDATA%/electron-builder/Cache
+ // by default) under `win-codesign@<ver>/` — there is NO `winCodeSign`
+ // subdir. The Windows Kits bundle extracts to
+ // win-codesign@<ver>/windows-kits-bundle-10_0_26100_0-<hash>/ with the
+ // HOST tools (signtool.exe + makeappx.exe) in its x64/ subdir. Legacy
+ // winCodeSign-2.6.0 used windows-10/<arch>/; the old nuget layout
+ // bin/<ver>/x64/ is long gone.
+ const roots = [
+ process.env.ELECTRON_BUILDER_CACHE || '',
+ path.join(process.env.LOCALAPPDATA || '', 'electron-builder', 'Cache'),
+ path.join(process.env.LOCALAPPDATA || '', 'electron-builder', 'cache'),
+ path.join(process.env.USERPROFILE || '', 'AppData', 'Local', 'electron-builder', 'Cache')
+ ]
+ for (const root of roots) {
+ if (!root || !fs.existsSync(root)) continue
+ for (const entry of fs.readdirSync(root)) {
+ const dir = path.join(root, entry)
+ if (!fs.statSync(dir).isDirectory()) continue
+ // Modern electron-builder ([email protected]): the Windows Kits bundle
+ // extracts to <cacheDir>/win-codesign@<ver>/windows-kits-bundle-10_0_26100_0-<hash>/,
+ // with the HOST tools (signtool.exe + makeappx.exe) directly in the
+ // x64/ subdir of the bundle folder — two levels under the cache root.
+ // Legacy winCodeSign-2.6.0 used windows-10/<arch>/ under the toolset
+ // dir; the old nuget layout bin/<ver>/x64/ is gone. Check every dir
+ // two levels down that carries a makeappx.exe + signtool.exe.
+ const toolDirs = []
+ for (const sub of fs.readdirSync(dir)) {
+ const subDir = path.join(dir, sub)
+ if (!fs.statSync(subDir).isDirectory()) continue
+ for (const arch of ['x64']) {
+ const x64 = path.join(subDir, arch)
+ if (fs.existsSync(path.join(x64, 'makeappx.exe')) && fs.existsSync(path.join(x64, 'signtool.exe'))) {
+ toolDirs.push(x64)
+ }
+ }
+ // Legacy: windows-10/x64 (winCodeSign-2.6.0)
+ const win10 = path.join(subDir, 'windows-10', 'x64')
+ if (fs.existsSync(path.join(win10, 'makeappx.exe')) && fs.existsSync(path.join(win10, 'signtool.exe'))) {
+ toolDirs.push(win10)
+ }
+ // Legacy nuget: bin/<ver>/x64
+ const binDir = path.join(subDir, 'bin')
+ if (fs.existsSync(binDir)) {
+ for (const bsub of fs.readdirSync(binDir)) {
+ const x64 = path.join(binDir, bsub, 'x64')
+ if (fs.existsSync(path.join(x64, 'makeappx.exe')) && fs.existsSync(path.join(x64, 'signtool.exe'))) {
+ toolDirs.push(x64)
+ }
+ }
+ }
+ }
+ // First root with a usable kit wins — the configured
+ // ELECTRON_BUILDER_CACHE must beat any stray default cache.
+ if (toolDirs.length > 0) {
+ toolDirs.sort()
+ return toolDirs[toolDirs.length - 1]
+ }
+ }
+ }
+ if (candidates.length === 0) {
+ console.error('[stage-msixbundle] no makeappx/signtool found under electron-builder winCodeSign cache')
+ process.exit(1)
+ }
+ // Prefer the newest SDK build.
+ candidates.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
+ return candidates[candidates.length - 1]
+}
+
+const winSdk = resolveWinSdkTools()
+const makeappx = path.join(winSdk, 'makeappx.exe')
+const signtool = path.join(winSdk, 'signtool.exe')
+
+// ── 1. bundle ──────────────────────────────────────────────────────────────
+const x64 = msixFile('x64')
+const arm64 = msixFile('arm64')
+const bundle = bundleFile()
+if (!fs.existsSync(x64) || !fs.existsSync(arm64)) {
+ console.error(`[stage-msixbundle] need both per-arch msix to bundle:\n ${x64}\n ${arm64}`)
+ process.exit(1)
+}
+
+// makeappx bundle /d includes EVERY .msix in the dir — the Store-submission
+// packages (Store-*.msix, same release dir after the legs merged their
+// artifacts) must never ride inside the out-of-store bundle. Stage only the
+// two per-arch packages into a clean dir before bundling.
+const bundleStaging = path.join(releaseDir, '__bundle-staging')
+fs.rmSync(bundleStaging, { recursive: true, force: true })
+fs.mkdirSync(bundleStaging, { recursive: true })
+fs.copyFileSync(x64, path.join(bundleStaging, path.basename(x64)))
+fs.copyFileSync(arm64, path.join(bundleStaging, path.basename(arm64)))
+
+if (fs.existsSync(bundle)) fs.rmSync(bundle, { force: true })
+execFileSync(makeappx, ['bundle', '/o', '/bv', version, '/d', bundleStaging, '/p', bundle], { stdio: 'inherit' })
+
+// Sign ONLY the bundle envelope; the inner .msix keep their build-leg
+// signatures. Runs only when the Azure vars are present (fork without them
+// ships unsigned — same posture as the build legs).
+if (process.env.AZURE_SIGN_ENDPOINT && process.env.AZURE_SIGN_ACCOUNT && process.env.AZURE_SIGN_PROFILE) {
+ const dlib = resolveTrustedSigningDlib()
+ if (dlib) {
+ const metaPath = path.join(releaseDir, 'msixbundle-sign.json')
+ fs.writeFileSync(metaPath, JSON.stringify({
+ Endpoint: process.env.AZURE_SIGN_ENDPOINT,
+ CodeSigningAccountName: process.env.AZURE_SIGN_ACCOUNT,
+ CertificateProfileName: process.env.AZURE_SIGN_PROFILE
+ }))
+ const signEnv = { ...process.env }
+ const dotnetRoot = resolveDotnetRuntimeDir()
+ if (dotnetRoot) signEnv.DOTNET_ROOT = dotnetRoot
+ execFileSync(signtool, [
+ 'sign', '/fd', 'SHA256', '/td', 'SHA256', '/tr', 'http://timestamp.acs.microsoft.com',
+ '/dlib', dlib, '/dmdf', metaPath, bundle
+ ], { stdio: 'inherit', env: signEnv })
+ execFileSync(signtool, ['verify', '/pa', bundle], { stdio: 'inherit' })
+ } else {
+ console.warn('[stage-msixbundle] Azure Trusted Signing dlib not found — bundle will be UNSIGNED')
+ }
+} else {
+ console.warn('[stage-msixbundle] AZURE_SIGN_* not set — bundle will be UNSIGNED')
+}
+
+function resolveTrustedSigningDlib() {
+ const roots = [
+ process.env.ELECTRON_BUILDER_CACHE || '',
+ path.join(process.env.LOCALAPPDATA || '', 'electron-builder', 'Cache'),
+ path.join(process.env.USERPROFILE || '', 'AppData', 'Local', 'electron-builder', 'Cache')
+ ]
+ // signtool above is always the x64 kit (resolveWinSdkTools scans x64 only),
+ // so the dlib must be the x64 one too — a 32-bit dlib cannot load in a 64-bit
+ // signtool process. The ats-bundle ships x86/ and x64/ subdirs.
+ const arch = 'x64'
+ for (const root of roots) {
+ if (!root || !fs.existsSync(root)) continue
+ const found = []
+ for (const entry of fs.readdirSync(root)) {
+ const dir = path.join(root, entry)
+ if (!fs.statSync(dir).isDirectory()) continue
+ const walk = (p) => {
+ if (!fs.existsSync(p)) return
+ if (fs.statSync(p).isDirectory()) {
+ for (const child of fs.readdirSync(p)) walk(path.join(p, child))
+ } else if (path.basename(p).toLowerCase() === 'azure.codesigning.dlib.dll') {
+ found.push(p)
+ }
+ }
+ walk(dir)
+ }
+ if (found.length > 0) {
+ const matched = found.filter(p => path.basename(path.dirname(p)).toLowerCase() === arch)
+ const pool = matched.length > 0 ? matched : found
+ pool.sort()
+ return pool[pool.length - 1]
+ }
+ }
+ return null
+}
+
+// The ATS dlib is a .NET assembly loaded via Ijwhost.dll, which finds
+// hostfxr.dll through DOTNET_ROOT — mirror app-builder-lib's
+// WindowsSignAzureManager and point it at the bundled runtime dir.
+function resolveDotnetRuntimeDir() {
+ const roots = [
+ process.env.ELECTRON_BUILDER_CACHE || '',
+ path.join(process.env.LOCALAPPDATA || '', 'electron-builder', 'Cache'),
+ path.join(process.env.USERPROFILE || '', 'AppData', 'Local', 'electron-builder', 'Cache')
+ ]
+ for (const root of roots) {
+ if (!root || !fs.existsSync(root)) continue
+ const found = []
+ const walk = (p, depth) => {
+ if (depth > 3) return
+ if (!fs.existsSync(p)) return
+ if (fs.statSync(p).isDirectory()) {
+ for (const child of fs.readdirSync(p)) {
+ const full = path.join(p, child)
+ if (/^dotnet-runtime-/.test(child)) found.push(full)
+ else walk(full, depth + 1)
+ }
+ }
+ }
+ for (const entry of fs.readdirSync(root)) {
+ walk(path.join(root, entry), 0)
+ }
+ if (found.length > 0) {
+ found.sort()
+ return found[found.length - 1]
+ }
+ }
+ return null
+}
+
+// ── 2. .appinstaller + uploads ─────────────────────────────────────────────
+const baseUrl = String(process.env.CLOUDFLARE_R2_PUBLIC_URL || '').replace(/\/+$/, '')
+if (!baseUrl) {
+ console.error('[stage-msixbundle] CLOUDFLARE_R2_PUBLIC_URL is required (feed dir URLs come from it)')
+ process.exit(1)
+}
+
+const appinstaller = buildAppInstaller({
+ baseUrl,
+ variantChannelPath: channelDir,
+ identityName: identity.msixAppIdWithOrg,
+ version,
+ bundleFilename: `${name}-${version}-win.msixbundle`
+})
+const appinstallerName = `${channel}.appinstaller`
+fs.writeFileSync(path.join(releaseDir, appinstallerName), appinstaller)
+
+const upload = (key, file, keyIsFull = false) => {
+ // NOTE: no fs.readFileSync here — the msixbundle can exceed Node's 2GiB
+ // buffer limit (ERR_FS_FILE_TOO_LARGE). r2-release.mjs put reads + hashes
+ // the file itself; log the size via stat instead.
+ const { size } = fs.statSync(file)
+ console.log(`[stage-msixbundle] upload ${key} (${size} bytes)`)
+ // Feed-dir keys are FULL object keys (releases/win32/<ch>/…) — pass
+ // --key-is-full so r2 put does NOT wrap them under releases/tag/<tag>/.
+ // r2-release.mjs put derives Content-Type from the key extension.
+ execFileSync(process.execPath, ['scripts/r2-release.mjs', 'put', '--tag', tag, '--key', key, '--file', file, ...(keyIsFull ? ['--key-is-full'] : [])], {
+ cwd: REPO_ROOT,
+ stdio: 'inherit'
+ })
+}
+
+// Feed dir manifests (the install + update source). Content-Types matter:
+// .appinstaller / .msixbundle must reach the OS App Installer, not download.
+upload(`${channelDir}/${appinstallerName}`, path.join(releaseDir, appinstallerName), true)
+upload(`${channelDir}/${name}-${version}-win.msixbundle`, bundle, true)
+
+// The Store-submission .msix files were already uploaded to the tag archive
+// by the win legs (Store- prefix); nothing for this job to re-upload.
+console.log('[stage-msixbundle] done — feed manifests + bundle staged')
diff --git a/scripts/write_install_stamp.py b/scripts/write_install_stamp.py
new file mode 100644
index 00000000000..1e6e2cd9fba
--- /dev/null
+++ b/scripts/write_install_stamp.py
@@ -0,0 +1,333 @@
+"""Generate canonical install-stamp.json for packaged Hermes builds.
+
+All packagers (Docker, Nix, desktop) call this script to produce the same
+``install-stamp.json`` file. Runtime surfaces (CLI, TUI, desktop) read the
+stamp through ``hermes_cli.version_info`` — no env vars, no separate
+docker/nix code paths.
+
+Usage::
+
+ # From a repo root with .git available (dev/CI builds):
+ python scripts/write_install_stamp.py --output /path/to/install-stamp.json
+
+ # Override provenance for reproducible/packaged builds:
+ python scripts/write_install_stamp.py --output ... \\
+ --commit <sha> --branch <name> --dirty \\
+ --base-version 0.19.0 --distance 42 --source nix --distribution nix
+
+ # Docker (no .git, commit known from CI):
+ python scripts/write_install_stamp.py --output install-stamp.json \\
+ --source ci --distribution docker
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import re
+import subprocess
+import sys
+from datetime import datetime, timezone
+from pathlib import Path
+
+# Bootstrap the repo root onto sys.path so the nightly tag shape can come
+# from hermes_cli.update_channel — the single authority — instead of a
+# re-typed regex (hermes_cli/__init__.py is import-light).
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
+
+from hermes_cli import update_channel # noqa: E402
+
+STAMP_SCHEMA_VERSION = 2
+_REPO_ROOT = Path(__file__).parent.parent.resolve()
+
+# Who applies the next update to the tree this stamp describes. REQUIRED —
+# stamp readers hard-fail a stamp without it.
+# self — `hermes update` owns the tree (installer-created
+# source checkouts).
+# electron-updater — the in-app updater replaces the artifact (NSIS,
+# mac .app, AppImage).
+# external — something else replaces the artifact wholesale
+# (nix, docker, MSIX / app stores).
+UPDATE_MECHANISMS = ("self", "electron-updater", "external")
+
+# Hermes's historical tags use a four-digit calendar year as their major
+# component (for example v2026.7.20). Restrict release majors to three digits
+# so these date tags cannot masquerade as the v0.x.y SemVer boundaries.
+_SEMVER_TAG_RE = re.compile(r"^v(0|[1-9]\d{0,2})\.(\d+)\.(\d+)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$")
+_LEGACY_CALVER_TAG_RE = re.compile(r"^v20\d{2}\.\d+\.\d+(?:\.\d+)?$")
+
+FALLBACK_COMMIT = "0" * 40
+
+
+def _run_git(*args: str, cwd: str | Path = _REPO_ROOT) -> str | None:
+ try:
+ result = subprocess.run(
+ ["git", *args], capture_output=True, text=True, timeout=5, cwd=str(cwd)
+ )
+ except (OSError, subprocess.SubprocessError):
+ return None
+ value = (result.stdout or "").strip()
+ return value if result.returncode == 0 and value else None
+
+
+def _parse_release_metadata() -> tuple[str | None, str | None]:
+ """Read __version__ and __release_date__ from hermes_cli/__init__.py."""
+ try:
+ text = (_REPO_ROOT / "hermes_cli" / "__init__.py").read_text(encoding="utf-8-sig")
+ except OSError:
+ return None, None
+ version = re.search(r'__version__\s*=\s*["\']([^"\']+)["\']', text)
+ date = re.search(r'__release_date__\s*=\s*["\']([^"\']+)["\']', text)
+ return (version.group(1) if version else None, date.group(1) if date else None)
+
+
+def _resolve_commit_from_env() -> str | None:
+ """CI builds pass the commit via $GITHUB_SHA."""
+ return os.environ.get("GITHUB_SHA") or None
+
+
+def _resolve_commit_from_git() -> str | None:
+ return _run_git("rev-parse", "HEAD")
+
+
+def _resolve_branch_from_env() -> str | None:
+ return os.environ.get("GITHUB_REF_NAME") or os.environ.get("GITHUB_HEAD_REF") or None
+
+
+def _resolve_branch_from_git() -> str | None:
+ branch = _run_git("rev-parse", "--abbrev-ref", "HEAD")
+ return branch if branch and branch != "HEAD" else None
+
+
+def _resolve_commit_date_from_git() -> int | None:
+ """Return the commit timestamp (Unix epoch seconds) of HEAD, or None."""
+ raw = _run_git("log", "-1", "--format=%ct", "HEAD")
+ if raw and raw.isdigit():
+ return int(raw)
+ return None
+
+
+def _resolve_dirty_from_git() -> bool:
+ status = _run_git("status", "--porcelain", "-uno")
+ return status is not None and len(status) > 0
+
+
+def _compute_distance(base_version: str | None, release_date: str | None) -> int | None:
+ """Count commits since the release tag, trying SemVer then CalVer fallback."""
+ if not base_version:
+ return None
+
+ # Try SemVer tag first, then legacy CalVer tag.
+ for tag in (f"v{base_version}", f"v{release_date}" if release_date else None):
+ if not tag:
+ continue
+ raw = _run_git("rev-list", "--count", f"{tag}..HEAD")
+ if raw is None:
+ continue
+ try:
+ count = int(raw)
+ except ValueError:
+ continue
+ if count >= 0:
+ return count
+ return None
+
+
+def build_stamp(
+ *,
+ update_mechanism: str,
+ commit: str | None = None,
+ branch: str | None = None,
+ dirty: bool | None = None,
+ base_version: str | None = None,
+ distance: int | None = None,
+ commit_date: int | None = None,
+ source: str = "local",
+ distribution: str | None = None,
+ runtime_dir: str | None = None,
+) -> dict:
+ """Build a stamp dict from explicit args, filling gaps from git/env.
+
+ Args override detection — an explicit ``commit`` is used directly.
+ ``source`` identifies where the stamp came from (``ci``, ``local``,
+ ``docker``, ``nix``, ``fallback``). ``update_mechanism`` is required:
+ every stamp names who applies the next update (see UPDATE_MECHANISMS).
+
+ ``runtime_dir`` is a path RELATIVE to the stamp file's directory, naming
+ where the pm store (the managed tool bytes) lives. A sealed desktop-app
+ payload stages its runtime dir as a sibling of ``repo/`` (the install
+ root), so the value is ``..``. The Python boot path reads this instead
+ of deriving ``<install_root>/.hermes-runtime``, which is wrong for that
+ layout: the runtime dir is the payload dir, not a child of the install
+ root. ``..`` keeps it relocatable — an absolute path would break under
+ MSIX translocation.
+ """
+ if update_mechanism not in UPDATE_MECHANISMS:
+ raise SystemExit(
+ f"write_install_stamp: invalid --update-mechanism {update_mechanism!r} "
+ f"(expected one of {', '.join(UPDATE_MECHANISMS)})"
+ )
+ _base_version, _release_date = _parse_release_metadata()
+ if base_version is None:
+ base_version = _base_version
+
+ # Commit: explicit > CI env > git
+ if commit is None:
+ commit = _resolve_commit_from_env()
+ source = "ci" if commit else source
+ if commit is None:
+ commit = _resolve_commit_from_git()
+ source = "local" if commit else source
+ if not commit:
+ commit = FALLBACK_COMMIT
+ source = "fallback"
+
+ # Branch: explicit > CI env > git
+ if branch is None:
+ branch = _resolve_branch_from_env()
+ if branch is None:
+ branch = _resolve_branch_from_git()
+
+ # Dirty: explicit > git
+ if dirty is None:
+ dirty = _resolve_dirty_from_git()
+
+ # Distance: explicit > computed from git
+ if distance is None:
+ distance = _compute_distance(base_version, _release_date)
+
+ # Commit date: explicit > git
+ if commit_date is None:
+ commit_date = _resolve_commit_date_from_git()
+
+ # Display version
+ display_version = base_version or ""
+ if distance is not None and distance > 0:
+ display_version = f"{display_version}+{distance}"
+ elif dirty and distance is None:
+ display_version = f"{display_version}+?"
+
+ # The desktop artifact kind, from the one build-time selector
+ # HERMES_DESKTOP_VARIANT. Every stamp carries it:
+ # bootstrap — no runtime in the artifact; first launch bootstraps a
+ # local install. The default (variable unset/empty; also
+ # the value for non-desktop stamps, where it is inert).
+ # bundled — the agent runtime ships inside the artifact resources.
+ # light — NO runtime at all, remote connections only. A Python
+ # process must never read a light stamp: the artifact
+ # contains no Python (the stamp readers raise on it).
+ # store — a Store-submission build: the SAME bundled payload, but a
+ # different MSIX packaging identity. Stamps as 'bundled'
+ # so the bundled shape logic (shared userData, steward-
+ # owned updates, no in-app updater) holds for it too.
+ # bundled, light and store all pin a release tag: electron-updater keys on
+ # it, so a tagless artifact of either kind cannot update itself.
+ variant = os.environ.get("HERMES_DESKTOP_VARIANT", "").strip()
+ if variant not in ("", "bootstrap", "bundled", "light", "store"):
+ raise SystemExit(
+ f"write_install_stamp: unknown HERMES_DESKTOP_VARIANT {variant!r} "
+ "(expected unset, 'bootstrap', 'bundled', 'light', or 'store')"
+ )
+ payload = "bundled" if variant == "store" else (variant or "bootstrap")
+ tag = os.environ.get("HERMES_PAYLOAD_TAG") or None
+ # Stable (vX.Y.Z) and nightly (vX.Y.<any patch>-nightly.<YYYYMMDDHHMMSS>,
+ # or the legacy date-only shape) tags are both release-feed keys; anything
+ # else cannot update itself and refuses. The nightly shape is validated by
+ # hermes_cli.update_channel — the single authority — so it accepts the
+ # patch+1 form scripts/release.py's nightly_tag_for_date produces.
+ _stable_tag = re.compile(r"^v(0|[1-9]\d{0,2})\.\d+\.\d+$")
+ if payload != "bootstrap" and not (
+ tag and (_stable_tag.match(tag) or update_channel.is_nightly_tag(tag))
+ ):
+ raise SystemExit(
+ f"write_install_stamp: HERMES_DESKTOP_VARIANT={payload} requires "
+ f"HERMES_PAYLOAD_TAG=vX.Y.Z or vX.Y.<n>-nightly.YYYYMMDDHHMMSS (got {tag!r})"
+ )
+
+ stamp = {
+ "schemaVersion": STAMP_SCHEMA_VERSION,
+ "commit": commit,
+ "commitDate": commit_date,
+ "branch": branch,
+ "builtAt": datetime.now(timezone.utc).isoformat(),
+ "dirty": dirty,
+ "source": source,
+ "distribution": distribution,
+ "updateMechanism": update_mechanism,
+ "baseVersion": base_version,
+ "displayVersion": display_version,
+ "distance": distance,
+ "payload": payload,
+ "tag": tag if payload != "bootstrap" else None,
+ }
+ if runtime_dir is not None:
+ stamp["runtimeDir"] = runtime_dir
+ return stamp
+
+
+def write_stamp(output: str | Path, **kwargs) -> dict:
+ """Build and write an install-stamp.json to ``output``. Returns the stamp."""
+ stamp = build_stamp(**kwargs)
+ out_path = Path(output)
+ out_path.parent.mkdir(parents=True, exist_ok=True)
+ out_path.write_text(json.dumps(stamp, indent=2) + "\n", encoding="utf-8")
+ return stamp
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description="Write install-stamp.json")
+ parser.add_argument("--output", "-o", required=True, help="Output file path")
+ parser.add_argument("--commit", default=None, help="Override commit SHA")
+ parser.add_argument("--branch", default=None, help="Override branch name")
+ parser.add_argument("--dirty", action="store_true", default=None, help="Mark as dirty")
+ parser.add_argument("--base-version", default=None, help="Override base version")
+ parser.add_argument("--distance", type=int, default=None, help="Override commit distance")
+ parser.add_argument("--commit-date", type=int, default=None, help="Override commit timestamp (Unix epoch seconds)")
+ parser.add_argument("--source", default="local", help="Stamp source label")
+ parser.add_argument(
+ "--distribution",
+ choices=("docker", "nix", "desktop-app"),
+ help="Package distribution (the steward that replaces this tree)",
+ )
+ parser.add_argument(
+ "--update-mechanism",
+ required=True,
+ choices=UPDATE_MECHANISMS,
+ help="Who applies the next update: 'self' (hermes update), "
+ "'electron-updater' (in-app updater), 'external' (nix/docker/store)",
+ )
+ parser.add_argument(
+ "--runtime-dir",
+ default=None,
+ help="Path RELATIVE to the stamp file's directory, naming where the "
+ "pm store (the managed tool bytes) lives. A sealed desktop-app "
+ "payload passes '..' (the payload dir is the install root's "
+ "parent). Omitted for source/docker/nix stamps.",
+ )
+ args = parser.parse_args()
+
+ stamp = write_stamp(
+ args.output,
+ update_mechanism=args.update_mechanism,
+ commit=args.commit,
+ branch=args.branch,
+ dirty=args.dirty,
+ base_version=args.base_version,
+ distance=args.distance,
+ commit_date=args.commit_date,
+ source=args.source,
+ distribution=args.distribution,
+ runtime_dir=args.runtime_dir,
+ )
+
+ commit_short = stamp["commit"][:12]
+ branch_str = f" ({stamp['branch']})" if stamp["branch"] else ""
+ dirty_str = " [DIRTY]" if stamp["dirty"] else ""
+ fallback_str = " [FALLBACK]" if stamp["source"] == "fallback" else ""
+ print(f"[write_install_stamp] wrote {args.output} -> {commit_short}{branch_str}{dirty_str}{fallback_str}")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tests-js/desktop-mac-usage-descriptions.test.ts b/tests-js/desktop-mac-usage-descriptions.test.ts
index c4fe21a100a..e94a6c0fbf6 100644
--- a/tests-js/desktop-mac-usage-descriptions.test.ts
+++ b/tests-js/desktop-mac-usage-descriptions.test.ts
@@ -54,7 +54,13 @@ import path from 'node:path'
import { test } from 'vitest'
const REPO_ROOT = path.resolve(__dirname, '..')
-const DESKTOP_PKG = path.join(REPO_ROOT, 'apps', 'desktop', 'package.json')
+const DESKTOP_DIR = path.join(REPO_ROOT, 'apps', 'desktop')
+// The desktop build config lives in electron-builder.config.cjs — the repo
+// deliberately keeps package.json free of a `build` field (see the config
+// header: "run-electron-builder.mjs always passes --config, so a stray
+// package.json field would be silently ignored"). extendInfo is read from
+// that file, exactly what electron-builder consumes.
+const DESKTOP_CONFIG = path.join(DESKTOP_DIR, 'electron-builder.config.cjs')
interface UsageDescriptionRow {
key: string
@@ -62,21 +68,22 @@ interface UsageDescriptionRow {
reason: string
}
-function desktopPkg(): Record<string, unknown> {
- assert.ok(fs.existsSync(DESKTOP_PKG), `missing ${DESKTOP_PKG}`)
+function desktopConfig(): Record<string, unknown> {
+ assert.ok(fs.existsSync(DESKTOP_CONFIG), `missing ${DESKTOP_CONFIG}`)
- return JSON.parse(fs.readFileSync(DESKTOP_PKG, 'utf-8'))
+ // The config is a .cjs module (CommonJS); require it like the builder does.
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
+ return require(DESKTOP_CONFIG) as Record<string, unknown>
}
function extendInfo(): Record<string, string> {
- const pkg = desktopPkg()
- const build = (pkg.build ?? {}) as Record<string, unknown>
- const mac = (build.mac ?? {}) as Record<string, unknown>
+ const config = desktopConfig()
+ const mac = (config.mac ?? {}) as Record<string, unknown>
assert.ok(
typeof mac.extendInfo === 'object' &&
mac.extendInfo !== null &&
!Array.isArray(mac.extendInfo),
- 'build.mac.extendInfo is missing or invalid in apps/desktop/package.json'
+ 'build.mac.extendInfo is missing or invalid in electron-builder.config.cjs'
)
const extend = mac.extendInfo as Record<string, unknown>
@@ -84,8 +91,13 @@ function extendInfo(): Record<string, string> {
// for NS*UsageDescription is string, but electron-builder's `extendInfo`
// accepts arbitrary plist scalars (bool, number, array, object) and we want
// a clean assertion error here, not a downstream `value.trim is not a
- // function` crash in the whitespace test.
+ // function` crash in the whitespace test. Only the privacy usage keys must
+ // be strings; other plist scalars (LSRequiresNativeExecution, etc.) are
+ // legitimate booleans/numbers.
for (const [key, value] of Object.entries(extend)) {
+ if (!key.startsWith('NS') || !key.endsWith('UsageDescription')) {
+ continue
+ }
assert.equal(
typeof value,
'string',
@@ -167,7 +179,7 @@ test.each(EXPECTED_USAGE_DESCRIPTIONS)(
assert.ok(
value !== undefined,
`Info.plist privacy usage description \`${key}\` is missing from ` +
- 'apps/desktop/package.json build.mac.extendInfo. macOS will surface ' +
+ 'electron-builder.config.cjs mac.extendInfo. macOS will surface ' +
'a misleading system prompt or silently deny the related API.\n' +
`Reason: ${reason}`
)
@@ -184,6 +196,11 @@ test('every extendInfo value is free of leading/trailing whitespace and newlines
const info = extendInfo()
for (const [key, value] of Object.entries(info)) {
+ // Only string values carry whitespace concerns; plist scalars
+ // (booleans/numbers like LSRequiresNativeExecution) are exempt.
+ if (typeof value !== 'string') {
+ continue
+ }
assert.equal(
value,
value.trim(),
diff --git a/tests-js/r2-release.test.mjs b/tests-js/r2-release.test.mjs
new file mode 100644
index 00000000000..69fbd74f4ca
--- /dev/null
+++ b/tests-js/r2-release.test.mjs
@@ -0,0 +1,273 @@
+/**
+ * scripts/r2-release.mjs — SigV4 signer pinned against AWS botocore (the
+ * reference implementation, 1.43.81) at a FIXED timestamp/creds, so the
+ * expected values are reproducible fixtures rather than self-consistency.
+ *
+ * Vectors were generated with the venv script at
+ * sigv4-venv/gen_vectors.py (botocore.auth.SigV4Auth / S3SigV4Auth,
+ * timestamp 20150830T123600Z, creds AKIDEXAMPLE):
+ * - get-vanilla generic signer (no x-amz-content-sha256), example.com
+ * - r2-put-payload S3 signer, payload hash signed, region auto
+ * - r2-list S3 signer, ListObjectsV2 with query params
+ * - r2-delete S3 signer, region auto
+ * The get-vanilla case also reproduces the public aws-sig-v4-test-suite
+ * request shape (verified by independent spec computation).
+ */
+
+import assert from 'node:assert/strict'
+
+import { test } from 'vitest'
+
+import {
+ authHeader,
+ canonicalQuery,
+ canonicalRequest,
+ channelForTag,
+ contentTypeFor,
+ encodeKeyPath,
+ feedDirFor,
+ mergeFeedYmls,
+ nightlyDoomedKeys,
+ rewriteFeedPaths,
+ stagingKeyFor,
+ parseListXml,
+ rfc3986Encode,
+} from '../scripts/r2-release.mjs'
+
+const AKID = 'AKIDEXAMPLE'
+const SECRET = 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY'
+const NOW = '20150830T123600Z'
+const EMPTY_SHA = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
+
+test('get-vanilla matches the AWS test-suite vector', () => {
+ const authz = authHeader({
+ method: 'GET',
+ host: 'example.com',
+ path: '/',
+ query: '',
+ headers: { host: 'example.com', 'x-amz-date': NOW },
+ payloadHash: EMPTY_SHA,
+ accessKeyId: AKID,
+ secretKey: SECRET,
+ now: NOW,
+ region: 'us-east-1',
+ service: 'service',
+ })
+ assert.equal(
+ authz,
+ 'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20150830/us-east-1/service/aws4_request, ' +
+ 'SignedHeaders=host;x-amz-date, ' +
+ 'Signature=33399fd3d4a9d6104710c7c04005f7c959f8b1f8bf41b823587ed36b079e453f',
+ )
+})
+
+test('r2-put-payload matches botocore (S3 signer, payload hash, region auto)', () => {
+ const bodyHash = '44ce7dd67c959e0d3524ffac1771dfbba87d2b6b4b4e99e42034a8b803f8b072' // sha256("Welcome to Amazon S3.")
+ const host = 'abc123.r2.cloudflarestorage.com'
+ const authz = authHeader({
+ method: 'PUT',
+ host,
+ path: '/hermes-releases/HermesBundled-0.28.0-win-x64.msix',
+ query: '',
+ headers: { host, 'x-amz-date': NOW, 'x-amz-content-sha256': bodyHash },
+ payloadHash: bodyHash,
+ accessKeyId: AKID,
+ secretKey: SECRET,
+ now: NOW,
+ })
+ assert.equal(
+ authz,
+ 'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20150830/auto/s3/aws4_request, ' +
+ 'SignedHeaders=host;x-amz-content-sha256;x-amz-date, ' +
+ 'Signature=05ba50acfb54042fac330848af50877e5fb477c4f2063c2f77f9cc80855eb1e9',
+ )
+})
+
+test('r2-list matches botocore (canonical query sorted, empty payload hash)', () => {
+ const query = canonicalQuery({ 'list-type': '2', prefix: 'HermesBundled-0.28.0-', 'max-keys': '1000' })
+ assert.equal(query, 'list-type=2&max-keys=1000&prefix=HermesBundled-0.28.0-')
+ const host = 'abc123.r2.cloudflarestorage.com'
+ const authz = authHeader({
+ method: 'GET',
+ host,
+ path: '/hermes-releases',
+ query,
+ headers: { host, 'x-amz-date': NOW, 'x-amz-content-sha256': EMPTY_SHA },
+ payloadHash: EMPTY_SHA,
+ accessKeyId: AKID,
+ secretKey: SECRET,
+ now: NOW,
+ })
+ assert.equal(
+ authz,
+ 'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20150830/auto/s3/aws4_request, ' +
+ 'SignedHeaders=host;x-amz-content-sha256;x-amz-date, ' +
+ 'Signature=3ec423c452a318664c85fbcc25667ad07201aedce688e3bb6b345b4baaa39d90',
+ )
+})
+
+test('r2-delete matches botocore', () => {
+ const host = 'abc123.r2.cloudflarestorage.com'
+ const authz = authHeader({
+ method: 'DELETE',
+ host,
+ path: '/hermes-releases/HermesBundled-0.28.0-nightly.20260818-win-arm64.msix',
+ query: '',
+ headers: { host, 'x-amz-date': NOW, 'x-amz-content-sha256': EMPTY_SHA },
+ payloadHash: EMPTY_SHA,
+ accessKeyId: AKID,
+ secretKey: SECRET,
+ now: NOW,
+ })
+ assert.equal(
+ authz,
+ 'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20150830/auto/s3/aws4_request, ' +
+ 'SignedHeaders=host;x-amz-content-sha256;x-amz-date, ' +
+ 'Signature=42051e3d24b20ff352dc6f4ff11323ace9ca20bceb46f830398768e51ae20526',
+ )
+})
+
+test('rfc3986Encode escapes the AWS reserved set, keeps unreserved', () => {
+ assert.equal(rfc3986Encode('HermesBundled-0.28.0-win-x64.msix'), 'HermesBundled-0.28.0-win-x64.msix')
+ assert.equal(rfc3986Encode("a b!'()*c"), 'a%20b%21%27%28%29%2Ac')
+})
+
+test('encodeKeyPath encodes segment-wise, preserves separators', () => {
+ assert.equal(encodeKeyPath('HermesBundled-0.28.0-win-x64.msix'), 'HermesBundled-0.28.0-win-x64.msix')
+ assert.equal(encodeKeyPath('a b/c d'), 'a%20b/c%20d')
+})
+
+test('parseListXml extracts keys, truncation, continuation token, entities', () => {
+ const xml = `<?xml version="1.0" encoding="UTF-8"?>
+<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
+ <Name>hermes-releases</Name>
+ <Prefix></Prefix>
+ <KeyCount>3</KeyCount>
+ <MaxKeys>1000</MaxKeys>
+ <IsTruncated>true</IsTruncated>
+ <Contents><Key>HermesBundled-0.28.0-win-x64.msix</Key><LastModified>2026-08-18T00:00:00Z</LastModified><Size>123</Size></Contents>
+ <Contents><Key>a&amp;b.msix</Key><LastModified>2026-08-18T00:00:00Z</LastModified><Size>1</Size></Contents>
+ <Contents><Key>latest.yml</Key><LastModified>2026-08-18T00:00:00Z</LastModified><Size>2</Size></Contents>
+ <NextContinuationToken>abc+def/=</NextContinuationToken>
+</ListBucketResult>`
+ const parsed = parseListXml(xml)
+ assert.deepEqual(parsed.keys, ['HermesBundled-0.28.0-win-x64.msix', 'a&b.msix', 'latest.yml'])
+ assert.equal(parsed.truncated, true)
+ assert.equal(parsed.nextToken, 'abc+def/=')
+})
+
+test('nightlyDoomedKeys dates by the key suffix, ignores stable artifacts', () => {
+ const keys = [
+ 'releases/tag/v0.28.0/HermesBundled-0.28.0-win-x64.msix', // stable — never doomed
+ 'releases/tag/v0.28.0-nightly.20260801/HermesBundled-0.28.0-nightly.20260801-win-x64.msix',
+ 'releases/tag/v0.28.0-nightly.20260818/HermesBundled-0.28.0-nightly.20260818-win-x64.msix', // today — kept
+ 'releases/tag/v0.28.0-nightly.20260801/HermesBundled-0.28.0-nightly.20260801-win-x64.msix.blockmap',
+ 'latest.yml',
+ 'nightly.yml',
+ ]
+ assert.deepEqual(nightlyDoomedKeys(keys, '20260814'), [
+ 'releases/tag/v0.28.0-nightly.20260801/HermesBundled-0.28.0-nightly.20260801-win-x64.msix',
+ 'releases/tag/v0.28.0-nightly.20260801/HermesBundled-0.28.0-nightly.20260801-win-x64.msix.blockmap',
+ ])
+})
+
+test('channelForTag maps stable vs nightly', () => {
+ assert.equal(channelForTag('v0.28.0'), 'stable')
+ assert.equal(channelForTag('v0.28.0-nightly.20260818101010'), 'nightly')
+ assert.equal(channelForTag('v0.28.0-nightly.20260818'), 'nightly')
+})
+
+test('stagingKeyFor + feedDirFor produce the layout keys', () => {
+ assert.equal(stagingKeyFor('v0.28.0', 'HermesBundled-0.28.0-win-x64.msix'),
+ 'releases/tag/v0.28.0/HermesBundled-0.28.0-win-x64.msix')
+ assert.equal(feedDirFor('win32', 'stable'), 'releases/win32/stable')
+ assert.equal(feedDirFor('darwin', 'nightly'), 'releases/darwin/nightly')
+})
+
+test('contentTypeFor maps MSIX / App Installer artifacts to their MIME types', () => {
+ assert.equal(contentTypeFor('HermesBundled-0.28.0-win-x64.msix'), 'application/msix')
+ assert.equal(contentTypeFor('HermesBundled-0.28.0-win.msixbundle'), 'application/msixbundle')
+ assert.equal(contentTypeFor('stable.appinstaller'), 'application/appinstaller')
+ assert.equal(contentTypeFor('HermesBundled-0.28.0-mac-x64.dmg'), undefined)
+ assert.equal(contentTypeFor('latest-mac.yml'), undefined)
+ // Case-insensitive on the suffix.
+ assert.equal(contentTypeFor('X.APPINSTALLER'), 'application/appinstaller')
+})
+
+test('canonicalRequest reads mixed-case header values (Content-Type)', () => {
+ // Regression: canonicalRequest lowercased the header NAME for the canonical
+ // line but read the value with `headers[lowerName]` — a 'Content-Type'
+ // value came out as 'undefined' while R2 canonicalized 'application/msix',
+ // so every signed msix PUT (the only artifact with Content-Type) failed
+ // with SignatureDoesNotMatch / 403. Value lookup must be case-insensitive.
+ const host = 'abc123.r2.cloudflarestorage.com'
+ const now = '20150830T123600Z'
+ const bodyHash = '44ce7dd67c959e0d3524ffac1771dfbba87d2b6b4b4e99e42034a8b803f8b072'
+ const headers = {
+ host,
+ 'x-amz-date': now,
+ 'x-amz-content-sha256': bodyHash,
+ 'Content-Type': 'application/msix'
+ }
+ const canon = canonicalRequest('PUT', '/hermes-releases/HermesBundled-0.28.0-win-x64.msix', '', headers, bodyHash)
+ assert.ok(canon.includes('content-type:application/msix'), 'content-type value must survive canonicalization')
+ assert.ok(!canon.includes('undefined'), 'no undefined values leaked into the canonical request')
+ // The canonical line ordering + header list match what SigV4/R2 recompute.
+ assert.ok(canon.includes('content-type;host;x-amz-content-sha256;x-amz-date'))
+})
+
+test('rewriteFeedPaths rewrites path:/url: to absolute /releases/tag keys, idempotent', () => {
+ const absKey = (f) => `/releases/tag/v0.28.0/${f}`
+ const yml = `version: 0.28.0
+files:
+ - url: HermesBundled-0.28.0-mac-x64.zip
+ sha512: abc
+ size: 1
+ - url: HermesBundled-0.28.0-mac-x64.dmg
+ sha512: def
+ size: 2
+path: HermesBundled-0.28.0-mac-x64.zip
+sha512: ghi
+releaseDate: '2026-08-18T00:00:00.000Z'
+`
+ const once = rewriteFeedPaths(yml, absKey)
+ assert.ok(once.includes('url: /releases/tag/v0.28.0/HermesBundled-0.28.0-mac-x64.zip'))
+ assert.ok(once.includes('url: /releases/tag/v0.28.0/HermesBundled-0.28.0-mac-x64.dmg'))
+ assert.ok(once.includes('path: /releases/tag/v0.28.0/HermesBundled-0.28.0-mac-x64.zip'))
+ assert.ok(once.includes('sha512: abc')) // artifact hashes untouched
+ // Already-absolute values are left alone (a re-finalize must not double-prefix).
+ assert.equal(rewriteFeedPaths(once, absKey), once)
+})
+
+test('mergeFeedYmls concatenates files[] lists, dedupes, keeps head', () => {
+ const x64 = `version: 0.28.0
+files:
+ - url: HermesBundled-0.28.0-mac-x64.zip
+ sha512: abc
+ size: 1
+ - url: HermesBundled-0.28.0-mac-x64.dmg
+ sha512: def
+ size: 2
+path: HermesBundled-0.28.0-mac-x64.zip
+sha512: ghi
+releaseDate: '2026-08-18T00:00:00.000Z'
+`
+ const arm64 = `version: 0.28.0
+files:
+ - url: HermesBundled-0.28.0-mac-arm64.zip
+ sha512: jkl
+ size: 3
+ - url: HermesBundled-0.28.0-mac-arm64.dmg
+ sha512: mno
+ size: 4
+path: HermesBundled-0.28.0-mac-arm64.zip
+sha512: pqr
+releaseDate: '2026-08-18T00:00:00.000Z'
+`
+ const merged = mergeFeedYmls([x64, arm64])
+ assert.ok(merged.includes('url: HermesBundled-0.28.0-mac-x64.zip'))
+ assert.ok(merged.includes('url: HermesBundled-0.28.0-mac-arm64.zip'))
+ assert.ok(merged.includes('releaseDate'))
+ // Idempotent: merging the merged output adds nothing new.
+ assert.equal(mergeFeedYmls([merged, arm64]), merged)
+})
diff --git a/tests-js/vitest.config.ts b/tests-js/vitest.config.ts
index 5d654e7e30d..ffc666f654e 100644
--- a/tests-js/vitest.config.ts
+++ b/tests-js/vitest.config.ts
@@ -3,6 +3,6 @@ import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
environment: 'node',
- include: ['**/*.test.ts'],
+ include: ['**/*.test.ts', '**/*.test.mjs'],
},
})
diff --git a/tests/docker/test_dump_build_sha.py b/tests/docker/test_dump_build_sha.py
index 20e6da19c06..56a2dbaea75 100644
--- a/tests/docker/test_dump_build_sha.py
+++ b/tests/docker/test_dump_build_sha.py
@@ -1,33 +1,34 @@
"""Regression test: ``hermes dump`` reports a real git SHA inside the container.
-Background: ``.dockerignore`` excludes ``.git``, so ``git rev-parse HEAD``
-fails inside the published image and ``hermes dump`` used to report
-``version: ... [(unknown)]``. The Dockerfile now writes the build-time
-``$HERMES_GIT_SHA`` build-arg to ``/opt/hermes/.hermes_build_sha`` and
-``hermes_cli/build_info.py`` reads it as a fallback.
-
-CI (``.github/workflows/docker.yml``) always sets the build-arg
-to ``${{ github.sha }}``. Local ``docker build`` (the ``built_image``
-fixture in ``tests/docker/conftest.py``) does NOT — so locally the file
-is absent and ``hermes dump`` correctly falls back to ``(unknown)``.
-
-This test handles both cases:
-
-* If ``/opt/hermes/.hermes_build_sha`` exists in the image, assert that
- ``hermes dump`` surfaces its content as the version SHA (not
- ``(unknown)``).
-* If the file is absent, assert the legacy behaviour (``(unknown)``)
- still holds — defensive guard against the helper accidentally
- reporting bogus data from somewhere else.
+``.dockerignore`` excludes ``.git``, so ``git rev-parse HEAD`` fails inside
+the published image. CI writes ``install-stamp.json`` before ``docker build``
+(scripts/write_install_stamp.py) and it is COPY'd to the canonical
+``/opt/hermes/install-stamp.json``. ``hermes dump`` reads the
+commit from that stamp through ``hermes_cli.version_info``.
+
+A local ``docker build`` (the ``built_image`` fixture in
+``tests/docker/conftest.py``) has no CI stamp — only the Dockerfile's
+distribution-only fallback, whose all-zero commit version_info skips. In
+that case ``hermes dump`` falls back to ``(unknown)``.
+
+This test asserts both cases:
+
+* When the stamp exists in the image, ``hermes dump`` must show the first 8
+ characters of its commit, not ``(unknown)``.
+* When the stamp is absent, ``hermes dump`` must show ``(unknown)`` — a guard
+ against the helper inventing a SHA from another source.
"""
from __future__ import annotations
+import json
import re
import subprocess
_VERSION_LINE = re.compile(r"^version:\s+(?P<rest>.+)$", re.MULTILINE)
-_SHA_BRACKET = re.compile(r"\[(?P<sha>[^\]]+)\]\s*$")
+# The stamp-first version line is "X.Y.Z [<sha>] (YYYY-MM-DD)" — the sha
+# bracket may be followed by the build-date suffix.
+_SHA_BRACKET = re.compile(r"\[(?P<sha>[^\]]+)\]")
def _run_dump(image: str) -> str:
@@ -50,28 +51,36 @@ def _run_dump(image: str) -> str:
return r.stdout
-def _read_baked_sha_from_image(image: str) -> str | None:
- """Return the ``/opt/hermes/.hermes_build_sha`` content, or None if absent."""
+def _read_stamp_commit_from_image(image: str) -> str | None:
+ """Return the stamp commit from the image, or None when absent/unusable."""
r = subprocess.run(
[
"docker", "run", "--rm", "--entrypoint", "cat", image,
- "/opt/hermes/.hermes_build_sha",
+ "/opt/hermes/install-stamp.json",
],
capture_output=True, text=True, timeout=30,
)
if r.returncode != 0:
return None
- return r.stdout.strip() or None
+ try:
+ commit = json.loads(r.stdout).get("commit") or ""
+ except ValueError:
+ return None
+ # An all-zero commit is the writer's fallback placeholder, and
+ # version_info skips it the same way.
+ if not commit or set(commit) == {"0"}:
+ return None
+ return commit
-def test_dump_reports_baked_sha_when_present(built_image: str) -> None:
- """When the image was built with ``HERMES_GIT_SHA``, dump must surface it.
+def test_dump_reports_stamp_commit_when_present(built_image: str) -> None:
+ """When the image carries an install stamp, dump must surface its commit.
Together with the smoke-test action (which exercises ``--help``), this
closes the regression loop for the missing-sha bug: any future change
- that breaks the baked-file -> dump pipeline will fail CI here.
+ that breaks the stamp -> dump pipeline will fail CI here.
"""
- baked = _read_baked_sha_from_image(built_image)
+ stamped = _read_stamp_commit_from_image(built_image)
stdout = _run_dump(built_image)
match = _VERSION_LINE.search(stdout)
@@ -82,23 +91,20 @@ def test_dump_reports_baked_sha_when_present(built_image: str) -> None:
)
reported = sha_match.group("sha")
- if baked is None:
- # Local-build path: no build-arg was passed. Verify the legacy
- # fallback ``(unknown)`` is intact — guards against the helper
- # ever inventing a SHA from thin air.
+ if stamped is None:
+ # Local-build path: no stamp in the image. The fallback must stay
+ # '(unknown)' — a guard against the helper inventing a SHA.
assert reported == "(unknown)", (
- f"expected '(unknown)' when no SHA baked, got {reported!r}"
+ f"expected '(unknown)' when no stamp is baked, got {reported!r}"
)
return
- # CI path: build-arg was set, baked file exists. ``hermes dump``
- # truncates to 8 chars via ``git rev-parse --short=8`` semantics.
+ # CI path: the stamp exists. ``hermes dump`` shows the first 8 chars.
assert reported != "(unknown)", (
- "baked SHA file present in image but dump still reported "
- f"'(unknown)' — the build-info fallback is broken. "
- f"Baked file content: {baked!r}"
+ "install stamp present in image but dump still reported "
+ f"'(unknown)' — the stamp fallback is broken. Stamp commit: {stamped!r}"
)
- assert reported == baked[:8], (
- f"dump reported {reported!r} but baked file contained {baked!r} "
- f"(expected first 8 chars: {baked[:8]!r})"
+ assert reported == stamped[:8], (
+ f"dump reported {reported!r} but the stamp commit is {stamped!r} "
+ f"(expected first 8 chars: {stamped[:8]!r})"
)
diff --git a/tests/gateway/test_control_socket.py b/tests/gateway/test_control_socket.py
index 7dba7588f36..57412b2105a 100644
--- a/tests/gateway/test_control_socket.py
+++ b/tests/gateway/test_control_socket.py
@@ -276,7 +276,7 @@ def test_collect_fleet_versions_prefers_socket(tmp_path: Path, monkeypatch):
home.mkdir()
monkeypatch.setattr(
- "hermes_cli.build_info.get_code_identity",
+ "hermes_cli.version_info.get_code_identity",
lambda refresh=False: {"sha": "HEADSHA", "version": "1.0"},
)
monkeypatch.setattr(
@@ -311,7 +311,7 @@ def test_collect_fleet_versions_falls_back_to_state_file(tmp_path: Path, monkeyp
home.mkdir()
monkeypatch.setattr(
- "hermes_cli.build_info.get_code_identity",
+ "hermes_cli.version_info.get_code_identity",
lambda refresh=False: {"sha": "HEADSHA", "version": "1.0"},
)
monkeypatch.setattr(
diff --git a/tests/gateway/test_control_socket_windows_live.py b/tests/gateway/test_control_socket_windows_live.py
index 6a5a25ffa01..eccb6a272db 100644
--- a/tests/gateway/test_control_socket_windows_live.py
+++ b/tests/gateway/test_control_socket_windows_live.py
@@ -107,7 +107,7 @@ def test_named_pipe_identify_status_and_fleet_consumer(live_server, monkeypatch)
import hermes_cli.update_receipt as ur
monkeypatch.setattr(
- "hermes_cli.build_info.get_code_identity",
+ "hermes_cli.version_info.get_code_identity",
lambda refresh=False: {"sha": ident.get("code_sha") or "X", "version": "t"},
)
monkeypatch.setattr("hermes_cli.profiles._get_default_hermes_home", lambda: home)
@@ -140,7 +140,7 @@ def test_pipe_gone_after_kill_falls_back(live_server, monkeypatch):
encoding="utf-8",
)
monkeypatch.setattr(
- "hermes_cli.build_info.get_code_identity",
+ "hermes_cli.version_info.get_code_identity",
lambda refresh=False: {"sha": "NEW", "version": "t"},
)
monkeypatch.setattr("hermes_cli.profiles._get_default_hermes_home", lambda: home)
diff --git a/tests/gateway/test_update_command.py b/tests/gateway/test_update_command.py
index 22cc9cd419b..4191bf7aa7e 100644
--- a/tests/gateway/test_update_command.py
+++ b/tests/gateway/test_update_command.py
@@ -122,6 +122,7 @@ class TestHandleUpdateCommand:
with patch("gateway.run._hermes_home", hermes_home), \
patch("gateway.run.__file__", fake_file), \
+ patch("hermes_cli.config.detect_install_method", return_value="git"), \
patch("shutil.which", side_effect=lambda x: "/usr/bin/hermes" if x == "hermes" else "/usr/bin/setsid"), \
patch("subprocess.Popen"):
result = await runner._handle_update_command(event)
@@ -163,6 +164,7 @@ class TestHandleUpdateCommand:
with patch("gateway.run._hermes_home", hermes_home), \
patch("gateway.run.__file__", fake_file), \
+ patch("hermes_cli.config.detect_install_method", return_value="git"), \
patch("shutil.which", side_effect=which_no_setsid), \
patch("subprocess.Popen", mock_popen):
result = await runner._handle_update_command(event)
@@ -539,3 +541,34 @@ class TestWatchUpdateProgress:
assert "continued after" in sent
assert "Hermes update finished" in sent
assert not (hermes_home / ".update_pending.json").exists()
+# ---------------------------------------------------------------------------
+# Install-method refusal gate
+# ---------------------------------------------------------------------------
+
+
+class TestUpdateCommandInstallMethodRefusal:
+ """/update on a non-git install refuses with the steward's own update
+ command instead of attempting a git-based `hermes update`."""
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("method", ["docker", "nix"])
+ async def test_refuses_non_git_install(self, tmp_path, method):
+ runner = _make_runner()
+ event = _make_event()
+ hermes_home = tmp_path / "hermes"
+ hermes_home.mkdir()
+ mock_popen = MagicMock()
+
+ with patch("gateway.run._hermes_home", hermes_home), \
+ patch("hermes_cli.config.detect_install_method",
+ return_value=method), \
+ patch("hermes_cli.config.recommended_update_command_for_method",
+ return_value=f"steward-update --{method}"), \
+ patch("subprocess.Popen", mock_popen):
+ result = await runner._handle_update_command(event)
+
+ assert f"does not apply to this install ({method})" in result
+ assert f"Update with: steward-update --{method}" in result
+ # No update attempt: nothing spawned, no pending marker written.
+ mock_popen.assert_not_called()
+ assert not (hermes_home / ".update_pending.json").exists()
diff --git a/tests/gateway/test_whatsapp_connect.py b/tests/gateway/test_whatsapp_connect.py
index 8ce6687b81f..f0ee7603509 100644
--- a/tests/gateway/test_whatsapp_connect.py
+++ b/tests/gateway/test_whatsapp_connect.py
@@ -15,7 +15,7 @@ Regression tests for two bugs in WhatsAppAdapter.connect():
import asyncio
import signal
from pathlib import Path
-from unittest.mock import AsyncMock, MagicMock, patch
+from unittest.mock import AsyncMock, MagicMock, call, patch
import pytest
@@ -405,14 +405,20 @@ class TestHttpSessionLifecycle:
patch("plugins.platforms.whatsapp.adapter.asyncio.sleep", new_callable=AsyncMock):
await adapter.disconnect()
- mock_run.assert_called_once_with(
- ["taskkill", "/PID", "12345", "/T"],
- capture_output=True,
- text=True,
- encoding="utf-8",
- errors="replace",
- timeout=10,
- )
+ taskkill_calls = [
+ c for c in mock_run.call_args_list
+ if c.args and c.args[0] and c.args[0][0] == "taskkill"
+ ]
+ assert taskkill_calls == [
+ call(
+ ["taskkill", "/PID", "12345", "/T"],
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=10,
+ )
+ ], mock_run.call_args_list
mock_proc.terminate.assert_not_called()
mock_proc.kill.assert_not_called()
diff --git a/tests/hermes_cli/test_boot_bootstrap.py b/tests/hermes_cli/test_boot_bootstrap.py
new file mode 100644
index 00000000000..966ce1d450b
--- /dev/null
+++ b/tests/hermes_cli/test_boot_bootstrap.py
@@ -0,0 +1,627 @@
+"""Boot-time post-update bootstrap: identity, records, locks, single-flight.
+
+The record files are an optimization layer over idempotent steps; these
+tests assert the contracts that keep that safe: identity resolution from
+real git trees and stamps, record scoping (per-install AND per-home vs
+per-machine), and the lock protocol including the double-check under lock.
+"""
+import json
+import os
+import shutil
+import subprocess
+import time
+from pathlib import Path
+
+import pytest
+
+from hermes_cli import boot_bootstrap
+from hermes_cli.boot_bootstrap import (
+ _RecordLock,
+ current_install_identity,
+ needs_bootstrap,
+ read_git_head,
+ read_last_known,
+ record_path,
+ run_boot_bootstrap,
+ write_record,
+)
+
+
+def _git(args, cwd):
+ env = dict(os.environ)
+ env.update({
+ "GIT_AUTHOR_NAME": "t", "GIT_AUTHOR_EMAIL": "t@t",
+ "GIT_COMMITTER_NAME": "t", "GIT_COMMITTER_EMAIL": "t@t",
+ "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_SYSTEM": os.devnull,
+ })
+ return subprocess.run(
+ ["git", *args], cwd=cwd, env=env, capture_output=True, text=True, check=True
+ )
+
+
+def repo(tmp_path):
+ root = tmp_path / "repo"
+ root.mkdir()
+ _git(["init", "-b", "main"], root)
+ (root / "f.txt").write_text("1", encoding="utf-8")
+ _git(["add", "."], root)
+ _git(["commit", "-m", "one"], root)
+ return root
+
+
+def _head_sha(root):
+ return _git(["rev-parse", "HEAD"], root).stdout.strip()
+
+
+# ── read_git_head ────────────────────────────────────────────────────
+
+
+def test_read_git_head_branch_ref(repo):
+ assert read_git_head(repo) == _head_sha(repo)
+
+
+def test_read_git_head_detached(repo):
+ sha = _head_sha(repo)
+ _git(["checkout", "--detach", sha], repo)
+ assert read_git_head(repo) == sha
+
+
+def test_read_git_head_packed_refs(repo):
+ sha = _head_sha(repo)
+ _git(["pack-refs", "--all"], repo)
+ # Loose ref is gone; only packed-refs carries the branch now.
+ assert not (repo / ".git" / "refs" / "heads" / "main").exists()
+ assert read_git_head(repo) == sha
+
+
+def test_read_git_head_worktree_gitfile(repo, tmp_path):
+ wt = tmp_path / "wt"
+ _git(["worktree", "add", str(wt)], repo)
+ assert (wt / ".git").is_file() # gitfile pointer, not a directory
+ assert read_git_head(wt) == _head_sha(wt)
+
+
+def test_read_git_head_reftable(tmp_path):
+ """The repo format that kills hand-rolled .git parsers.
+
+ A reftable repo stores refs in neither loose files nor packed-refs,
+ and its HEAD is a decoy (``ref: refs/heads/.invalid``) kept only so
+ pre-reftable tools fail loudly instead of misreading. Asking git
+ answers. If git here is too old for reftable, nothing to test.
+ """
+ root = tmp_path / "rt"
+ root.mkdir()
+ try:
+ _git(["init", "--ref-format=reftable", "-b", "main", "."], root)
+ except subprocess.CalledProcessError:
+ pytest.skip("git too old for --ref-format=reftable")
+ (root / "f.txt").write_text("1", encoding="utf-8")
+ _git(["add", "."], root)
+ _git(["commit", "-m", "one"], root)
+
+ head = (root / ".git" / "HEAD").read_text(encoding="utf-8")
+ assert ".invalid" in head, "reftable decoy HEAD is the point of this test"
+
+ assert read_git_head(root) == _head_sha(root)
+
+
+def test_read_git_head_missing_and_garbage(tmp_path):
+ assert read_git_head(tmp_path) is None
+ (tmp_path / ".git").write_text("not a gitdir pointer", encoding="utf-8")
+ assert read_git_head(tmp_path) is None
+
+
+# ── current_install_identity ─────────────────────────────────────────
+
+
+def test_identity_prefers_git(repo):
+ assert current_install_identity(repo) == _head_sha(repo)
+
+
+def test_identity_sealed_stamp(tmp_path):
+ (tmp_path / "install-stamp.json").write_text(
+ json.dumps({"commit": "a" * 40, "distribution": "desktop-app", "updateMechanism": "electron-updater"}),
+ encoding="utf-8",
+ )
+ assert current_install_identity(tmp_path) == "a" * 40
+
+
+def test_identity_broken_tree_is_none(tmp_path):
+ assert current_install_identity(tmp_path) is None
+ (tmp_path / "install-stamp.json").write_text("garbage", encoding="utf-8")
+ assert current_install_identity(tmp_path) is None
+
+
+# ── record paths ─────────────────────────────────────────────────────
+
+
+def test_record_paths_key_on_install_root(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
+ a = record_path(tmp_path / "install-a", "home")
+ b = record_path(tmp_path / "install-b", "home")
+ assert a != b
+ # The key is a FOLDER (installs/<SHA16>/bootstrap/<profile>.json),
+ # not a filename suffix: same grandparent tree, different key dirs.
+ assert a.parent != b.parent
+ assert a.parent.parent.parent == b.parent.parent.parent # installs/
+ assert a.name == b.name # the profile filename is the shared part
+
+
+def test_home_records_differ_per_profile_machine_record_shared(tmp_path, monkeypatch):
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ base = tmp_path / ".hermes"
+ profile = base / "profiles" / "coder"
+ install = tmp_path / "install"
+
+ monkeypatch.setenv("HERMES_HOME", str(base))
+ home_default = record_path(install, "home")
+ machine_default = record_path(install, "machine")
+
+ monkeypatch.setenv("HERMES_HOME", str(profile))
+ home_profile = record_path(install, "home")
+ machine_profile = record_path(install, "machine")
+
+ assert home_default != home_profile # each profile bootstraps its own home
+ assert machine_default == machine_profile # machine record is shared
+
+
+def test_record_path_rejects_unknown_scope(tmp_path):
+ with pytest.raises(ValueError):
+ record_path(tmp_path, "galaxy")
+
+
+ os.name == "nt", reason="requires symlink privilege on Windows"
+)
+def test_symlinked_root_canonicalizes(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
+ real = tmp_path / "real-install"
+ real.mkdir()
+ link = tmp_path / "link-install"
+ link.symlink_to(real)
+ assert record_path(real, "home") == record_path(link, "home")
+
+
+# ── needs_bootstrap ──────────────────────────────────────────────────
+
+
+def test_needs_bootstrap_lifecycle(repo, tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
+ sha = _head_sha(repo)
+
+ # No record yet → identity returned.
+ assert needs_bootstrap(repo, "home") == sha
+
+ write_record(repo, "home", sha)
+ assert needs_bootstrap(repo, "home") is None
+
+ # New commit → mismatch again.
+ (repo / "f.txt").write_text("2", encoding="utf-8")
+ _git(["add", "."], repo)
+ _git(["commit", "-m", "two"], repo)
+ assert needs_bootstrap(repo, "home") == _head_sha(repo)
+
+
+def test_needs_bootstrap_broken_tree_never_fires(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
+ assert needs_bootstrap(tmp_path / "nope", "home") is None
+
+
+# ── lock protocol ────────────────────────────────────────────────────
+
+
+def test_lock_loser_skips(tmp_path):
+ record = tmp_path / "r.json"
+ first = _RecordLock(record)
+ second = _RecordLock(record)
+ assert first.acquire()
+ assert not second.acquire()
+ first.release()
+ assert second.acquire()
+ second.release()
+
+
+def test_stale_lock_is_broken(tmp_path):
+ record = tmp_path / "r.json"
+ lock_path = record.with_name(record.name + ".lock")
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
+ lock_path.write_text(
+ json.dumps({"pid": 1, "startedAt": time.time() - 3600}), encoding="utf-8"
+ )
+ lock = _RecordLock(record)
+ assert lock.acquire()
+ lock.release()
+
+
+def test_fresh_lock_is_respected(tmp_path):
+ record = tmp_path / "r.json"
+ lock_path = record.with_name(record.name + ".lock")
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
+ lock_path.write_text(
+ json.dumps({"pid": os.getpid(), "startedAt": time.time()}), encoding="utf-8"
+ )
+ assert not _RecordLock(record).acquire()
+
+
+# ── run_boot_bootstrap ───────────────────────────────────────────────
+
+
+def fake_steps(monkeypatch):
+ calls = {"home": 0, "machine": 0}
+
+ def home_step():
+ calls["home"] += 1
+ return {"ok": True}
+
+ def machine_step():
+ calls["machine"] += 1
+ return {"ok": True}
+
+ from hermes_cli import post_update
+
+ monkeypatch.setattr(post_update, "HOME_STEPS", (("h", home_step),))
+ monkeypatch.setattr(post_update, "MACHINE_STEPS", (("m", machine_step),))
+ # Machine steps run on a thread; make THOSE synchronous for the test.
+ # boot_bootstrap does `import threading` inside the function, so patching
+ # the stdlib module's Thread attribute is what reaches it — but only the
+ # bootstrap's own threads may be faked: subprocess.communicate creates
+ # reader Threads on Windows and needs the real class.
+ import threading
+
+ real_thread = threading.Thread
+
+ class _SyncThread(real_thread):
+ def start(self):
+ if str(getattr(self, "name", "")).startswith("hermes-bootstrap"):
+ if self._target is not None:
+ self._target(*self._args, **self._kwargs)
+ return
+ real_thread.start(self)
+
+ monkeypatch.setattr(threading, "Thread", _SyncThread)
+ return calls
+
+
+def test_run_boot_bootstrap_runs_then_noops(repo, tmp_path, monkeypatch, fake_steps):
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+
+ first = run_boot_bootstrap(repo)
+ assert fake_steps == {"home": 1, "machine": 1}
+ assert first["home"] == {"h": {"ok": True}}
+ assert first["machine"] == "deferred"
+
+ second = run_boot_bootstrap(repo)
+ assert fake_steps == {"home": 1, "machine": 1} # no re-run
+ assert second == {"home": "skipped", "machine": "skipped"}
+
+
+def test_machine_step_runs_once_across_profiles(repo, tmp_path, monkeypatch, fake_steps):
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ base = tmp_path / ".hermes"
+
+ monkeypatch.setenv("HERMES_HOME", str(base))
+ run_boot_bootstrap(repo)
+ monkeypatch.setenv("HERMES_HOME", str(base / "profiles" / "coder"))
+ run_boot_bootstrap(repo)
+
+ # Each home bootstraps itself; the machine step fires once.
+ assert fake_steps == {"home": 2, "machine": 1}
+
+
+def test_step_failure_still_writes_record(repo, tmp_path, monkeypatch):
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+
+ from hermes_cli import post_update
+
+ def boom():
+ raise RuntimeError("step exploded")
+
+ monkeypatch.setattr(post_update, "HOME_STEPS", (("boom", boom),))
+ monkeypatch.setattr(post_update, "MACHINE_STEPS", ())
+
+ run_boot_bootstrap(repo)
+ record = read_last_known(record_path(repo, "home"))
+ assert record["identity"] == _head_sha(repo)
+ assert record["results"]["boom"]["ok"] is False
+
+ # A broken step must not retrigger the slow path every boot.
+ assert needs_bootstrap(repo, "home") is None
+
+
+def test_double_check_under_lock(repo, tmp_path, monkeypatch, fake_steps):
+ """A racer that finished between our read and our acquire wins."""
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ sha = _head_sha(repo)
+
+ real_acquire = _RecordLock.acquire
+
+ def acquire_after_racer_finished(self):
+ got = real_acquire(self)
+ if got and self.path.name.endswith(".json.lock"):
+ # Simulate the previous holder completing just before us.
+ write_record(repo, "home", sha)
+ return got
+
+ monkeypatch.setattr(_RecordLock, "acquire", acquire_after_racer_finished)
+ result = run_boot_bootstrap(repo)
+ assert result["home"] == "done-by-other"
+ assert fake_steps["home"] == 0
+
+
+def test_maybe_run_never_raises(monkeypatch, tmp_path):
+ monkeypatch.setattr(
+ boot_bootstrap, "run_boot_bootstrap",
+ lambda root: (_ for _ in ()).throw(RuntimeError("boom")),
+ )
+ boot_bootstrap.maybe_run_boot_bootstrap(tmp_path) # must not raise
+
+
+def test_deferred_machine_steps_execute(repo, tmp_path, monkeypatch):
+ """The machine scope defers to a REAL thread — the record is written
+ first (boot readiness must not wait on network installers), and the
+ steps still actually run. No synchronous-thread fake here on purpose:
+ the claim under test is that the deferred work happens."""
+ import threading
+
+ from hermes_cli import post_update
+
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+
+ ran = threading.Event()
+ monkeypatch.setattr(post_update, "HOME_STEPS", ())
+ monkeypatch.setattr(
+ post_update,
+ "MACHINE_STEPS",
+ (("probe", lambda: (ran.set(), {"ok": True})[1]),),
+ )
+
+ result = run_boot_bootstrap(repo)
+
+ assert result["machine"] == "deferred"
+ # The record was written BEFORE the steps finished (that ordering is
+ # the design: a crash mid-step must not retrigger every boot).
+ record = boot_bootstrap.record_path(repo, "machine")
+ assert json.loads(record.read_text())["results"]["deferred"] is True
+ assert ran.wait(timeout=10), "deferred machine steps never executed"
+
+
+def test_sealed_tree_bootstrap_end_to_end(tmp_path, monkeypatch):
+ """The desktop-bundle-swap scenario. A sealed tree (install-stamp.json,
+ no .git) must bootstrap on first boot, no-op on the second, and RE-RUN
+ when the stamp's commit changes — that is the only signal a bundle
+ swap emits."""
+ import json as _json
+
+ from hermes_cli import post_update
+
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ # A sealed tree consults pm for drift; keep the test hermetic.
+ import pm
+
+ monkeypatch.setattr(pm, "check", lambda: [])
+
+ sealed = tmp_path / "payload"
+ sealed.mkdir()
+ (sealed / "install-stamp.json").write_text(
+ _json.dumps({"commit": "aaaa1111", "payload": "full", "updateMechanism": "electron-updater"})
+ )
+
+ calls = {"n": 0}
+
+ def count():
+ calls["n"] += 1
+ return {"ok": True}
+
+ monkeypatch.setattr(post_update, "HOME_STEPS", (("h", count),))
+ monkeypatch.setattr(post_update, "MACHINE_STEPS", ())
+
+ assert run_boot_bootstrap(sealed)["home"] != "skipped"
+ assert calls["n"] == 1
+ assert run_boot_bootstrap(sealed)["home"] == "skipped"
+ assert calls["n"] == 1 # second boot: identity unchanged, no work
+
+ # The bundle swap: same root, new stamp commit.
+ (sealed / "install-stamp.json").write_text(
+ _json.dumps({"commit": "bbbb2222", "payload": "full", "updateMechanism": "electron-updater"})
+ )
+
+ assert run_boot_bootstrap(sealed)["home"] != "skipped"
+ assert calls["n"] == 2, "a swapped bundle must re-run the bootstrap"
+
+
+# ── the per-install state folder ─────────────────────────────────────
+
+
+def test_ensure_install_dir_writes_the_reverse_map(repo, tmp_path, monkeypatch):
+ """install.json is the sha16 → root reverse map that makes orphan GC
+ possible. Written once; a second call must not rewrite firstSeen."""
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes")) # isolate the default root
+
+ state = boot_bootstrap.ensure_install_dir(repo)
+
+ assert state == boot_bootstrap.install_state_dir(repo)
+ record = json.loads((state / "install.json").read_text())
+ assert record["root"] == str(repo.resolve())
+ assert record["steward"] == "checkout"
+ first_seen = record["firstSeen"]
+
+ boot_bootstrap.ensure_install_dir(repo)
+ assert json.loads((state / "install.json").read_text())["firstSeen"] == first_seen
+
+
+def test_ensure_install_dir_records_the_sealed_steward(tmp_path, monkeypatch):
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes")) # isolate the default root
+
+ sealed = tmp_path / "payload"
+ sealed.mkdir()
+ (sealed / "install-stamp.json").write_text(
+ json.dumps({"commit": "c" * 40, "distribution": "desktop-app", "updateMechanism": "electron-updater"})
+ )
+ state = boot_bootstrap.ensure_install_dir(sealed)
+ record = json.loads((state / "install.json").read_text())
+ assert record["steward"] == "desktop-app"
+
+
+def test_orphan_sweep_flags_only_vanished_roots(repo, tmp_path, monkeypatch):
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes")) # isolate the default root
+
+ boot_bootstrap.ensure_install_dir(repo) # alive
+ ghost = tmp_path / "deleted-checkout"
+ ghost.mkdir()
+ ghost_state = boot_bootstrap.ensure_install_dir(ghost)
+ shutil.rmtree(ghost) # the install is gone; its state folder is not
+
+ orphans = boot_bootstrap.orphaned_installs()
+
+ assert [(folder, root) for folder, root in orphans] == [
+ (ghost_state, str(ghost))
+ ]
+
+
+def test_bootstrap_records_live_inside_the_state_folder(repo, tmp_path, monkeypatch):
+ """Both scopes share the install's folder; profile identity rides the
+ FILENAME. One anchor, not two homes."""
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes")) # isolate the default root
+
+ home = boot_bootstrap.record_path(repo, "home")
+ machine = boot_bootstrap.record_path(repo, "machine")
+
+ state = boot_bootstrap.install_state_dir(repo)
+ assert home == state / "bootstrap" / "default.json"
+ assert machine == state / "bootstrap" / "machine.json"
+
+
+class TestSealedDriftBackstop:
+ """_report_sealed_runtime_drift — every boot of a drifted sealed tree
+ says so; nothing else makes a sound, and nothing ever gates boot."""
+
+ def _sealed_tree(self, tmp_path):
+ root = tmp_path / "sealed"
+ root.mkdir()
+ (root / "install-stamp.json").write_text(
+ json.dumps({"schemaVersion": 2, "commit": "a" * 40, "distribution": "docker", "updateMechanism": "external"}),
+ encoding="utf-8",
+ )
+ return root
+
+ def test_drifted_sealed_tree_reports_to_stderr(self, tmp_path, capsys, monkeypatch):
+ import pm
+
+ root = self._sealed_tree(tmp_path)
+ monkeypatch.setattr(pm, "check", lambda: ["node: not installed or outdated"])
+ message = boot_bootstrap._report_sealed_runtime_drift(root)
+ assert message is not None and "node" in message
+ err = capsys.readouterr().err
+ assert "docker" in err and "node" in err
+
+ def test_current_sealed_tree_is_silent(self, tmp_path, capsys, monkeypatch):
+ import pm
+
+ root = self._sealed_tree(tmp_path)
+ monkeypatch.setattr(pm, "check", lambda: [])
+ assert boot_bootstrap._report_sealed_runtime_drift(root) is None
+ assert capsys.readouterr().err == ""
+
+ def test_checkout_is_silent_even_with_drift(self, tmp_path, capsys, monkeypatch):
+ """A checkout provisions on demand; drift there is self-healing
+ and must not produce boot noise."""
+ import pm
+
+ root = tmp_path / "co"
+ (root / ".git").mkdir(parents=True)
+ monkeypatch.setattr(pm, "check", lambda: ["node: not installed or outdated"])
+ assert boot_bootstrap._report_sealed_runtime_drift(root) is None
+ assert capsys.readouterr().err == ""
+
+ def test_a_broken_check_never_gates_boot(self, tmp_path, monkeypatch):
+ import pm
+
+ root = self._sealed_tree(tmp_path)
+
+ def explode():
+ raise RuntimeError("facts file corrupted")
+
+ monkeypatch.setattr(pm, "check", explode)
+ assert boot_bootstrap._report_sealed_runtime_drift(root) is None
+
+ def test_drift_lands_in_the_boot_summary(self, tmp_path, monkeypatch):
+ import pm
+
+ from hermes_cli import post_update
+
+ root = self._sealed_tree(tmp_path)
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ monkeypatch.setattr(pm, "check", lambda: ["uv: not installed or outdated"])
+ monkeypatch.setattr(post_update, "HOME_STEPS", ())
+ monkeypatch.setattr(post_update, "MACHINE_STEPS", ())
+ summary = run_boot_bootstrap(root)
+ assert "uv" in summary.get("sealed_runtime_drift", "")
+
+
+class TestOrphanedStoreEntries:
+ """orphaned_store_entries — pm's facts.json is the only authority,
+ keep on doubt."""
+
+ @pytest.fixture
+ def store(self, tmp_path, monkeypatch):
+ store = tmp_path / "tools"
+ store.mkdir(parents=True)
+ monkeypatch.setenv("HERMES_RUNTIME_DIR", str(store))
+ return store
+
+ def _publish(self, store, name, payload=b"tool bytes"):
+ entry = store / name
+ entry.mkdir(parents=True)
+ (entry / "tool.bin").write_bytes(payload)
+ return entry
+
+ def _facts(self, store, packages: dict):
+ (store / "facts.json").write_text(
+ json.dumps({"schema": 1, "packages": packages}), encoding="utf-8"
+ )
+
+ def test_referenced_entries_survive_unreferenced_are_flagged(self, store):
+ self._publish(store, "ripgrep-15.2.0-win32-x64")
+ stale = self._publish(store, "ripgrep-14.1.0-win32-x64", b"x" * 512)
+ self._facts(store, {
+ "ripgrep": {"entry": "ripgrep-15.2.0-win32-x64", "version": "15.2.0", "env": {}},
+ })
+
+ orphans = boot_bootstrap.orphaned_store_entries()
+
+ assert [(e.name, s) for e, s in orphans] == [
+ ("ripgrep-14.1.0-win32-x64", 512)
+ ]
+ assert stale.exists() # report-only: nothing was deleted
+
+ def test_no_facts_file_reports_nothing(self, store):
+ """pm only vouches for what it installed: no ledger, no verdicts."""
+ self._publish(store, "gh-2.97.0-win32-x64")
+ assert boot_bootstrap.orphaned_store_entries() == []
+
+ def test_unreadable_facts_err_toward_keep(self, store):
+ """A busted ledger must cost disk, not flag entries it may own."""
+ self._publish(store, "gh-2.97.0-win32-x64")
+ (store / "facts.json").write_text("NOT JSON", encoding="utf-8")
+ assert boot_bootstrap.orphaned_store_entries() == []
+
+ def test_scratch_fetch_and_files_are_not_candidates(self, store):
+ """Scratch dirs are pm's own cleanup, fetch-* entries are the
+ re-download cache, and stray files are not entries at all."""
+ (store / ".staging-abc123").mkdir()
+ self._publish(store, "fetch-0123456789abcdef")
+ (store / "stray.txt").write_text("x", encoding="utf-8")
+ self._facts(store, {})
+ assert boot_bootstrap.orphaned_store_entries() == []
diff --git a/tests/hermes_cli/test_build_info.py b/tests/hermes_cli/test_build_info.py
deleted file mode 100644
index e3bc7e3ecf8..00000000000
--- a/tests/hermes_cli/test_build_info.py
+++ /dev/null
@@ -1,35 +0,0 @@
-"""Tests for hermes_cli.build_info — baked-in build SHA resolution.
-
-The build SHA is written by the Dockerfile's ``HERMES_GIT_SHA`` build-arg
-into ``<project_root>/.hermes_build_sha``. These tests cover the read-side
-helper: missing file, malformed file, truncation, and error tolerance.
-"""
-
-from pathlib import Path
-from unittest.mock import patch
-
-
-def test_get_build_sha_returns_none_when_file_absent(tmp_path):
- """Source installs: no file present → None, callers fall back to git."""
- from hermes_cli import build_info
-
- missing = tmp_path / ".hermes_build_sha" # never created
-
- with patch.object(build_info, "_BUILD_SHA_FILE", missing):
- assert build_info.get_build_sha() is None
-
-
-def test_get_build_sha_respects_short_argument(tmp_path):
- """``short=N`` truncates to N chars; ``short<=0`` returns full SHA."""
- from hermes_cli import build_info
-
- sha_file = tmp_path / ".hermes_build_sha"
- full_sha = "abcdef1234567890abcdef1234567890abcdef12"
- sha_file.write_text(full_sha + "\n")
-
- with patch.object(build_info, "_BUILD_SHA_FILE", sha_file):
- assert build_info.get_build_sha(short=12) == "abcdef123456"
- assert build_info.get_build_sha(short=0) == full_sha
- assert build_info.get_build_sha(short=-1) == full_sha
-
-
diff --git a/tests/hermes_cli/test_bundled_desktop_launch.py b/tests/hermes_cli/test_bundled_desktop_launch.py
new file mode 100644
index 00000000000..97676307181
--- /dev/null
+++ b/tests/hermes_cli/test_bundled_desktop_launch.py
@@ -0,0 +1,329 @@
+"""``hermes desktop`` from inside a BUNDLED desktop payload.
+
+A bundled artifact ships the CLI inside ``<app>/resources/agent-payload``
+and the desktop app is the artifact itself — there is no source tree to
+build and the app resources are signed and read-only. These tests pin the
+two halves of that: where the launcher is (hermes_cli.bundled_app) and
+that cmd_gui starts it instead of running the checkout build ladder.
+
+The layout resolver is pure path arithmetic over real directories, so
+every platform's shape is exercised from any host.
+"""
+
+import json
+import subprocess
+import sys
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import patch
+
+import pytest
+
+import hermes_cli.main as cli_main
+from hermes_cli.bundled_app import (
+ NotBundledApp,
+ launch_detached,
+ resolve_bundle_layout,
+)
+from hermes_cli.steward import is_bundled_payload
+
+STAMP = {
+ "schemaVersion": 2,
+ "commit": "a" * 40,
+ "commitDate": 1750000000,
+ "branch": None,
+ "builtAt": "2026-08-21T00:00:00+00:00",
+ "dirty": False,
+ "source": "ci",
+ "distribution": "desktop-app",
+ "updateMechanism": "electron-updater",
+ "baseVersion": "0.27.0",
+ "displayVersion": "0.27.0",
+ "distance": 0,
+ "payload": "bundled",
+ "tag": "v0.27.0",
+}
+
+
+def _exe(path: Path) -> Path:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(b"MZ")
+ path.chmod(0o755)
+ return path
+
+
+def _payload(app_root: Path, *, resources_name: str = "resources") -> Path:
+ """Stage a payload repo under *app_root*; returns the repo root."""
+ repo = app_root / resources_name / "agent-payload" / "repo"
+ # repo/apps/desktop survives prunePayload(), which is exactly why a
+ # package.json probe cannot tell a bundle from a checkout.
+ (repo / "apps" / "desktop").mkdir(parents=True)
+ (repo / "apps" / "desktop" / "package.json").write_text('{"name":"desktop"}\n')
+ (repo / "install-stamp.json").write_text(json.dumps(STAMP) + "\n", encoding="utf-8")
+ return repo
+
+
+def _linux_bundle(tmp_path: Path) -> Path:
+ app = tmp_path / "linux-unpacked"
+ repo = _payload(app)
+ _exe(app / "Hermes")
+ # The helpers a Linux Electron tree ships beside its launcher.
+ _exe(app / "chrome-sandbox")
+ _exe(app / "chrome_crashpad_handler")
+ _exe(app / "libffmpeg.so")
+ (app / "version").write_text("40.9.3\n")
+ return repo
+
+
+def _windows_bundle(tmp_path: Path) -> Path:
+ app = tmp_path / "Hermes"
+ repo = _payload(app)
+ _exe(app / "Hermes.exe")
+ _exe(app / "Uninstall Hermes.exe")
+ return repo
+
+
+def _macos_bundle(tmp_path: Path) -> Path:
+ app = tmp_path / "Hermes.app"
+ repo = _payload(app / "Contents", resources_name="Resources")
+ _exe(app / "Contents" / "MacOS" / "Hermes")
+ return repo
+
+
+def _host_bundle(tmp_path: Path) -> tuple[Path, Path]:
+ """A bundle in THIS host's shape, plus its expected launcher.
+
+ cmd_gui resolves the launcher with the real sys.platform, and the
+ Linux rule depends on POSIX execute bits that do not exist on Windows
+ — so the cmd_gui tests must stage the host's own shape.
+ """
+ if sys.platform == "win32":
+ repo = _windows_bundle(tmp_path)
+ return repo, tmp_path / "Hermes" / "Hermes.exe"
+ repo = _linux_bundle(tmp_path)
+ return repo, tmp_path / "linux-unpacked" / "Hermes"
+
+
+class TestResolveBundleLayout:
+ @pytest.mark.skipif(
+ sys.platform == "win32",
+ reason="POSIX-only: the Linux launcher rule reads execute bits, "
+ "which os.access reports as always-set on Windows",
+ )
+ def test_linux_launcher_is_the_one_non_helper_executable(self, tmp_path):
+ repo = _linux_bundle(tmp_path)
+ layout = resolve_bundle_layout(repo, platform="linux")
+ assert layout.app_root == tmp_path / "linux-unpacked"
+ assert layout.payload.name == "agent-payload"
+ assert layout.launcher == tmp_path / "linux-unpacked" / "Hermes"
+
+ def test_windows_launcher_is_never_the_uninstaller(self, tmp_path):
+ repo = _windows_bundle(tmp_path)
+ layout = resolve_bundle_layout(repo, platform="win32")
+ assert layout.launcher == tmp_path / "Hermes" / "Hermes.exe"
+
+ def test_macos_app_root_climbs_out_of_contents_resources(self, tmp_path):
+ repo = _macos_bundle(tmp_path)
+ layout = resolve_bundle_layout(repo, platform="darwin")
+ assert layout.app_root == tmp_path / "Hermes.app"
+ assert layout.resources == tmp_path / "Hermes.app" / "Contents" / "Resources"
+ assert layout.launcher == tmp_path / "Hermes.app" / "Contents" / "MacOS" / "Hermes"
+
+ def test_ambiguous_launcher_reports_none_rather_than_guessing(self, tmp_path):
+ repo = _windows_bundle(tmp_path)
+ _exe(repo.parent.parent.parent / "Other.exe")
+ assert resolve_bundle_layout(repo, platform="win32").launcher is None
+
+ def test_a_checkout_is_not_a_bundle(self, tmp_path):
+ checkout = tmp_path / "hermes-agent"
+ (checkout / "apps" / "desktop").mkdir(parents=True)
+ with pytest.raises(NotBundledApp):
+ resolve_bundle_layout(checkout)
+
+ def test_a_sealed_tree_with_no_app_is_not_a_bundle(self, tmp_path):
+ # docker/nix shape: sealed repo, no agent-payload parent.
+ repo = tmp_path / "opt" / "hermes" / "repo"
+ repo.mkdir(parents=True)
+ with pytest.raises(NotBundledApp):
+ resolve_bundle_layout(repo)
+
+
+class TestShapePredicate:
+ """cmd_gui and the bundle build must agree about what a bundle is."""
+
+ def test_a_stamped_payload_is_bundled(self, tmp_path):
+ assert is_bundled_payload(_linux_bundle(tmp_path))
+
+ def test_a_surviving_desktop_package_json_does_not_make_a_bundle(self, tmp_path):
+ """repo/apps/desktop survives the payload prune, so a filesystem
+ probe cannot be the authority — only the stamp can."""
+ checkout = tmp_path / "hermes-agent"
+ (checkout / "apps" / "desktop").mkdir(parents=True)
+ (checkout / "apps" / "desktop" / "package.json").write_text("{}\n")
+ assert not is_bundled_payload(checkout)
+
+ def test_a_bootstrap_artifact_is_not_bundled(self, tmp_path):
+ root = tmp_path / "hermes-agent"
+ root.mkdir()
+ stamp = dict(STAMP, payload="bootstrap", tag=None)
+ (root / "install-stamp.json").write_text(json.dumps(stamp) + "\n")
+ assert not is_bundled_payload(root)
+
+ def test_an_unreadable_stamp_is_not_bundled(self, tmp_path):
+ root = tmp_path / "hermes-agent"
+ root.mkdir()
+ (root / "install-stamp.json").write_text("{ not json\n")
+ assert not is_bundled_payload(root)
+
+
+class TestLaunchDetached:
+ def test_the_child_outlives_this_process_and_owns_no_stdio(self):
+ seen = {}
+
+ def fake_popen(argv, **kwargs):
+ seen["argv"] = argv
+ seen["kwargs"] = kwargs
+ return SimpleNamespace(pid=1234)
+
+ with patch("hermes_cli.bundled_app.subprocess.Popen", side_effect=fake_popen):
+ pid = launch_detached(["/app/Hermes", "--no-sandbox"], cwd="/app")
+
+ assert pid == 1234
+ assert seen["argv"] == ["/app/Hermes", "--no-sandbox"]
+ assert seen["kwargs"]["cwd"] == "/app"
+ assert seen["kwargs"]["stdout"] is subprocess.DEVNULL
+ assert seen["kwargs"]["stderr"] is subprocess.DEVNULL
+ assert seen["kwargs"]["stdin"] is subprocess.DEVNULL
+ # POSIX detaches with a new session; Windows with creation flags.
+ detach_key = "creationflags" if sys.platform == "win32" else "start_new_session"
+ assert seen["kwargs"][detach_key]
+
+ def test_a_real_child_survives_and_is_reachable(self, tmp_path):
+ """The one E2E rung: spawn a real process and prove it ran."""
+ marker = tmp_path / "ran.txt"
+ pid = launch_detached(
+ [sys.executable, "-c", f"open({str(marker)!r}, 'w').write('yes')"]
+ )
+ assert pid > 0
+ deadline = 10.0
+ import time
+
+ while deadline > 0 and not marker.exists():
+ time.sleep(0.1)
+ deadline -= 0.1
+ assert marker.read_text() == "yes"
+
+
+class TestCmdGuiOnABundle:
+ """The behavior the checkout ladder got wrong: never build in a bundle."""
+
+ @staticmethod
+ def _args(**overrides):
+ base = dict(
+ source=False, build_only=False, fake_boot=False, ignore_existing=False,
+ hermes_root=None, cwd=None, skip_build=False, force_build=False,
+ )
+ base.update(overrides)
+ return SimpleNamespace(**base)
+
+ @staticmethod
+ def _run(monkeypatch, repo: Path, args, *, launcher_ok: bool = True):
+ """Run cmd_gui against *repo*, recording builds and launches."""
+ builds: list[list[str]] = []
+ launches: list[list[str]] = []
+
+ def record_run(cmd, *a, **kw):
+ builds.append([str(c) for c in cmd])
+ return subprocess.CompletedProcess(cmd, 0)
+
+ def record_npm_install(npm, root, **kw):
+ builds.append(["npm", "ci", str(root)])
+ return subprocess.CompletedProcess(["npm", "ci"], 0)
+
+ def record_popen(argv, **kw):
+ launches.append([str(a) for a in argv])
+ return SimpleNamespace(pid=4242)
+
+ monkeypatch.setattr(cli_main, "PROJECT_ROOT", repo)
+ monkeypatch.setattr(cli_main, "_resolve_node_runtime_npm", lambda: "/usr/bin/npm")
+ monkeypatch.setattr(cli_main, "_desktop_build_needed", lambda *a, **k: True)
+ monkeypatch.setattr(cli_main, "_write_desktop_build_stamp", lambda *a, **k: None)
+ monkeypatch.setattr(
+ cli_main, "_run_npm_install_deterministic", record_npm_install
+ )
+ monkeypatch.setattr(
+ cli_main, "_stop_desktop_processes_locking_build", lambda *a, **k: []
+ )
+ monkeypatch.setattr(
+ cli_main, "_desktop_linux_sandbox_fixup", lambda *a, **k: launcher_ok
+ )
+ monkeypatch.setattr(
+ cli_main, "_desktop_linux_needs_no_sandbox", lambda: not launcher_ok
+ )
+ monkeypatch.setattr(
+ cli_main,
+ "_desktop_linux_sandbox_helper_is_regular_file",
+ lambda *a, **k: True,
+ )
+ monkeypatch.setattr(cli_main, "_detect_linux_password_store", lambda: None)
+
+ with patch("hermes_cli.bundled_app.subprocess.Popen", side_effect=record_popen), \
+ patch.object(cli_main.subprocess, "run", side_effect=record_run), \
+ pytest.raises(SystemExit) as exit_info:
+ cli_main.cmd_gui(args)
+
+ return exit_info.value.code, builds, launches
+
+ def test_launches_the_bundle_and_builds_nothing(self, tmp_path, monkeypatch):
+ repo, launcher = _host_bundle(tmp_path)
+ code, builds, launches = self._run(monkeypatch, repo, self._args())
+
+ assert code == 0
+ # THE regression: repo/apps/desktop/package.json exists in a bundle,
+ # so the old probe fell through to npm ci + npm run pack inside the
+ # app's own signed resources.
+ assert builds == []
+ assert launches == [[str(launcher)]]
+
+ def test_a_checkout_still_takes_the_build_ladder(self, tmp_path, monkeypatch):
+ checkout = tmp_path / "hermes-agent"
+ (checkout / "apps" / "desktop").mkdir(parents=True)
+ (checkout / "apps" / "desktop" / "package.json").write_text("{}\n")
+ code, builds, launches = self._run(monkeypatch, checkout, self._args())
+
+ assert launches == []
+ assert any("npm" in " ".join(cmd) for cmd in builds), builds
+
+ @pytest.mark.parametrize("flag", ["source", "build_only", "force_build"])
+ def test_build_flags_are_refused_rather_than_ignored(self, tmp_path, monkeypatch, flag):
+ repo, _launcher = _host_bundle(tmp_path)
+ code, builds, launches = self._run(
+ monkeypatch, repo, self._args(**{flag: True})
+ )
+
+ assert code == 2
+ assert builds == []
+ assert launches == []
+
+ def test_a_stamped_bundle_with_no_app_reports_damage(self, tmp_path, monkeypatch):
+ """A bundled stamp over a non-bundle tree must never fall back to
+ the build ladder — that would npm-build inside app resources."""
+ orphan = tmp_path / "somewhere" / "repo"
+ orphan.mkdir(parents=True)
+ (orphan / "install-stamp.json").write_text(json.dumps(STAMP) + "\n")
+ code, builds, launches = self._run(monkeypatch, orphan, self._args())
+
+ assert code == 1
+ assert builds == []
+ assert launches == []
+
+ def test_a_bundle_with_no_resolvable_launcher_reports_damage(self, tmp_path, monkeypatch):
+ app = tmp_path / "linux-unpacked"
+ repo = _payload(app)
+ _exe(app / "Hermes")
+ _exe(app / "Hermes-Other")
+ code, builds, launches = self._run(monkeypatch, repo, self._args())
+
+ assert code == 1
+ assert builds == []
+ assert launches == []
diff --git a/tests/hermes_cli/test_cmd_update.py b/tests/hermes_cli/test_cmd_update.py
index 119892aa538..1b9f4d501f3 100644
--- a/tests/hermes_cli/test_cmd_update.py
+++ b/tests/hermes_cli/test_cmd_update.py
@@ -1,6 +1,7 @@
"""Tests for cmd_update — branch fallback when remote branch doesn't exist."""
import hashlib
+import os
import subprocess
from types import SimpleNamespace
from unittest.mock import ANY, patch
@@ -43,32 +44,15 @@ def mock_args():
# ---------------------------------------------------------------------------
# Managed-uv compatibility for tests that patch shutil.which
# ---------------------------------------------------------------------------
-# The production code now uses ``ensure_uv()`` / ``update_managed_uv()``
-# instead of ``shutil.which("uv")``. Many tests in this file patch
-# ``shutil.which`` to control whether uv is "available" — these autouse
-# fixtures make the managed_uv functions delegate to the patched
-# ``shutil.which`` so the existing test setup keeps working without
-# per-test changes.
+# The production code resolves uv through ``pm.uv()`` instead of
+# ``shutil.which("uv")``. Many tests in this file patch ``shutil.which``
+# to control whether uv is "available" — this autouse fixture makes
+# pm.uv delegate to the patched ``shutil.which`` so the existing test
+# setup keeps working without per-test changes.
@pytest.fixture(autouse=True)
-def _patch_managed_uv(request):
- """Make managed_uv helpers follow shutil.which mocking in tests."""
- import shutil
-
- # resolve_uv delegates to shutil.which("uv") so that test patches
- # on shutil.which flow through naturally.
- def _fake_resolve_uv():
- return shutil.which("uv")
-
- def _fake_ensure_uv(**_kwargs):
- return shutil.which("uv")
-
- def _fake_update_managed_uv(**_kwargs):
- return None # never actually self-update in tests
-
- with patch("hermes_cli.managed_uv.resolve_uv", side_effect=_fake_resolve_uv), \
- patch("hermes_cli.managed_uv.ensure_uv", side_effect=_fake_ensure_uv), \
- patch("hermes_cli.managed_uv.update_managed_uv", side_effect=_fake_update_managed_uv):
- yield
+def _patch_managed_uv(request, patch_pm_uv_to_shutil_which):
+ """Make pm.uv follow shutil.which mocking in tests."""
+ yield
@pytest.fixture(autouse=True)
@@ -85,7 +69,27 @@ def _patch_gateway_discovery():
"""
with patch("hermes_cli.gateway.find_gateway_pids", return_value=[]), \
patch("hermes_cli.gateway.supports_systemd_services", return_value=False), \
- patch("hermes_cli.gateway.find_profile_gateway_processes", return_value=[]):
+ patch("hermes_cli.gateway.find_profile_gateway_processes", return_value=[]), \
+ patch("hermes_cli.main._detect_venv_python_processes", return_value=[]), \
+ patch("hermes_cli.main._fleet_probe_expected_runtimes", return_value=False), \
+ patch("os.kill"), \
+ patch("pm.ensure.sync_venv"), \
+ patch(
+ "hermes_cli.update_inventory.collect_runtime_inventory",
+ return_value=SimpleNamespace(runtimes=[], to_dict=lambda: {}),
+ ), \
+ patch("hermes_cli.main._purge_stale_hermes_modules"), \
+ patch("hermes_cli.main._pause_windows_gateways_for_update", return_value=None), \
+ patch("hermes_cli.main._resume_windows_gateways_after_update"), \
+ patch(
+ "hermes_cli.main._install_hangup_protection",
+ return_value={
+ "prev_stdout": None, "prev_stderr": None,
+ "log_file": None, "installed": False,
+ },
+ ), \
+ patch("hermes_cli.main._finalize_update_output"), \
+ patch("hermes_cli.update_cmd._reload_config_modules"):
yield
@@ -169,65 +173,19 @@ class TestCmdUpdateNpmLockfileCache:
assert cache_roots == [shared_root, shared_root]
-class TestCmdUpdateTermuxUvBootstrap:
- """Regression tests for Termux-specific uv bootstrap behavior."""
-
- @patch("shutil.which", return_value=None)
- @patch("subprocess.run")
- def test_termux_uv_bootstrap_uses_binary_only_install(
- self, mock_run, _mock_which, monkeypatch
- ):
- from hermes_cli import main as hm
-
- mock_run.return_value = subprocess.CompletedProcess([], 1, stdout="", stderr="")
- monkeypatch.setattr(hm, "_is_termux_env", lambda env=None: True)
-
- uv_bin = hm._ensure_uv_for_termux(["/termux/python", "-m", "pip"])
-
- assert uv_bin is None
- assert mock_run.call_count == 1
- assert mock_run.call_args.args[0] == [
- "/termux/python",
- "-m",
- "pip",
- "install",
- "uv",
- "--only-binary",
- ":all:",
- ]
- assert mock_run.call_args.kwargs["cwd"] == PROJECT_ROOT
- assert mock_run.call_args.kwargs["check"] is False
-
- @patch("subprocess.run")
- def test_termux_reuses_existing_path_uv_without_pip(self, mock_run, monkeypatch):
- """A uv already on PATH (e.g. ``pkg install uv``) is reused before pip runs."""
- from hermes_cli import main as hm
-
- pkg_uv = "/data/data/com.termux/files/usr/bin/uv"
- monkeypatch.setattr(hm, "_is_termux_env", lambda env=None: True)
- # Production resolve_uv only checks $HERMES_HOME/bin/uv; model an empty
- # managed dir so the PATH probe is what surfaces the packaged uv.
- monkeypatch.setattr("hermes_cli.managed_uv.resolve_uv", lambda: None)
- monkeypatch.setattr("shutil.which", lambda name: pkg_uv if name == "uv" else None)
-
- uv_bin = hm._ensure_uv_for_termux(["/termux/python", "-m", "pip"])
-
- assert uv_bin == pkg_uv
- mock_run.assert_not_called()
-
-
class TestUpdateManagedPythonEnvIsolation:
"""Regression for the uv-env isolation fix (third-party UV_PYTHON_INSTALL_DIR
must not hijack the update's pip install).
- The update path builds uv_env via managed_python_env() (drops
- VIRTUAL_ENV/PYTHONPATH/UV_PYTHON, pins UV_MANAGED_PYTHON=1 + UV_NO_CONFIG=1,
- forces UV_PYTHON_INSTALL_DIR to .hermes-runtime/python), then re-points
- VIRTUAL_ENV at this install's venv. These tests lock that contract in.
+ The update path builds uv_env via pm.packages.uv_env(): every UV_* user
+ override and active-venv leak (VIRTUAL_ENV, PYTHONPATH, ...) is STRIPPED
+ rather than re-pinned — pm passes --python explicitly, so no ambient
+ variable may steer which interpreter or install dir uv picks
+ (interpreter-hijack class, #83914). UV_NO_CONFIG=1 is the one pin.
"""
- def test_managed_env_drops_third_party_uv_install_dir(self):
- from hermes_cli.managed_uv import managed_python_env
+ def test_managed_env_drops_third_party_uv_overrides(self):
+ from pm.packages import uv_env
poisoned = {
"UV_PYTHON_INSTALL_DIR": r"C:\WorkBuddy\python",
@@ -236,37 +194,33 @@ class TestUpdateManagedPythonEnvIsolation:
"UV_NO_MANAGED_PYTHON": "1",
"VIRTUAL_ENV": r"C:\Some\Other\venv",
"PYTHONPATH": r"C:\Some\site-packages",
+ "PATH": r"C:\Windows",
}
- env = managed_python_env()
+ env = uv_env(poisoned)
- # Third-party UV_PYTHON_INSTALL_DIR must not survive into the env.
- assert env.get("UV_PYTHON_INSTALL_DIR", "") != r"C:\WorkBuddy\python"
+ # Every hijack vector is gone, not overridden.
assert "WorkBuddy" not in env.get("UV_PYTHON_INSTALL_DIR", "")
- # Managed pins are set; the hijack guards are explicitly cleared.
- assert env.get("UV_MANAGED_PYTHON") == "1"
- assert env.get("UV_NO_CONFIG") == "1"
assert env.get("UV_PYTHON") is None
assert env.get("UV_SYSTEM_PYTHON") is None
assert env.get("UV_NO_MANAGED_PYTHON") is None
assert env.get("VIRTUAL_ENV") is None
assert env.get("PYTHONPATH") is None
- # Sanity: the poisoned values did exist on input (guards the test itself).
- assert poisoned["UV_PYTHON_INSTALL_DIR"].startswith("C:\\WorkBuddy")
+ # The one pin: user/system uv config must not apply.
+ assert env.get("UV_NO_CONFIG") == "1"
+ # Non-UV env passes through untouched.
+ assert env.get("PATH") == r"C:\Windows"
- def test_update_uv_env_points_venv_and_runtime_store(self):
- """The update's final uv_env must carry VIRTUAL_ENV=this venv while the
- managed store path is still the UV_PYTHON_INSTALL_DIR."""
- from hermes_cli import main as hm
- from hermes_cli.managed_uv import managed_python_env
+ def test_update_uv_env_points_venv_after_repoint(self):
+ """The update path re-points VIRTUAL_ENV at this install's venv and
+ re-enables uv config discovery for the project sync."""
+ from pm.packages import uv_env
- uv_env = managed_python_env()
- uv_env["VIRTUAL_ENV"] = str(PROJECT_ROOT / "venv")
+ env = uv_env()
+ env["VIRTUAL_ENV"] = str(PROJECT_ROOT / "venv")
+ env.pop("UV_NO_CONFIG", None)
- assert uv_env["VIRTUAL_ENV"] == str(PROJECT_ROOT / "venv")
- # Managed store stays the install-scoped runtime dir, not a third-party one.
- assert ".hermes-runtime" in uv_env.get("UV_PYTHON_INSTALL_DIR", "")
- assert uv_env.get("UV_MANAGED_PYTHON") == "1"
- assert uv_env.get("UV_NO_CONFIG") == "1"
+ assert env["VIRTUAL_ENV"] == str(PROJECT_ROOT / "venv")
+ assert env.get("UV_NO_CONFIG") is None
class TestCmdUpdateBranchFallback:
@@ -919,35 +873,6 @@ class TestCmdUpdateZipBranchRefusal:
assert "Downloading latest version" not in out
-def test_is_termux_env_true_for_termux_prefix():
- from hermes_cli import main as hm
-
- assert hm._is_termux_env({"PREFIX": "/data/data/com.termux/files/usr"}) is True
-
-
-def test_load_installable_optional_extras_supports_termux_group(tmp_path, monkeypatch):
- from hermes_cli import main as hm
-
- pyproject = tmp_path / "pyproject.toml"
- pyproject.write_text(
- """
-[project]
-name = "x"
-version = "0.0.0"
-
-[project.optional-dependencies]
-all = ["x[mcp]"]
-termux-all = ["x[termux]", "x[mcp]"]
-mcp = ["mcp>=1"]
-termux = ["rich>=14"]
-""".strip()
- )
- monkeypatch.setattr(hm, "PROJECT_ROOT", tmp_path)
-
- assert hm._load_installable_optional_extras(group="all") == ["mcp"]
- assert hm._load_installable_optional_extras(group="termux-all") == ["termux", "mcp"]
-
-
class TestNodeRuntimeNpmResolution:
"""Regression tests for #30271 — WSL must not run Windows npm against the
Linux checkout, and a failed Node refresh must not report success."""
@@ -1127,8 +1052,7 @@ class TestNodeRuntimeNpmResolution:
patch("hermes_cli.config.load_config", return_value={}),
patch("subprocess.run", side_effect=fail_git_fetch),
patch("urllib.request.urlretrieve", side_effect=write_source_zip),
- patch("hermes_cli.managed_uv.ensure_uv", return_value="uv"),
- patch("hermes_cli.managed_uv.update_managed_uv"),
+ patch("pm.uv", return_value=("uv", dict(os.environ))),
patch(
"tools.skills_sync.sync_skills",
return_value={
diff --git a/tests/hermes_cli/test_cmd_update_docker.py b/tests/hermes_cli/test_cmd_update_docker.py
index a4c52ab2c53..e10e9a34617 100644
--- a/tests/hermes_cli/test_cmd_update_docker.py
+++ b/tests/hermes_cli/test_cmd_update_docker.py
@@ -29,9 +29,10 @@ from hermes_cli.main import _cmd_update_check, cmd_update
@patch("hermes_cli.config.is_managed", return_value=False)
@patch("hermes_cli.config.detect_install_method", return_value="docker")
+@patch("hermes_cli.version_info.get_version_info")
@patch("subprocess.run")
def test_cmd_update_in_docker_prints_guidance_and_exits(
- mock_run, _mock_method, _mock_managed, capsys
+ mock_run, _mock_version, _mock_method, _mock_managed, capsys
):
"""``hermes update`` inside Docker → friendly message + exit 2, no git calls.
diff --git a/tests/hermes_cli/test_doctor_channel_hygiene.py b/tests/hermes_cli/test_doctor_channel_hygiene.py
new file mode 100644
index 00000000000..525ac56fdb1
--- /dev/null
+++ b/tests/hermes_cli/test_doctor_channel_hygiene.py
@@ -0,0 +1,54 @@
+"""Doctor's channel-record hygiene check (_check_channel_record_hygiene).
+
+Report-don't-delete: doctor names the stale config key; the user removes
+it. The staleness shapes themselves are covered in
+tests/hermes_cli/test_update_channel.py::TestDoctorStaleness — this file
+covers the doctor-side wiring: warnings printed, exceptions swallowed
+into a warning, silence on a clean config.
+"""
+
+from unittest.mock import patch
+
+from hermes_cli.doctor import _check_channel_record_hygiene
+
+
+def test_clean_config_prints_nothing(capsys):
+ with (
+ patch("hermes_cli.config.load_config", return_value={}),
+ ):
+ _check_channel_record_hygiene()
+ assert capsys.readouterr().out == ""
+
+
+def test_stale_records_warned_with_reason_texts(tmp_path, capsys, monkeypatch):
+ home = tmp_path / ".hermes"
+ home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ gone = tmp_path / "gone"
+ live = tmp_path / "live"
+ live.mkdir()
+ config = {
+ "update": {
+ "installs": {
+ # missing: nothing at the recorded path
+ "deadbeefdeadbeef": {"path": str(gone), "channel": "main"},
+ # replaced: path exists but keys to a different sha16
+ "0" * 16: {"path": str(live), "channel": "stable"},
+ }
+ }
+ }
+ with patch("hermes_cli.config.load_config", return_value=config):
+ _check_channel_record_hygiene()
+ out = capsys.readouterr().out
+ assert "Stale channel record: deadbeefdeadbeef" in out
+ assert "safe to remove update.installs.deadbeefdeadbeef" in out
+ assert f"Stale channel record: {'0' * 16}" in out
+ assert "different install now" in out
+
+
+def test_unreadable_config_degrades_to_a_warning(capsys):
+ with patch("hermes_cli.config.load_config", side_effect=RuntimeError("boom")):
+ _check_channel_record_hygiene()
+ out = capsys.readouterr().out
+ assert "Channel-record hygiene unreadable" in out
+ assert "boom" in out
diff --git a/tests/hermes_cli/test_doctor_legacy_checkout.py b/tests/hermes_cli/test_doctor_legacy_checkout.py
new file mode 100644
index 00000000000..3ff8a0477df
--- /dev/null
+++ b/tests/hermes_cli/test_doctor_legacy_checkout.py
@@ -0,0 +1,100 @@
+"""Tests for the legacy-desktop-checkout report in hermes doctor."""
+
+import json
+import subprocess
+
+import pytest
+
+import hermes_cli.doctor as doctor
+from hermes_cli.doctor import check_legacy_desktop_checkout
+
+
+def _git(cwd, *args):
+ result = subprocess.run(
+ ["git", "-C", str(cwd), *args],
+ capture_output=True, text=True, encoding="utf-8",
+ )
+ assert result.returncode == 0, f"git {args} failed: {result.stderr}"
+ return result.stdout.strip()
+
+
+def embedded_context(tmp_path, monkeypatch):
+ """Running tree = sealed desktop-app; legacy checkout at the managed root."""
+ bundle = tmp_path / "bundle" / "repo"
+ bundle.mkdir(parents=True)
+ # The code-scoped stamp (hermes_cli.steward.BUILD_INFO_NAME).
+ (bundle / "install-stamp.json").write_text(
+ json.dumps({"commit": "a" * 40, "distribution": "desktop-app", "updateMechanism": "electron-updater"})
+ )
+ import hermes_cli.main as hermes_main
+
+ monkeypatch.setattr(hermes_main, "PROJECT_ROOT", bundle)
+
+ home = tmp_path / ".hermes"
+ checkout = home / "hermes-agent"
+ checkout.mkdir(parents=True)
+ _git(checkout, "init", "-b", "main")
+ _git(checkout, "config", "user.email", "[email protected]")
+ _git(checkout, "config", "user.name", "test")
+ (checkout / "f.txt").write_text("x\n")
+ _git(checkout, "add", ".")
+ _git(checkout, "commit", "-m", "initial")
+ monkeypatch.setattr(doctor, "HERMES_HOME", home)
+ return checkout
+
+
+class TestLegacyDesktopCheckout:
+ def test_pristine_checkout_gets_a_deletion_suggestion(self, embedded_context, capsys):
+ check_legacy_desktop_checkout()
+ out = capsys.readouterr().out
+ assert "Unused checkout" in out
+ assert "rm -rf" in out
+
+ def test_dirty_checkout_warns_and_suggests_nothing(self, embedded_context, capsys):
+ (embedded_context / "f.txt").write_text("local work\n")
+ check_legacy_desktop_checkout()
+ out = capsys.readouterr().out
+ assert "holds local work" in out
+ assert "rm -rf" not in out
+ # And the tree is untouched.
+ assert (embedded_context / "f.txt").read_text() == "local work\n"
+
+ def test_branched_checkout_counts_as_local_work(self, embedded_context, capsys):
+ _git(embedded_context, "checkout", "-b", "feature/y")
+ check_legacy_desktop_checkout()
+ out = capsys.readouterr().out
+ assert "holds local work" in out
+ assert "rm -rf" not in out
+
+ def test_stashed_checkout_counts_as_local_work(self, embedded_context, capsys):
+ (embedded_context / "f.txt").write_text("stash me\n")
+ _git(embedded_context, "stash")
+ check_legacy_desktop_checkout()
+ out = capsys.readouterr().out
+ assert "holds local work" in out
+ assert "rm -rf" not in out
+
+ def test_silent_without_a_checkout(self, embedded_context, tmp_path, monkeypatch, capsys):
+ import shutil
+ import stat
+
+ def _force_rm(func, path, _exc):
+ # Windows: git object files are read-only; clear the bit and retry.
+ import os
+
+ os.chmod(path, stat.S_IWRITE)
+ func(path)
+
+ shutil.rmtree(embedded_context, onerror=_force_rm)
+ check_legacy_desktop_checkout()
+ assert capsys.readouterr().out == ""
+
+ def test_silent_when_running_from_a_git_checkout(self, embedded_context, monkeypatch, capsys):
+ # A git-managed install (dev tree or ejected) is not embedded; the
+ # checkout at the managed root might BE the running tree.
+ import hermes_cli.main as hermes_main
+
+ monkeypatch.setattr(hermes_main, "PROJECT_ROOT", embedded_context)
+ check_legacy_desktop_checkout()
+ assert capsys.readouterr().out == ""
diff --git a/tests/hermes_cli/test_doctor_pm_store_probe.py b/tests/hermes_cli/test_doctor_pm_store_probe.py
new file mode 100644
index 00000000000..55c181f2115
--- /dev/null
+++ b/tests/hermes_cli/test_doctor_pm_store_probe.py
@@ -0,0 +1,50 @@
+"""Doctor reports the tools Hermes would actually run — the pm store first.
+
+Hermes runs pinned tools out of the pm store. Nothing puts the store on an
+interactive shell's PATH, so a PATH-only probe reports a perfectly healthy
+managed install as "not found", and silently skips the checks that depend
+on the tool being present.
+"""
+from __future__ import annotations
+
+from hermes_cli import doctor
+
+
+class TestPmToolPath:
+ """_pm_tool_path answers from facts.json + the pm store, nothing else."""
+
+ def _store(self, tmp_path, monkeypatch, facts: dict):
+ import json
+
+ store = tmp_path / "tools"
+ store.mkdir(parents=True, exist_ok=True)
+ (store / "facts.json").write_text(
+ json.dumps({"schema": 1, "packages": facts}), encoding="utf-8"
+ )
+ monkeypatch.setenv("HERMES_RUNTIME_DIR", str(store))
+ return store
+
+ def test_staged_tool_resolves_to_its_store_binary(self, tmp_path, monkeypatch):
+ import sys
+
+ store = self._store(
+ tmp_path, monkeypatch,
+ {"ripgrep": {"entry": "ripgrep-15.0.0-test", "version": "15.0.0", "env": {}}},
+ )
+ entry = store / "ripgrep-15.0.0-test"
+ entry.mkdir()
+ binary = entry / ("rg.exe" if sys.platform == "win32" else "rg")
+ binary.write_text("", encoding="utf-8")
+
+ assert doctor._pm_tool_path("ripgrep") == binary
+
+ def test_unstaged_tool_resolves_to_none(self, tmp_path, monkeypatch):
+ self._store(tmp_path, monkeypatch, {})
+ assert doctor._pm_tool_path("ripgrep") is None
+
+ def test_recorded_but_deleted_binary_resolves_to_none(self, tmp_path, monkeypatch):
+ self._store(
+ tmp_path, monkeypatch,
+ {"ripgrep": {"entry": "ripgrep-15.0.0-test", "version": "15.0.0", "env": {}}},
+ )
+ assert doctor._pm_tool_path("ripgrep") is None
diff --git a/tests/hermes_cli/test_dump_git_commit.py b/tests/hermes_cli/test_dump_git_commit.py
index 47c9cd9cb9d..76dcd6762bb 100644
--- a/tests/hermes_cli/test_dump_git_commit.py
+++ b/tests/hermes_cli/test_dump_git_commit.py
@@ -1,75 +1,123 @@
"""Tests for hermes_cli.dump._get_git_commit — git SHA resolution for ``hermes dump``.
``hermes dump`` prints the running commit so support bug reports identify the
-exact version. Source installs resolve it live via ``git rev-parse``; the
-published Docker image excludes ``.git`` and falls back to the baked SHA
-written by the Dockerfile's ``HERMES_GIT_SHA`` build-arg.
+exact version. Source installs resolve it live via git; packaged builds
+(Docker, Nix) use the install stamp. Both paths go through
+``version_info.get_version_info()``.
-These tests cover both paths plus the failure modes (no git, no baked file).
+These tests cover both paths plus the failure modes (no stamp, no git).
"""
from unittest.mock import MagicMock, patch
+from hermes_cli.version_info import VersionInfo, _reset_version_info_cache
+
+
+def setup_function():
+ _reset_version_info_cache()
+
def test_get_git_commit_uses_live_git_when_available(tmp_path):
- """Source install: ``git rev-parse --short=8 HEAD`` wins; no fallback."""
+ """Source install: version_info resolves commit from live git."""
from hermes_cli import dump
repo_dir = tmp_path / "repo"
repo_dir.mkdir()
- git_result = MagicMock(returncode=0, stdout="deadbeef\n")
- # build_info should NOT be consulted when live git succeeds.
- with patch("hermes_cli.dump.subprocess.run", return_value=git_result) as mock_run, \
- patch("hermes_cli.build_info.get_build_sha") as mock_build:
+ with patch("hermes_cli.version_info._resolve_stamp_file", lambda: None), \
+ patch("hermes_cli.version_info._resolve_repo_dir", lambda: repo_dir), \
+ patch("hermes_cli.version_info._git_version_info",
+ return_value=VersionInfo("0.19.0", "0.19.0+3", 3, "deadbeef" * 5, "main", "git")):
commit = dump._get_git_commit(repo_dir)
assert commit == "deadbeef"
- mock_run.assert_called_once()
- mock_build.assert_not_called()
-def test_get_git_commit_output_format_identical_between_sources(tmp_path):
- """Regression guard: live-git and baked-SHA outputs share the same shape.
+def test_get_git_commit_uses_stamp_when_no_git(tmp_path):
+ """Docker/Nix: version_info resolves commit from the install stamp."""
+ from hermes_cli import dump
- Ben explicitly asked for identical output between Docker and source installs
- so support tooling that parses ``hermes dump`` doesn't have to special-case
- container builds. Both paths must return a bare 8-char SHA — no prefix,
- no suffix, no annotation.
- """
+ repo_dir = tmp_path / "no-git-here"
+ repo_dir.mkdir()
+
+ with patch("hermes_cli.version_info._resolve_stamp_file", lambda: tmp_path / "stamp.json"), \
+ patch("hermes_cli.version_info._resolve_repo_dir", lambda: None), \
+ patch("hermes_cli.version_info._stamp_version_info",
+ return_value=VersionInfo("0.19.0", "0.19.0", None, "cafef00d" * 5, None, "docker")):
+ commit = dump._get_git_commit(repo_dir)
+
+ assert commit == "cafef00d"
+
+
+def test_get_git_commit_returns_unknown_when_neither_source_available(tmp_path):
+ """Pip-installed wheel: no stamp, no git → '(unknown)'."""
+ from hermes_cli import dump
+
+ repo_dir = tmp_path / "repo"
+ repo_dir.mkdir()
+
+ with patch("hermes_cli.version_info._resolve_stamp_file", lambda: None), \
+ patch("hermes_cli.version_info._resolve_repo_dir", lambda: None):
+ commit = dump._get_git_commit(repo_dir)
+
+ assert commit == "(unknown)"
+
+
+def test_get_git_commit_output_format_identical_between_sources(tmp_path):
+ """Regression guard: live-git and stamp outputs share the same shape."""
from hermes_cli import dump
repo_dir = tmp_path / "repo"
repo_dir.mkdir()
# Live-git path.
- git_result = MagicMock(returncode=0, stdout="b2f477a3\n")
- with patch("hermes_cli.dump.subprocess.run", return_value=git_result):
+ with patch("hermes_cli.version_info._resolve_stamp_file", lambda: None), \
+ patch("hermes_cli.version_info._resolve_repo_dir", lambda: repo_dir), \
+ patch("hermes_cli.version_info._git_version_info",
+ return_value=VersionInfo("0.19.0", "0.19.0+3", 3, "b2f477a3" * 5, "main", "git")):
+ _reset_version_info_cache()
live = dump._get_git_commit(repo_dir)
- # Baked-SHA path.
- failed = MagicMock(returncode=128, stdout="")
- with patch("hermes_cli.dump.subprocess.run", return_value=failed), \
- patch("hermes_cli.build_info.get_build_sha", return_value="b2f477a3"):
+ # Stamp path.
+ with patch("hermes_cli.version_info._resolve_stamp_file", lambda: tmp_path / "stamp.json"), \
+ patch("hermes_cli.version_info._resolve_repo_dir", lambda: None), \
+ patch("hermes_cli.version_info._stamp_version_info",
+ return_value=VersionInfo("0.19.0", "0.19.0", None, "b2f477a3" * 5, None, "docker")):
+ _reset_version_info_cache()
baked = dump._get_git_commit(repo_dir)
assert live == baked == "b2f477a3"
- # Same length, same charset — no decoration in either branch.
assert len(live) == 8
assert all(c in "0123456789abcdef" for c in live)
-def test_get_git_commit_date_empty_when_git_fails(tmp_path):
- """Docker image / pip wheel: no git → '' so the dump line drops the date."""
+def test_get_git_commit_date_uses_version_info(tmp_path):
+ """Source install: version_info carries the commit date from live git."""
from hermes_cli import dump
- repo_dir = tmp_path / "no-git-here"
+ repo_dir = tmp_path / "repo"
repo_dir.mkdir()
- failed = MagicMock(returncode=128, stdout="")
- with patch("hermes_cli.dump.subprocess.run", return_value=failed):
+ with patch("hermes_cli.version_info._resolve_stamp_file", lambda: None), \
+ patch("hermes_cli.version_info._resolve_repo_dir", lambda: repo_dir), \
+ patch("hermes_cli.version_info._git_version_info",
+ return_value=VersionInfo("0.19.0", "0.19.0+3", 3, "deadbeef" * 5, "main", "git", False, 1718662620)):
+ _reset_version_info_cache()
date = dump._get_git_commit_date(repo_dir)
- assert date == ""
+ assert date == "2024-06-17"
+def test_get_git_commit_date_empty_when_unknown(tmp_path):
+ """Docker/pip: no git, no stamp → '' so the dump line drops the date."""
+ from hermes_cli import dump
+
+ repo_dir = tmp_path / "no-git-here"
+ repo_dir.mkdir()
+
+ with patch("hermes_cli.version_info._resolve_stamp_file", lambda: None), \
+ patch("hermes_cli.version_info._resolve_repo_dir", lambda: None):
+ _reset_version_info_cache()
+ date = dump._get_git_commit_date(repo_dir)
+
+ assert date == ""
diff --git a/tests/hermes_cli/test_fleet_matrix_down_state.py b/tests/hermes_cli/test_fleet_matrix_down_state.py
index 0519e30c259..f2c4942743b 100644
--- a/tests/hermes_cli/test_fleet_matrix_down_state.py
+++ b/tests/hermes_cli/test_fleet_matrix_down_state.py
@@ -19,7 +19,7 @@ def _setup(monkeypatch, tmp_path, record: dict):
home = tmp_path / ".hermes"
home.mkdir(exist_ok=True)
monkeypatch.setattr(
- "hermes_cli.build_info.get_code_identity",
+ "hermes_cli.version_info.get_code_identity",
lambda refresh=False: {"sha": "HEADSHA", "version": "1.0"},
)
monkeypatch.setattr("hermes_cli.profiles._get_default_hermes_home", lambda: home)
diff --git a/tests/hermes_cli/test_gateway_service.py b/tests/hermes_cli/test_gateway_service.py
index 6c707f325be..d7e27c95a30 100644
--- a/tests/hermes_cli/test_gateway_service.py
+++ b/tests/hermes_cli/test_gateway_service.py
@@ -1,5 +1,6 @@
"""Tests for gateway service management helpers."""
+import json
import os
import plistlib
import subprocess
@@ -1151,9 +1152,59 @@ class TestGatewaySystemServiceRouting:
class TestDetectVenvDir:
- """Tests for _detect_venv_dir() virtualenv detection."""
+ """Tests for _detect_venv_dir() virtualenv detection.
+
+ pm's facts/store resolution is the primary source; each legacy-probe
+ test isolates it (``_pm_runtime_venv_dir`` patched to None) so the
+ fallbacks are exercised deterministically regardless of whether the
+ host checkout has pm-provisioned a venv.
+ """
+
+ def test_resolves_pm_provisioned_venv_without_virtual_env(self, tmp_path, monkeypatch):
+ """No sys.prefix venv, no VIRTUAL_ENV anywhere — the pm-provisioned
+ venv (facts + store layout) is the answer."""
+ monkeypatch.setattr("sys.prefix", "/usr")
+ monkeypatch.setattr("sys.base_prefix", "/usr")
+ monkeypatch.delenv("VIRTUAL_ENV", raising=False)
+ monkeypatch.delenv("HERMES_RUNTIME_DIR", raising=False)
+ monkeypatch.setattr(gateway_cli, "PROJECT_ROOT", tmp_path)
+
+ payload = tmp_path / "payload"
+ store = payload / "tools"
+ venv = payload / "venv"
+ venv.mkdir(parents=True)
+ (payload / "manifest.json").write_text("{}", encoding="utf-8")
+ (store / "facts.json").write_text(
+ json.dumps(
+ {"schema": 1, "packages": {"venv": {"stamp": "abc", "extras": []}}}
+ ),
+ encoding="utf-8",
+ )
+ monkeypatch.setenv("HERMES_RUNTIME_DIR", str(store))
+
+ assert gateway_cli._detect_venv_dir() == venv
+
+ def test_pm_resolution_none_without_venv_fact(self, tmp_path, monkeypatch):
+ """A store without a venv fact does not vouch — no pm answer."""
+ monkeypatch.setattr("sys.prefix", "/usr")
+ monkeypatch.setattr("sys.base_prefix", "/usr")
+ monkeypatch.delenv("VIRTUAL_ENV", raising=False)
+ monkeypatch.setattr(gateway_cli, "PROJECT_ROOT", tmp_path)
+
+ payload = tmp_path / "payload"
+ store = payload / "tools"
+ (payload / "venv").mkdir(parents=True)
+ (payload / "manifest.json").write_text("{}", encoding="utf-8")
+ (store / "facts.json").write_text(
+ json.dumps({"schema": 1, "packages": {}}), encoding="utf-8"
+ )
+ monkeypatch.setenv("HERMES_RUNTIME_DIR", str(store))
+
+ assert gateway_cli._detect_venv_dir() is None
def test_detects_active_virtualenv_via_sys_prefix(self, tmp_path, monkeypatch):
+ # Legacy probe (pre-pm environments): isolated from pm resolution.
+ monkeypatch.setattr(gateway_cli, "_pm_runtime_venv_dir", lambda: None)
venv_path = tmp_path / "my-custom-venv"
venv_path.mkdir()
monkeypatch.setattr("sys.prefix", str(venv_path))
@@ -1164,6 +1215,7 @@ class TestDetectVenvDir:
def test_falls_back_to_dot_venv_directory(self, tmp_path, monkeypatch):
# Not inside a virtualenv
+ monkeypatch.setattr(gateway_cli, "_pm_runtime_venv_dir", lambda: None)
monkeypatch.setattr("sys.prefix", "/usr")
monkeypatch.setattr("sys.base_prefix", "/usr")
monkeypatch.delenv("VIRTUAL_ENV", raising=False)
@@ -1177,6 +1229,7 @@ class TestDetectVenvDir:
def test_returns_none_when_no_virtualenv(self, tmp_path, monkeypatch):
+ monkeypatch.setattr(gateway_cli, "_pm_runtime_venv_dir", lambda: None)
monkeypatch.setattr("sys.prefix", "/usr")
monkeypatch.setattr("sys.base_prefix", "/usr")
monkeypatch.delenv("VIRTUAL_ENV", raising=False)
@@ -1186,6 +1239,35 @@ class TestDetectVenvDir:
assert result is None
+class TestServicePathDirsPmVenv:
+ """_build_service_path_dirs() must derive the venv bin dir from pm's
+ facts/store resolution, not from sys.prefix sniffing (which degrades
+ under no-boot-through-venv, where sys.prefix == sys.base_prefix)."""
+
+ def test_includes_pm_venv_bin_without_sys_prefix_venv(self, tmp_path, monkeypatch):
+ monkeypatch.setattr("sys.prefix", "/usr")
+ monkeypatch.setattr("sys.base_prefix", "/usr")
+ monkeypatch.delenv("VIRTUAL_ENV", raising=False)
+ monkeypatch.delenv("HERMES_RUNTIME_DIR", raising=False)
+
+ payload = tmp_path / "payload"
+ store = payload / "tools"
+ venv_bin = payload / "venv" / "bin"
+ venv_bin.mkdir(parents=True)
+ (payload / "manifest.json").write_text("{}", encoding="utf-8")
+ (store / "facts.json").write_text(
+ json.dumps(
+ {"schema": 1, "packages": {"venv": {"stamp": "abc", "extras": []}}}
+ ),
+ encoding="utf-8",
+ )
+ monkeypatch.setenv("HERMES_RUNTIME_DIR", str(store))
+
+ dirs = gateway_cli._build_service_path_dirs(project_root=tmp_path / "project")
+
+ assert str(venv_bin) in dirs
+
+
def _seed_pm_node_facts(hermes_root):
"""Write a pm installed-state file recording node/npm store entries.
diff --git a/tests/hermes_cli/test_gui_command.py b/tests/hermes_cli/test_gui_command.py
index a3480f96d10..d2c0eabde48 100644
--- a/tests/hermes_cli/test_gui_command.py
+++ b/tests/hermes_cli/test_gui_command.py
@@ -140,18 +140,43 @@ def test_gui_install_env_prepends_managed_node_on_bare_path(tmp_path, monkeypatc
the parent PATH is stripped, so the install env MUST carry the Hermes-managed
Node ahead of that bare PATH or the install dies with ``node: not found``.
"""
+ import json
import os
- from hermes_constants import iter_hermes_node_dirs
-
root = _make_desktop_tree(tmp_path)
monkeypatch.setattr(cli_main, "PROJECT_ROOT", root)
_make_packaged_executable(root, monkeypatch)
- # A managed Node tree on disk so with_hermes_node_path() actually prepends it.
+ # A pm-installed Node/npm on disk so with_hermes_node_path() actually
+ # prepends the store dirs.
home = tmp_path / "hermes-home"
- (home / "node" / "bin").mkdir(parents=True)
+ store_root = home / "tools"
+ node_entry = store_root / "node-v22.0.0"
+ npm_entry = store_root / "npm-9.0.0" / "bin"
+ node_entry.mkdir(parents=True)
+ npm_entry.mkdir(parents=True)
+ (store_root / "facts.json").write_text(
+ json.dumps(
+ {
+ "schema": 1,
+ "packages": {
+ "node": {
+ "entry": "node-v22.0.0",
+ "version": "22.0.0",
+ "env": {"PATH": ["{{store}}/node-v22.0.0"]},
+ },
+ "npm": {
+ "entry": "npm-9.0.0",
+ "version": "9.0.0",
+ "env": {"PATH": ["{{store}}/npm-9.0.0/bin"]},
+ },
+ },
+ }
+ ),
+ encoding="utf-8",
+ )
monkeypatch.setenv("HERMES_HOME", str(home))
+ monkeypatch.setenv("HERMES_RUNTIME_DIR", str(store_root))
# Simulate the stripped PATH the desktop updater chain hands us.
monkeypatch.setenv("PATH", os.pathsep.join(["/usr/bin", "/bin"]))
@@ -174,12 +199,15 @@ def test_gui_install_env_prepends_managed_node_on_bare_path(tmp_path, monkeypatc
pytest.raises(SystemExit):
cli_main.cmd_gui(_ns(skip_build=False))
- managed_dirs = [str(p) for p in iter_hermes_node_dirs() if p.is_dir()]
- assert managed_dirs, "managed node tree not discovered"
+ managed_dirs = [str(npm_entry), str(node_entry)]
install_env = mock_install.call_args.kwargs["env"]
- path_parts = install_env["PATH"].split(os.pathsep)
- assert path_parts[: len(managed_dirs)] == managed_dirs
- assert "/usr/bin" in path_parts # the bare updater PATH is preserved, just after managed Node
+ path_parts = [
+ os.path.normpath(p) for p in install_env["PATH"].split(os.pathsep)
+ ]
+ assert path_parts[: len(managed_dirs)] == [
+ os.path.normpath(d) for d in managed_dirs
+ ]
+ assert os.path.normpath("/usr/bin") in path_parts # the bare updater PATH is preserved, just after managed Node
diff --git a/tests/hermes_cli/test_install_bucket_separation.py b/tests/hermes_cli/test_install_bucket_separation.py
new file mode 100644
index 00000000000..2b3e40e3330
--- /dev/null
+++ b/tests/hermes_cli/test_install_bucket_separation.py
@@ -0,0 +1,85 @@
+"""Uninstall and profile cloning respect the install/profile bucket split.
+
+Runtime artifacts belong to an install; config, sessions and skills belong
+to a profile. Uninstall removes the former (in either mode — they are not
+data); profile clone/export never copies them.
+"""
+
+import pytest
+
+from hermes_cli.uninstall import remove_legacy_runtime_trees
+
+
+class TestRemoveLegacyRuntimeTrees:
+ def test_removes_a_pre_split_node_tree(self, tmp_path):
+ home = tmp_path / "home"
+ (home / "node" / "bin").mkdir(parents=True)
+ (home / "node" / "bin" / "node").write_text("#!/bin/sh\n", encoding="utf-8")
+
+ removed = remove_legacy_runtime_trees(home)
+
+ assert (home / "node") not in [p for p in home.iterdir()]
+ assert removed == [home / "node"]
+
+ def test_removes_only_the_uv_binary_not_the_whole_bin_dir(self, tmp_path):
+ """A user's own scripts live in bin/ — deleting the directory would
+ take them with it."""
+ home = tmp_path / "home"
+ (home / "bin").mkdir(parents=True)
+ (home / "bin" / "uv").write_text("#!/bin/sh\n", encoding="utf-8")
+ (home / "bin" / "my-script").write_text("#!/bin/sh\n", encoding="utf-8")
+
+ removed = remove_legacy_runtime_trees(home)
+
+ assert removed == [home / "bin" / "uv"]
+ assert (home / "bin").is_dir()
+ assert (home / "bin" / "my-script").is_file()
+
+ def test_never_touches_profile_state(self, tmp_path):
+ home = tmp_path / "home"
+ home.mkdir()
+ for name in ("config.yaml", "auth.json", "SOUL.md"):
+ (home / name).write_text("keep me", encoding="utf-8")
+ for name in ("sessions", "skills", "memories", "profiles"):
+ (home / name).mkdir()
+
+ remove_legacy_runtime_trees(home)
+
+ for name in ("config.yaml", "auth.json", "SOUL.md"):
+ assert (home / name).is_file(), name
+ for name in ("sessions", "skills", "memories", "profiles"):
+ assert (home / name).is_dir(), name
+
+ def test_no_runtime_trees_is_a_quiet_no_op(self, tmp_path):
+ home = tmp_path / "home"
+ home.mkdir()
+ assert remove_legacy_runtime_trees(home) == []
+
+
+class TestProfileCopyExclusions:
+ @pytest.mark.parametrize(
+ "excluded", [".hermes-runtime", "node", "hermes-agent", "profiles"]
+ )
+ def test_clone_all_excludes_install_artifacts(self, excluded):
+ from hermes_cli.profiles import _CLONE_ALL_DEFAULT_EXCLUDE_ROOT
+
+ assert excluded in _CLONE_ALL_DEFAULT_EXCLUDE_ROOT
+
+ @pytest.mark.parametrize("excluded", [".hermes-runtime", "node"])
+ def test_export_excludes_managed_runtimes(self, excluded):
+ from hermes_cli.profiles import _DEFAULT_EXPORT_EXCLUDE_ROOT
+
+ assert excluded in _DEFAULT_EXPORT_EXCLUDE_ROOT
+
+ @pytest.mark.parametrize("excluded", [".hermes-runtime", "node"])
+ def test_distribution_excludes_managed_runtimes(self, excluded):
+ from hermes_cli.profile_distribution import USER_OWNED_EXCLUDE
+
+ assert excluded in USER_OWNED_EXCLUDE
+
+ def test_profile_state_is_still_copied(self):
+ """The exclusions must not swallow actual profile data."""
+ from hermes_cli.profiles import _CLONE_ALL_DEFAULT_EXCLUDE_ROOT
+
+ for kept in ("config.yaml", "skills", "memories", "SOUL.md"):
+ assert kept not in _CLONE_ALL_DEFAULT_EXCLUDE_ROOT
diff --git a/tests/hermes_cli/test_macos_tcc_anchor.py b/tests/hermes_cli/test_macos_tcc_anchor.py
index f07eff9f4ca..137d51d09b5 100644
--- a/tests/hermes_cli/test_macos_tcc_anchor.py
+++ b/tests/hermes_cli/test_macos_tcc_anchor.py
@@ -139,10 +139,10 @@ class TestEnsureTccAnchor:
def test_install_signs_the_anchor_copy(self, tmp_path, monkeypatch):
_darwin(monkeypatch)
signed = []
- import hermes_cli.managed_uv as managed_uv
+ import hermes_cli.runtime_repair as runtime_repair
monkeypatch.setattr(
- managed_uv, "_macos_sign_managed_python", lambda p: signed.append(Path(p)) or True
+ runtime_repair, "_macos_sign_managed_python", lambda p: signed.append(Path(p)) or True
)
store_bin = _build_store(tmp_path)
root = _build_checkout(tmp_path, store_bin=store_bin)
@@ -359,10 +359,10 @@ class TestEnsureTccAnchor:
assert marker.read_text(encoding="utf-8") == tcc._marker_value(source)
assert not list(venv_bin.glob(".tcc-anchor-source.*"))
- def test_store_root_marker_tracks_managed_uv_constant(self):
+ def test_store_root_marker_tracks_runtime_repair_constant(self):
# The repair-generation store marker must stay derived from
- # managed_uv's directory constant, not drift as a hardcoded string.
- from hermes_cli.managed_uv import _RUNTIME_DIR_NAME
+ # runtime_repair's directory constant, not drift as a hardcoded string.
+ from hermes_cli.runtime_repair import _RUNTIME_DIR_NAME
assert f"/{_RUNTIME_DIR_NAME}/python/" in tcc._STORE_ROOT_MARKERS
diff --git a/tests/hermes_cli/test_post_update.py b/tests/hermes_cli/test_post_update.py
new file mode 100644
index 00000000000..b49f33c6d92
--- /dev/null
+++ b/tests/hermes_cli/test_post_update.py
@@ -0,0 +1,412 @@
+"""post_update step registry: scopes, isolation, and the migrate contract.
+
+These assert behavior contracts, not snapshots: the registries' scopes must
+match what boot_bootstrap gates them with, a failing step must not stop the
+rest, and step_migrate_config must restore its backups when a migration
+fails or does not advance the version.
+"""
+import json
+from pathlib import Path
+
+import pytest
+
+from hermes_cli import post_update
+from hermes_cli.post_update import (
+ HOME_STEPS,
+ MACHINE_STEPS,
+ run_steps,
+ step_migrate_config,
+ step_state_db_guard,
+)
+
+
+# ── registry invariants ──────────────────────────────────────────────
+
+
+def test_registries_are_disjoint_and_named():
+ home_names = {name for name, _ in HOME_STEPS}
+ machine_names = {name for name, _ in MACHINE_STEPS}
+ assert home_names, "home registry must not be empty"
+ assert not (home_names & machine_names)
+ for name, func in (*HOME_STEPS, *MACHINE_STEPS):
+ assert callable(func), name
+
+
+def test_home_steps_cover_the_boot_contract():
+ # boot_bootstrap gates these with the per-home record; the three
+ # user-state concerns (config, skills, state.db) must all be present.
+ names = {name for name, _ in HOME_STEPS}
+ assert {"migrate_config", "sync_skills", "state_db_guard"} <= names
+
+
+# ── run_steps isolation ──────────────────────────────────────────────
+
+
+def test_run_steps_isolates_failures():
+ order = []
+
+ def ok():
+ order.append("ok")
+ return {"ok": True}
+
+ def boom():
+ order.append("boom")
+ raise RuntimeError("nope")
+
+ results = run_steps((("first", boom), ("second", ok)))
+ assert order == ["boom", "ok"] # failure did not stop the run
+ assert results["first"]["ok"] is False
+ assert "nope" in results["first"]["error"]
+ assert results["second"] == {"ok": True}
+
+
+# ── step_migrate_config ──────────────────────────────────────────────
+
+
+def test_migrate_config_noop_when_current(monkeypatch):
+ import hermes_cli.config as cfg
+
+ monkeypatch.setattr(cfg, "check_config_version", lambda: (34, 34))
+ result = step_migrate_config()
+ assert result == {"ok": True, "skipped": "up-to-date"}
+
+
+def test_migrate_config_restores_backup_when_version_does_not_advance(
+ tmp_path, monkeypatch
+):
+ import hermes_cli.config as cfg
+ import hermes_cli.config_migrations as mig
+
+ config_path = tmp_path / "config.yaml"
+ config_path.write_text("_config_version: 20\n", encoding="utf-8")
+ env_path = tmp_path / ".env"
+
+ floor = getattr(mig, "SUPPORT_FLOOR_VERSION", 12)
+ versions = iter([(max(20, floor), 34), (max(20, floor), 34)])
+ monkeypatch.setattr(cfg, "check_config_version", lambda: next(versions))
+ monkeypatch.setattr(cfg, "get_config_path", lambda: config_path)
+ monkeypatch.setattr(cfg, "get_env_path", lambda: env_path)
+
+ def fake_migrate(**kw):
+ # Corrupt the file; the version check will then report no advance.
+ config_path.write_text("_config_version: 20\nbroken: true\n", encoding="utf-8")
+
+ monkeypatch.setattr(cfg, "migrate_config", lambda **kw: fake_migrate(**kw))
+
+ with pytest.raises(RuntimeError, match="did not advance"):
+ step_migrate_config()
+
+ # Original content restored from the backup.
+ assert config_path.read_text(encoding="utf-8") == "_config_version: 20\n"
+ backups = list(tmp_path.glob("config.yaml.bak-*"))
+ assert backups, "backup file must exist"
+
+
+def test_migrate_config_restores_backup_on_exception(tmp_path, monkeypatch):
+ import hermes_cli.config as cfg
+ import hermes_cli.config_migrations as mig
+
+ config_path = tmp_path / "config.yaml"
+ config_path.write_text("_config_version: 20\n", encoding="utf-8")
+
+ floor = getattr(mig, "SUPPORT_FLOOR_VERSION", 12)
+ monkeypatch.setattr(cfg, "check_config_version", lambda: (max(20, floor), 34))
+ monkeypatch.setattr(cfg, "get_config_path", lambda: config_path)
+ monkeypatch.setattr(cfg, "get_env_path", lambda: tmp_path / ".env")
+
+ def exploding_migrate(**kw):
+ config_path.write_text("half-written garbage", encoding="utf-8")
+ raise RuntimeError("migration blew up")
+
+ monkeypatch.setattr(cfg, "migrate_config", lambda **kw: exploding_migrate(**kw))
+
+ with pytest.raises(RuntimeError, match="blew up"):
+ step_migrate_config()
+ assert config_path.read_text(encoding="utf-8") == "_config_version: 20\n"
+
+
+# ── step_state_db_guard ──────────────────────────────────────────────
+
+
+def test_state_db_guard_skips_missing_db(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ assert step_state_db_guard() == {"ok": True, "skipped": "no-state-db"}
+
+
+def test_state_db_guard_flags_corrupt_db(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ (tmp_path / "state.db").write_text("this is not sqlite", encoding="utf-8")
+ result = step_state_db_guard()
+ assert result["ok"] is False
+ assert result.get("error")
+
+
+def test_state_db_guard_passes_valid_db(tmp_path, monkeypatch):
+ import sqlite3
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ conn = sqlite3.connect(tmp_path / "state.db")
+ conn.execute("CREATE TABLE t (x)")
+ conn.commit()
+ conn.close()
+ assert step_state_db_guard() == {"ok": True}
+
+
+# ── machine-step registry ────────────────────────────────────────────
+
+
+def test_provisioning_is_the_machine_scope_driver_path():
+ """cua-driver has no refresh step of its own — provisioning carries it.
+
+ Pinned managed tools ride pm's lockfile; the provision_runtimes sweep
+ moves a pin bump exactly like node or ripgrep, and a second mechanism
+ would be a second authority on a tool's version.
+ """
+ names = [name for name, _ in post_update.MACHINE_STEPS]
+ assert "provision_runtimes" in names
+ assert not any("cua" in name for name in names)
+
+
+def test_provision_runtimes_is_a_noop_when_pm_is_current(monkeypatch):
+ import pm
+
+ monkeypatch.setattr(pm, "check", lambda: [])
+ assert post_update.step_provision_runtimes() == {"ok": True, "skipped": "current"}
+
+
+def test_provision_runtimes_reensures_only_what_pm_names(monkeypatch):
+ import importlib
+
+ import pm
+
+ # pm/__init__ rebinds the name `pm.ensure` to the FUNCTION; the module
+ # object (whose attrs step_provision_runtimes imports at call time)
+ # comes from sys.modules.
+ pm_ensure = importlib.import_module("pm.ensure")
+
+ ensured = []
+ monkeypatch.setattr(pm, "check", lambda: ["node: not installed or outdated", "venv: out of sync with uv.lock"])
+ monkeypatch.setattr(pm_ensure, "sealed", lambda: False)
+ monkeypatch.setattr(pm_ensure, "lazy_installs_allowed", lambda: True)
+ monkeypatch.setattr(pm, "ensure", lambda name, explicit=False: ensured.append((name, explicit)))
+ monkeypatch.setattr(pm, "sync_venv", lambda explicit=False: ensured.append(("venv", explicit)))
+
+ result = post_update.step_provision_runtimes()
+
+ assert result["ok"] is True
+ assert ("node", True) in ensured and ("venv", True) in ensured
+
+
+def test_provision_runtimes_respects_the_lazy_install_policy(monkeypatch):
+ import importlib
+
+ import pm
+
+ pm_ensure = importlib.import_module("pm.ensure")
+
+ monkeypatch.setattr(pm, "check", lambda: ["node: not installed or outdated"])
+ monkeypatch.setattr(pm_ensure, "sealed", lambda: False)
+ monkeypatch.setattr(pm_ensure, "lazy_installs_allowed", lambda: False)
+ result = post_update.step_provision_runtimes()
+ assert result == {"ok": True, "skipped": "lazy-installs-disabled"}
+
+
+# ── __main__ entry ───────────────────────────────────────────────────
+
+
+def test_main_reports_failure_in_exit_code(monkeypatch):
+ monkeypatch.setattr(
+ post_update, "HOME_STEPS",
+ (("bad", lambda: (_ for _ in ()).throw(RuntimeError("x"))),),
+ )
+ monkeypatch.setattr(post_update, "MACHINE_STEPS", ())
+ assert post_update.main(["--scope", "home"]) == 1
+
+
+def test_main_scope_selects_registries(monkeypatch):
+ ran = []
+ monkeypatch.setattr(
+ post_update, "HOME_STEPS", (("h", lambda: ran.append("h") or {"ok": True}),)
+ )
+ monkeypatch.setattr(
+ post_update, "MACHINE_STEPS", (("m", lambda: ran.append("m") or {"ok": True}),)
+ )
+ assert post_update.main(["--scope", "home"]) == 0
+ assert ran == ["h"]
+ ran.clear()
+ assert post_update.main(["--scope", "all"]) == 0
+ assert ran == ["h", "m"]
+
+
+# ── --update-phase runner mode ───────────────────────────────────────
+
+
+def test_update_phase_runs_shared_registry_and_writes_boot_records(
+ tmp_path, monkeypatch
+):
+ """`hermes update` and boot bootstrap share ONE registry: the update
+ phase runs HOME_STEPS + MACHINE_STEPS and records the new identity so
+ the next boot's bootstrap skips."""
+ from hermes_cli import boot_bootstrap
+
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+
+ root = tmp_path / "payload"
+ root.mkdir()
+ (root / "install-stamp.json").write_text(
+ json.dumps({"commit": "cafe1234", "payload": "full", "updateMechanism": "electron-updater"})
+ )
+ monkeypatch.setattr(boot_bootstrap, "default_project_root", lambda: root)
+
+ ran = []
+ monkeypatch.setattr(
+ post_update, "HOME_STEPS", (("h", lambda: ran.append("h") or {"ok": True}),)
+ )
+ monkeypatch.setattr(
+ post_update, "MACHINE_STEPS", (("m", lambda: ran.append("m") or {"ok": True}),)
+ )
+
+ rc = post_update.main(["--update-phase", "--resumed-after-sync"])
+
+ assert rc == 0
+ assert ran == ["h", "m"] # machine steps inline in an update, not deferred
+ for scope in ("home", "machine"):
+ record = boot_bootstrap.read_last_known(
+ boot_bootstrap.record_path(root, scope)
+ )
+ assert record.get("identity") == "cafe1234"
+ assert boot_bootstrap.needs_bootstrap(root, scope) is None
+
+
+def test_update_phase_propagates_step_failure(tmp_path, monkeypatch):
+ from hermes_cli import boot_bootstrap
+
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ root = tmp_path / "payload"
+ root.mkdir()
+ (root / "install-stamp.json").write_text(
+ json.dumps({"commit": "cafe1234", "payload": "full", "updateMechanism": "electron-updater"})
+ )
+ monkeypatch.setattr(boot_bootstrap, "default_project_root", lambda: root)
+ monkeypatch.setattr(
+ post_update, "HOME_STEPS",
+ (("bad", lambda: (_ for _ in ()).throw(RuntimeError("x"))),),
+ )
+ monkeypatch.setattr(post_update, "MACHINE_STEPS", ())
+
+ assert post_update.main(["--update-phase", "--resumed-after-sync"]) == 1
+ # The record is still written: a broken step must not retrigger the
+ # slow path every boot (the steps re-gate themselves).
+ assert boot_bootstrap.needs_bootstrap(root, "home") is None
+
+
+# ── the re-exec-after-sync handoff ───────────────────────────────────
+
+
+class _Args:
+ """The argparse surface resync_and_reexec consumes."""
+
+ def __init__(self, resumed=False, gateway=False, yes=False, snap=None):
+ self.resumed_after_sync = resumed
+ self.gateway_mode = gateway
+ self.assume_yes = yes
+ self.pre_update_snapshot_id = snap
+
+
+class TestResyncAndReexec:
+ def test_the_resumed_flag_is_absolute(self, monkeypatch):
+ """Loop-proofing: the post-sync process must never sync again,
+ even when the stamp looks stale (another writer could move it
+ between exec and check — argv cannot race)."""
+
+ def no_sync(*a, **k):
+ raise AssertionError("--resumed-after-sync must not sync")
+
+ from hermes_cli import venv_sync
+
+ monkeypatch.setattr(venv_sync, "sync", no_sync)
+
+ assert post_update.resync_and_reexec(_Args(resumed=True)) is None
+
+ def test_current_and_sealed_run_phase2_in_place(self, monkeypatch):
+ """No world change, no exec: the running interpreter is as good
+ as a fresh one and the exec would only cost startup."""
+ from hermes_cli import venv_sync
+
+ for state in ("current", "sealed"):
+ monkeypatch.setattr(
+ venv_sync, "sync", lambda *a, s=state, **k: {"state": s, "ok": True}
+ )
+ monkeypatch.setattr(
+ post_update.os, "execv",
+ lambda *a: (_ for _ in ()).throw(AssertionError("must not exec")),
+ raising=False,
+ )
+ assert post_update.resync_and_reexec(_Args()) is None
+
+ def test_a_failed_sync_stops_the_phase(self, monkeypatch):
+ from hermes_cli import venv_sync
+
+ monkeypatch.setattr(
+ venv_sync,
+ "sync",
+ lambda *a, **k: {"state": "failed", "ok": False, "detail": "uv exited 3"},
+ )
+
+ assert post_update.resync_and_reexec(_Args()) == 1
+
+ def test_a_synced_world_reexecs_with_carried_args(self, monkeypatch):
+ """POSIX: os.execv, same pid, update-lock owner stays correct.
+ Every serialized arg must survive the handoff, plus the resumed
+ marker."""
+ from hermes_cli import venv_sync
+
+ monkeypatch.setattr(
+ venv_sync, "sync", lambda *a, **k: {"state": "synced", "ok": True}
+ )
+ seen = {}
+
+ def fake_execv(exe, argv):
+ seen["exe"] = exe
+ seen["argv"] = argv
+ raise SystemExit(0) # execv never returns; simulate the replacement
+
+ monkeypatch.setattr(post_update.os, "execv", fake_execv, raising=False)
+ monkeypatch.setattr(post_update.os, "name", "posix")
+
+ with pytest.raises(SystemExit):
+ post_update.resync_and_reexec(
+ _Args(gateway=True, yes=True, snap="snap-7")
+ )
+
+ argv = seen["argv"]
+ assert seen["exe"] == post_update.sys.executable
+ assert argv[1:4] == ["-m", "hermes_cli.post_update", "--update-phase"]
+ assert "--resumed-after-sync" in argv
+ assert "--gateway-mode" in argv and "--assume-yes" in argv
+ assert argv[argv.index("--pre-update-snapshot-id") + 1] == "snap-7"
+
+ def test_windows_spawns_and_propagates(self, monkeypatch):
+ """No exec on Windows: spawn + wait + propagate the child's code;
+ the child passes any update lock by ancestry."""
+ from hermes_cli import venv_sync
+
+ monkeypatch.setattr(
+ venv_sync, "sync", lambda *a, **k: {"state": "synced", "ok": True}
+ )
+ monkeypatch.setattr(post_update.os, "name", "nt")
+ seen = {}
+
+ class _Done:
+ returncode = 7
+
+ def fake_run(argv, **kwargs):
+ seen["argv"] = argv
+ return _Done()
+
+ monkeypatch.setattr(post_update.subprocess, "run", fake_run)
+
+ assert post_update.resync_and_reexec(_Args()) == 7
+ assert "--resumed-after-sync" in seen["argv"]
diff --git a/tests/hermes_cli/test_post_update_adoption.py b/tests/hermes_cli/test_post_update_adoption.py
new file mode 100644
index 00000000000..c1f2dfd7383
--- /dev/null
+++ b/tests/hermes_cli/test_post_update_adoption.py
@@ -0,0 +1,109 @@
+"""step_adopt_blessed_checkout — one-time birth certificate for shipped
+stampless installs.
+
+Blessed root + .git + no stamp → write {updateMechanism: self} atomically.
+Anything else — untouched. A read-only tree fails soft (nix-like layouts).
+"""
+import json
+import os
+import stat
+import sys
+
+import pytest
+
+from hermes_cli.post_update import step_adopt_blessed_checkout
+
+
+def blessed_checkout(tmp_path, monkeypatch):
+ """A .git checkout at the blessed $HERMES_HOME/hermes-agent root."""
+ home = tmp_path / ".hermes"
+ root = home / "hermes-agent"
+ root.mkdir(parents=True)
+ (root / ".git").mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ monkeypatch.setenv("HERMES_INSTALL_ROOT", str(root))
+ return root
+
+
+def test_adopts_blessed_stampless_checkout(blessed_checkout):
+ result = step_adopt_blessed_checkout()
+ assert result["ok"] is True
+ assert result.get("adopted") == str(blessed_checkout)
+ stamp = json.loads((blessed_checkout / "install-stamp.json").read_text())
+ assert stamp["updateMechanism"] == "self"
+ assert stamp["source"] == "adoption"
+
+
+def test_adoption_is_idempotent(blessed_checkout):
+ """Second run: the stamp already exists, nothing rewritten."""
+ step_adopt_blessed_checkout()
+ first = (blessed_checkout / "install-stamp.json").read_text()
+ result = step_adopt_blessed_checkout()
+ assert result.get("skipped") == "already-stamped"
+ assert (blessed_checkout / "install-stamp.json").read_text() == first
+
+
+def test_existing_stamp_is_never_touched(blessed_checkout):
+ """Any pre-existing stamp wins — adoption must not clobber richer
+ provenance (an installer-written or build-baked stamp)."""
+ original = json.dumps({"schemaVersion": 2, "updateMechanism": "self", "source": "installer"})
+ (blessed_checkout / "install-stamp.json").write_text(original)
+ result = step_adopt_blessed_checkout()
+ assert result.get("skipped") == "already-stamped"
+ assert (blessed_checkout / "install-stamp.json").read_text() == original
+
+
+def test_non_blessed_checkout_untouched(tmp_path, monkeypatch):
+ """.git anywhere else → never adopted."""
+ home = tmp_path / ".hermes"
+ home.mkdir()
+ dev = tmp_path / "src" / "hermes-agent"
+ dev.mkdir(parents=True)
+ (dev / ".git").mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ monkeypatch.setenv("HERMES_INSTALL_ROOT", str(dev))
+ result = step_adopt_blessed_checkout()
+ assert result.get("skipped") == "not-a-blessed-root"
+ assert not (dev / "install-stamp.json").exists()
+
+
+def test_sealed_tree_untouched(tmp_path, monkeypatch):
+ """No .git → not a checkout, nothing to adopt (sealed trees always
+ ship stamps anyway)."""
+ home = tmp_path / ".hermes"
+ root = home / "hermes-agent"
+ root.mkdir(parents=True)
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ monkeypatch.setenv("HERMES_INSTALL_ROOT", str(root))
+ result = step_adopt_blessed_checkout()
+ assert result.get("skipped") == "not-a-checkout"
+ assert not (root / "install-stamp.json").exists()
+
+
+ sys.platform == "win32" or os.geteuid() == 0,
+ reason="chmod-based read-only dirs are not enforceable on Windows or as root",
+)
+def test_read_only_tree_fails_soft(blessed_checkout):
+ """nix-like read-only tree: debug-log skip, never a crash."""
+ mode = stat.S_IMODE(os.stat(blessed_checkout).st_mode)
+ os.chmod(blessed_checkout, stat.S_IRUSR | stat.S_IXUSR)
+ try:
+ result = step_adopt_blessed_checkout()
+ assert result["ok"] is True
+ assert str(result.get("skipped", "")).startswith("unwritable")
+ finally:
+ os.chmod(blessed_checkout, mode)
+
+
+def test_adoption_keeps_the_steward_verdict_checkout(blessed_checkout):
+ """End to end: the adopted stamp changes update admission, never the
+ steward ladder — a .git tree stays a checkout (sealed_steward None)."""
+ from hermes_cli.steward import sealed_steward
+
+ assert sealed_steward(blessed_checkout) is None
+ step_adopt_blessed_checkout()
+ assert sealed_steward(blessed_checkout) is None
+ stamp = json.loads((blessed_checkout / "install-stamp.json").read_text())
+ assert stamp["updateMechanism"] == "self"
diff --git a/tests/hermes_cli/test_post_update_expose_cli.py b/tests/hermes_cli/test_post_update_expose_cli.py
new file mode 100644
index 00000000000..c7ea6d98508
--- /dev/null
+++ b/tests/hermes_cli/test_post_update_expose_cli.py
@@ -0,0 +1,232 @@
+"""step_expose_cli — the post-update side owns launcher-wrapper repair.
+
+The installers write ~/.local/bin/hermes* once, at install time. This
+step rewrites them when they drift (moved checkout, recreated venv,
+deleted by hand) and — just as load-bearing — REFUSES to touch a
+launcher that belongs to a different install sharing the link dir.
+Real files under a temp HOME; no mocks of the things being tested.
+
+The wrapper-writing surface is POSIX-only by design (Windows exposure is
+installer-owned), so the behaviour tests skip on win32 and the win32
+gate gets its own test.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+from pathlib import Path
+
+import pytest
+
+from hermes_cli import post_update
+
+posix_only = pytest.mark.skipif(
+ sys.platform == "win32", reason="wrapper exposure is POSIX-only; Windows is installer-owned"
+)
+
+
+def _write_bundled_stamp(repo_root: Path) -> None:
+ """The minimal install-stamp.json this branch accepts as a bundled
+ payload (payload marker + a valid updateMechanism)."""
+ repo_root.mkdir(parents=True, exist_ok=True)
+ (repo_root / "install-stamp.json").write_text(
+ json.dumps({"payload": "bundled", "updateMechanism": "electron-updater"})
+ )
+
+
+def fake_install(tmp_path, monkeypatch):
+ """A venv-shaped install root plus an isolated HOME."""
+ home = tmp_path / "home"
+ home.mkdir()
+ monkeypatch.setattr(Path, "home", staticmethod(lambda: home))
+
+ root = tmp_path / "checkout"
+ (root / "venv" / "bin").mkdir(parents=True)
+ (root / "venv" / "bin" / "python").write_text("#!fake\n")
+ (root / "hermes").write_text("# entrypoint\n")
+ (root / "run_agent.py").write_text("# agent\n")
+ monkeypatch.setenv("HERMES_INSTALL_ROOT", str(root))
+ return home, root
+
+
+def test_windows_is_installer_owned(monkeypatch):
+ if sys.platform != "win32":
+ monkeypatch.setattr(post_update.sys, "platform", "win32")
+ assert post_update.step_expose_cli() == {
+ "ok": True,
+ "skipped": "windows-installer-owned",
+ }
+
+
+def test_registered_as_a_home_step():
+ assert ("expose_cli", post_update.step_expose_cli) in post_update.HOME_STEPS
+
+
+@posix_only
+class TestExposeCli:
+ def test_writes_all_three_wrappers_fresh(self, fake_install):
+ home, root = fake_install
+ result = post_update.step_expose_cli()
+ assert result["ok"] is True
+ assert sorted(result["written"]) == ["hermes", "hermes-acp", "hermes-agent"]
+ for name in ("hermes", "hermes-agent", "hermes-acp"):
+ wrapper = home / ".local" / "bin" / name
+ body = wrapper.read_text()
+ assert str(root) in body
+ assert "PYTHONPATH" in body
+ assert os.access(wrapper, os.X_OK)
+
+ def test_second_run_is_a_no_op(self, fake_install):
+ post_update.step_expose_cli()
+ result = post_update.step_expose_cli()
+ assert result == {"ok": True, "written": []}
+
+ def test_repairs_a_stale_same_install_wrapper(self, fake_install):
+ home, root = fake_install
+ post_update.step_expose_cli()
+ wrapper = home / ".local" / "bin" / "hermes"
+ wrapper.write_text(f'#!/bin/sh\nexec "{root}/venv/bin/python" OLD-SHAPE\n')
+ result = post_update.step_expose_cli()
+ assert "hermes" in result["written"]
+ assert "OLD-SHAPE" not in wrapper.read_text()
+
+ def test_leaves_another_installs_wrapper_alone(self, fake_install):
+ home, root = fake_install
+ other = "/somewhere/else/checkout"
+ wrapper_dir = home / ".local" / "bin"
+ wrapper_dir.mkdir(parents=True)
+ foreign = f'#!/bin/sh\nexec "{other}/venv/bin/python" "{other}/hermes" "$@"\n'
+ (wrapper_dir / "hermes").write_text(foreign)
+ result = post_update.step_expose_cli()
+ assert (wrapper_dir / "hermes").read_text() == foreign
+ assert "hermes" not in result["written"]
+ # The other two had no file at all — those ARE written.
+ assert sorted(result["written"]) == ["hermes-acp", "hermes-agent"]
+
+ def test_config_gate_disables(self, fake_install, monkeypatch):
+ monkeypatch.setattr(
+ "hermes_cli.config.load_config",
+ lambda: {"cli": {"expose_on_path": False}},
+ )
+ result = post_update.step_expose_cli()
+ assert result == {"ok": True, "skipped": "config-disabled"}
+
+ def test_sealed_tree_without_venv_skips(self, fake_install, monkeypatch, tmp_path):
+ bare = tmp_path / "sealed"
+ bare.mkdir()
+ monkeypatch.setenv("HERMES_INSTALL_ROOT", str(bare))
+ result = post_update.step_expose_cli()
+ assert result == {"ok": True, "skipped": "no-venv-layout"}
+
+ @pytest.mark.skipif(sys.platform == "darwin", reason="darwin takes the symlink branch")
+ def test_bundled_tree_skips_bundle_owns_launchers(
+ self, fake_install, monkeypatch, tmp_path
+ ):
+ """The bundle owns its shims: on Linux (AppImage: transient mount)
+ the step names the shape and writes nothing."""
+ payload = tmp_path / "agent-payload"
+ (payload / "bin").mkdir(parents=True)
+ (payload / "repo").mkdir()
+ _write_bundled_stamp(payload / "repo")
+ for name in ("hermes", "hermes-agent", "hermes-acp"):
+ (payload / "bin" / name).write_text("\x7fELF fake shim\n")
+ monkeypatch.setenv("HERMES_INSTALL_ROOT", str(payload / "repo"))
+ result = post_update.step_expose_cli()
+ assert result == {"ok": True, "skipped": "bundle-owns-launchers"}
+
+ def test_unstamped_tree_with_sibling_bin_is_not_a_bundle(
+ self, fake_install, monkeypatch, tmp_path
+ ):
+ """The stamp is the shape authority. A venv-less checkout whose
+ PARENT happens to carry a bin/hermes (the installers' launcher
+ dir shares ~/.hermes with the checkout) must skip, not enter the
+ sealed branch — on every platform."""
+ parent = tmp_path / "hermes-home"
+ (parent / "bin").mkdir(parents=True)
+ (parent / "bin" / "hermes").write_text("#!/bin/sh\n# installer launcher\n")
+ checkout = parent / "hermes-agent"
+ checkout.mkdir()
+ monkeypatch.setenv("HERMES_INSTALL_ROOT", str(checkout))
+ result = post_update.step_expose_cli()
+ assert result == {"ok": True, "skipped": "no-venv-layout"}
+ assert post_update._is_bundled_payload(checkout) is False
+
+ def test_replaces_a_dangling_symlink_from_old_installs(self, fake_install):
+ """#21454: `cat >` used to follow an old symlink into the venv and
+ clobber the console script. The step must unlink FIRST."""
+ home, root = fake_install
+ wrapper_dir = home / ".local" / "bin"
+ wrapper_dir.mkdir(parents=True)
+ console_script = root / "venv" / "bin" / "hermes"
+ console_script.write_text("# real console script\n")
+ (wrapper_dir / "hermes").symlink_to(console_script)
+ result = post_update.step_expose_cli()
+ assert "hermes" in result["written"]
+ # The venv console script survives untouched…
+ assert console_script.read_text() == "# real console script\n"
+ # …and the link-dir entry is now a real file, not a symlink.
+ assert not (wrapper_dir / "hermes").is_symlink()
+
+
+@posix_only
+class TestSymlinkSealedLaunchers:
+ """The macOS sealed-bundle exposure helper, tested directly — the
+ symlink/ownership logic is platform-free; only its call site in
+ step_expose_cli is darwin-gated."""
+
+ @pytest.fixture
+ def payload(self, tmp_path, monkeypatch):
+ home = tmp_path / "home"
+ home.mkdir()
+ monkeypatch.setattr(Path, "home", staticmethod(lambda: home))
+ payload_bin = tmp_path / "Hermes.app" / "Contents" / "Resources" / "agent-payload" / "bin"
+ payload_bin.mkdir(parents=True)
+ for name in ("hermes", "hermes-agent", "hermes-acp"):
+ (payload_bin / name).write_text("fake mach-o shim\n")
+ return home, payload_bin
+
+ def test_links_all_three_fresh(self, payload):
+ home, payload_bin = payload
+ result = post_update._symlink_sealed_launchers(payload_bin)
+ assert result["ok"] is True
+ assert sorted(result["written"]) == ["hermes", "hermes-acp", "hermes-agent"]
+ for name in ("hermes", "hermes-agent", "hermes-acp"):
+ link = home / ".local" / "bin" / name
+ assert link.is_symlink()
+ assert os.readlink(link) == str(payload_bin / name)
+
+ def test_second_run_is_a_no_op(self, payload):
+ _, payload_bin = payload
+ post_update._symlink_sealed_launchers(payload_bin)
+ result = post_update._symlink_sealed_launchers(payload_bin)
+ assert result["written"] == []
+
+ def test_retargets_own_link_after_app_moved(self, payload, tmp_path):
+ """An app update / move leaves ~/.local/bin pointing at the old
+ bundle path INSIDE this payload tree — that link is ours; retarget."""
+ home, payload_bin = payload
+ old = payload_bin.parent / "bin-old"
+ link_dir = home / ".local" / "bin"
+ link_dir.mkdir(parents=True)
+ (link_dir / "hermes").symlink_to(old / "hermes") # dangling, old payload path
+ result = post_update._symlink_sealed_launchers(payload_bin)
+ assert "hermes" in result["written"]
+ assert os.readlink(link_dir / "hermes") == str(payload_bin / "hermes")
+
+ def test_never_touches_a_live_foreign_entry(self, payload, tmp_path):
+ home, payload_bin = payload
+ link_dir = home / ".local" / "bin"
+ link_dir.mkdir(parents=True)
+ # A real file (pipx-style launcher)…
+ (link_dir / "hermes").write_text("#!/bin/sh\n# pipx launcher\n")
+ # …and a live symlink to a different tool.
+ other = tmp_path / "other-tool"
+ other.write_text("other\n")
+ (link_dir / "hermes-agent").symlink_to(other)
+ result = post_update._symlink_sealed_launchers(payload_bin)
+ assert (link_dir / "hermes").read_text() == "#!/bin/sh\n# pipx launcher\n"
+ assert os.readlink(link_dir / "hermes-agent") == str(other)
+ assert sorted(result["written"]) == ["hermes-acp"]
diff --git a/tests/hermes_cli/test_managed_uv.py b/tests/hermes_cli/test_runtime_repair.py
similarity index 57%
rename from tests/hermes_cli/test_managed_uv.py
rename to tests/hermes_cli/test_runtime_repair.py
index 67b137ff50e..5a86e373a95 100644
--- a/tests/hermes_cli/test_managed_uv.py
+++ b/tests/hermes_cli/test_runtime_repair.py
@@ -1,9 +1,7 @@
-"""Tests for hermes_cli.managed_uv — one path, no guessing."""
+"""Tests for hermes_cli.runtime_repair — the venv/SQLite repair machinery."""
from __future__ import annotations
-import os
-import stat
import sys
from pathlib import Path
from types import SimpleNamespace
@@ -12,17 +10,26 @@ from unittest.mock import MagicMock, patch
import pytest
[email protected](autouse=True)
+def _pinned_uv_resolves(monkeypatch):
+ """repair_vulnerable_runtime() resolves uv itself via pm.ensure.uv;
+ pin it so no test realizes the pm store for real.
+
+ NOTE: the module object must be reached through sys.modules — both the
+ string form "pm.ensure.uv" and `import pm.ensure as x` resolve through
+ the `ensure` FUNCTION re-exported by pm/__init__, which shadows the
+ submodule attribute of the same name on the package.
+ """
+ import importlib
+
+ pm_ensure = importlib.import_module("pm.ensure")
+ monkeypatch.setattr(pm_ensure, "uv", lambda *a, **k: ("uv", {}))
+
+
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
-def _make_executable(path: Path) -> None:
- """Create a minimal fake uv binary at *path*."""
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text("#!/bin/sh\necho uv 0.1.2\n")
- path.chmod(path.stat().st_mode | stat.S_IEXEC)
-
-
def _runtime_info(
executable: Path,
sqlite_version: tuple[int, int, int],
@@ -39,18 +46,6 @@ def _runtime_info(
)
-def _RRR(status):
- """not-applicable RuntimeRepairResult for tests that neutralize the
- repair hook. ensure_uv()/update_managed_uv() invoke runtime repair as a
- side effect; unmocked, it probes the REAL checkout's venv/.venv — on CI
- the repo .venv links vulnerable SQLite, so repair fires for real and
- re-invokes _install_uv (uv-refresh retry), breaking call-count asserts.
- """
- from hermes_cli.managed_uv import RuntimeRepairResult
-
- return RuntimeRepairResult(status)
-
-
def _make_runtime_install(
tmp_path: Path,
*,
@@ -69,322 +64,9 @@ def _make_runtime_install(
return root, live, sentinel
-# ---------------------------------------------------------------------------
-# managed_uv_path
-# ---------------------------------------------------------------------------
-
-class TestManagedUvPath:
- # POSIX arm of the name mapping; the Windows arm (uv.exe) is exercised
- # for real by TestEnsureUvWindowsSafe on the Windows lane.
- @pytest.mark.skipif(sys.platform == "win32", reason="POSIX-only: bin/uv name")
- def test_posix(self, tmp_path):
- with patch("hermes_cli.managed_uv.get_hermes_home", return_value=tmp_path):
- from hermes_cli.managed_uv import managed_uv_path
- assert managed_uv_path() == tmp_path / "bin" / "uv"
-
-
-class TestMacOSManagedPythonSigning:
- def test_signs_with_stable_identifier_and_verifies(self, tmp_path, monkeypatch):
- import hermes_cli.managed_uv as managed_uv
-
- python = tmp_path / "generation" / "bin" / "python3.11"
- python.parent.mkdir(parents=True)
- python.touch()
- calls = []
-
- def fake_run(cmd, **kwargs):
- calls.append((cmd, kwargs))
- return SimpleNamespace(returncode=0, stdout="", stderr="")
-
- monkeypatch.setattr(managed_uv.platform, "system", lambda: "Darwin")
- monkeypatch.setattr(managed_uv.shutil, "which", lambda name: "/usr/bin/codesign")
- monkeypatch.setattr(managed_uv.subprocess, "run", fake_run)
-
- assert managed_uv._macos_sign_managed_python(python) is True
- assert calls[0][0] == [
- "/usr/bin/codesign",
- "--force",
- "--deep",
- "--sign",
- "-",
- "--timestamp=none",
- "--identifier",
- "com.nousresearch.hermes.managed-python",
- "--requirements",
- '=designated => identifier "com.nousresearch.hermes.managed-python"',
- str(python),
- ]
- assert calls[1][0] == [
- "/usr/bin/codesign",
- "--verify",
- "--deep",
- "--strict",
- str(python),
- ]
-
- def test_is_non_blocking_when_signing_fails(self, tmp_path, monkeypatch):
- import hermes_cli.managed_uv as managed_uv
-
- python = tmp_path / "python3.11"
- monkeypatch.setattr(managed_uv.platform, "system", lambda: "Darwin")
- monkeypatch.setattr(managed_uv.shutil, "which", lambda name: "/usr/bin/codesign")
- monkeypatch.setattr(
- managed_uv.subprocess,
- "run",
- lambda *args, **kwargs: SimpleNamespace(
- returncode=1, stdout="", stderr="not signable"
- ),
- )
-
- assert managed_uv._macos_sign_managed_python(python) is False
-
- def test_skips_non_macos(self, tmp_path, monkeypatch):
- import hermes_cli.managed_uv as managed_uv
-
- monkeypatch.setattr(managed_uv.platform, "system", lambda: "Linux")
- monkeypatch.setattr(
- managed_uv.subprocess,
- "run",
- lambda *args, **kwargs: pytest.fail("codesign must not run on Linux"),
- )
-
- assert managed_uv._macos_sign_managed_python(tmp_path / "python") is False
-
-
-# ---------------------------------------------------------------------------
-# resolve_uv
-# ---------------------------------------------------------------------------
-
-class TestResolveUv:
-
- def test_existing_executable(self, tmp_path):
- _make_executable(tmp_path / "bin" / "uv")
- with patch("hermes_cli.managed_uv.get_hermes_home", return_value=tmp_path):
- from hermes_cli.managed_uv import resolve_uv
- result = resolve_uv()
- assert result == str(tmp_path / "bin" / "uv")
-
- def test_non_executable_file_returns_none(self, tmp_path):
- uv = tmp_path / "bin" / "uv"
- uv.parent.mkdir(parents=True)
- uv.write_text("not a binary")
- # Ensure no execute bit
- uv.chmod(0o644)
- with patch("hermes_cli.managed_uv.get_hermes_home", return_value=tmp_path):
- from hermes_cli.managed_uv import resolve_uv
- assert resolve_uv() is None
-
-
-# ---------------------------------------------------------------------------
-# ensure_uv
-# ---------------------------------------------------------------------------
-
-class TestEnsureUv:
-
- def test_installs_if_missing(self, tmp_path):
- with patch("hermes_cli.managed_uv.get_hermes_home", return_value=tmp_path), \
- patch("hermes_cli.managed_uv.repair_vulnerable_runtime", return_value=_RRR("not-applicable")), \
- patch("hermes_cli.managed_uv._install_uv") as mock_install:
- # Simulate the installer creating the binary
- def fake_install(target):
- _make_executable(target)
- mock_install.side_effect = fake_install
-
- from hermes_cli.managed_uv import ensure_uv
- path = ensure_uv()
- assert path == str(tmp_path / "bin" / "uv")
- mock_install.assert_called_once()
-
- def test_install_reports_runtime_repair_to_observer(self, tmp_path):
- from hermes_cli.managed_uv import (
- RuntimeRepairResult,
- ensure_uv,
- )
-
- repair = RuntimeRepairResult(
- "repaired",
- sqlite_before="3.50.4",
- sqlite_after="3.53.1",
- )
-
- def fake_install(target):
- _make_executable(target)
-
- observed = []
- with patch(
- "hermes_cli.managed_uv.get_hermes_home",
- return_value=tmp_path,
- ), patch(
- "hermes_cli.managed_uv._install_uv",
- side_effect=fake_install,
- ), patch(
- "hermes_cli.managed_uv.repair_vulnerable_runtime",
- return_value=repair,
- ):
- path = ensure_uv(repair_observer=observed.append)
-
- assert path == str(tmp_path / "bin" / "uv")
- assert observed == [repair]
-
-
[email protected](sys.platform == "win32",
- reason="POSIX-only: the _UvResult dual contract is not offered on Windows")
-class TestEnsureUvUpdateBoundary:
- """``ensure_uv()`` must answer to both the single-value and the legacy
- ``(path, fresh_bootstrap)`` call conventions — **on POSIX**.
-
- ``hermes update`` runs the call site from the old, already-imported
- ``hermes_cli.main`` against the freshly pulled ``managed_uv``. A release
- parked on a ``(path, fresh)`` tuple runs ``uv_bin, fresh = ensure_uv()``
- against the single-value module; the path is an iterable ``str`` so the
- 2-target unpack walked its characters and raised
- ``ValueError: too many values to unpack (expected 2)`` (root cause behind
- PR #39763), or ``TypeError`` on the ``None`` failure path. On POSIX the
- result must therefore be usable as a bare path *and* unpackable as a
- 2-tuple, in both the success and failure cases.
-
- The dual contract is intentionally **not** offered on Windows — see
- ``TestEnsureUvWindowsSafe`` for why — so these tests are POSIX-only: the
- host's real ``platform.system()`` selects the wrapper branch, nothing is
- faked.
- """
-
- def test_success_usable_as_single_value(self, tmp_path):
- _make_executable(tmp_path / "bin" / "uv")
- with patch("hermes_cli.managed_uv.get_hermes_home", return_value=tmp_path), \
- patch("hermes_cli.managed_uv.repair_vulnerable_runtime", return_value=_RRR("not-applicable")):
- from hermes_cli.managed_uv import ensure_uv
- uv_bin = ensure_uv()
- assert uv_bin == str(tmp_path / "bin" / "uv")
- assert bool(uv_bin) is True
-
- def test_success_unpacks_as_legacy_two_tuple(self, tmp_path):
- _make_executable(tmp_path / "bin" / "uv")
- with patch("hermes_cli.managed_uv.get_hermes_home", return_value=tmp_path), \
- patch("hermes_cli.managed_uv.repair_vulnerable_runtime", return_value=_RRR("not-applicable")):
- from hermes_cli.managed_uv import ensure_uv
- uv_bin, fresh = ensure_uv() # old: uv_bin, fresh_bootstrap = ensure_uv()
- assert uv_bin == str(tmp_path / "bin" / "uv")
- assert fresh is False
-
- def test_failure_unpacks_without_raising(self, tmp_path):
- with patch("hermes_cli.managed_uv.get_hermes_home", return_value=tmp_path), \
- patch("hermes_cli.managed_uv.repair_vulnerable_runtime", return_value=_RRR("not-applicable")), \
- patch("hermes_cli.managed_uv._install_uv", side_effect=RuntimeError("network down")):
- from hermes_cli.managed_uv import ensure_uv
- uv_bin, fresh = ensure_uv()
- assert uv_bin is None
- assert fresh is False
-
-
-class TestEnsureUvWindowsSafe:
- """On Windows ``ensure_uv()`` must return a plain ``str``/``None``.
-
- ``subprocess`` on Windows serializes argv through
- ``subprocess.list2cmdline``, which iterates every entry *as a string*
- (``for c in arg``). The dependency installer feeds uv straight into the
- command list (``[uv_bin, "pip", "install", ...]``). A ``str`` subclass
- whose ``__iter__`` yields ``(path, fresh_bootstrap)`` instead of characters
- therefore injects the bool into the command line and crashes the install
- with ``TypeError: sequence item 1: expected str instance, bool found``
- (a real field report on a 10-commits-behind Windows install). A single
- return value cannot serve both the legacy 2-tuple unpack and Windows
- char-iteration — both use the iterator protocol — so Windows opts out of
- the wrapper entirely.
- """
-
- def test_uvresult_would_break_windows_list2cmdline(self):
- # Canary: this is *why* the wrapper is gated off Windows. If a future
- # change makes _UvResult char-iterable (and thus list2cmdline-safe),
- # the gate may be revisited.
- import subprocess
- from hermes_cli.managed_uv import _UvResult
- with pytest.raises(TypeError):
- subprocess.list2cmdline([_UvResult("C:\\hermes\\uv.exe"), "pip"])
-
- @pytest.mark.windows_only
- def test_windows_returns_plain_str_safe_for_subprocess(self, tmp_path):
- """``windows_only``: the subject is the real Windows opt-out branch and
- ``subprocess.list2cmdline`` — the faked ``platform.system`` only ever
- proved the branch existed, not that the field crash was fixed on the
- host that reported it."""
- import subprocess
- # On Windows the managed binary is uv.exe.
- _make_executable(tmp_path / "bin" / "uv.exe")
- with patch("hermes_cli.managed_uv.get_hermes_home", return_value=tmp_path), \
- patch("hermes_cli.managed_uv.repair_vulnerable_runtime", return_value=_RRR("not-applicable")):
- from hermes_cli.managed_uv import _UvResult, ensure_uv
- uv_bin = ensure_uv()
- assert type(uv_bin) is str and not isinstance(uv_bin, _UvResult)
- # The exact operation that crashed in the field must now succeed.
- cmdline = subprocess.list2cmdline([uv_bin, "pip", "install", "-e", "."])
- assert "pip" in cmdline and "install" in cmdline
-
-
-# ---------------------------------------------------------------------------
-# update_managed_uv
-# ---------------------------------------------------------------------------
-
-class TestUpdateManagedUv:
-
-
-
- def test_fresh_stamp_skips_network_self_update_but_not_repair(self, tmp_path, monkeypatch):
- """A recent success stamp must skip `uv self update` entirely while the
- vulnerable-runtime repair probe still runs (CVE repair is never gated)."""
- from hermes_cli.managed_uv import RuntimeRepairResult, update_managed_uv
-
- uv = tmp_path / "bin" / "uv"
- _make_executable(uv)
- # Fresh stamp under the isolated HERMES_HOME.
- import hermes_constants
- stamp = hermes_constants.get_hermes_home() / "cache" / ".uv_self_update_stamp"
- stamp.parent.mkdir(parents=True, exist_ok=True)
- stamp.touch()
-
- with patch("hermes_cli.managed_uv.get_hermes_home", return_value=tmp_path), \
- patch("hermes_cli.managed_uv.subprocess.run") as mock_run, \
- patch(
- "hermes_cli.managed_uv.repair_vulnerable_runtime",
- return_value=RuntimeRepairResult("skipped"),
- ) as mock_repair:
- result = update_managed_uv()
-
- assert result == str(uv)
- assert mock_run.call_count == 0, "fresh stamp must skip the network self-update"
- mock_repair.assert_called_once_with(str(uv))
-
-
- def test_stale_stamp_runs_self_update_and_refreshes_stamp(self, tmp_path):
- import os as _os
- import time as _time
-
- from hermes_cli.managed_uv import UV_SELF_UPDATE_INTERVAL_SECONDS, update_managed_uv
-
- uv = tmp_path / "bin" / "uv"
- _make_executable(uv)
- import hermes_constants
- stamp = hermes_constants.get_hermes_home() / "cache" / ".uv_self_update_stamp"
- stamp.parent.mkdir(parents=True, exist_ok=True)
- stamp.touch()
- old = _time.time() - UV_SELF_UPDATE_INTERVAL_SECONDS - 60
- _os.utime(stamp, (old, old))
-
- with patch("hermes_cli.managed_uv.get_hermes_home", return_value=tmp_path), \
- patch("hermes_cli.managed_uv.repair_vulnerable_runtime", return_value=_RRR("not-applicable")), \
- patch("hermes_cli.managed_uv.subprocess.run") as mock_run:
- mock_run.return_value = MagicMock(returncode=0, stdout="uv 0.2.0")
- update_managed_uv()
-
- assert mock_run.call_args_list[0][0][0] == [str(uv), "self", "update"]
- assert stamp.stat().st_mtime > old + 30, "successful self-update must refresh the stamp"
-
-
-
-
class TestManagedPythonStore:
def test_store_is_checkout_scoped_across_profiles(self, tmp_path, monkeypatch):
- from hermes_cli.managed_uv import managed_python_install_dir
+ from hermes_cli.runtime_repair import managed_python_install_dir
checkout = tmp_path / "checkout"
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "profiles" / "alpha"))
@@ -397,7 +79,7 @@ class TestManagedPythonStore:
assert beta == expected
def test_environment_is_private_and_sanitized(self, tmp_path):
- from hermes_cli.managed_uv import managed_python_env
+ from hermes_cli.runtime_repair import managed_python_env
checkout = tmp_path / "checkout"
base_env = {
@@ -444,18 +126,18 @@ class TestManagedPythonStore:
reason="POSIX-only: fixtures build the bin/ (not Scripts/) venv layout")
class TestRuntimeRepair:
def test_safe_runtime_is_a_noop(self, tmp_path):
- from hermes_cli.managed_uv import repair_vulnerable_runtime
+ from hermes_cli.runtime_repair import repair_vulnerable_runtime
root, live, sentinel = _make_runtime_install(tmp_path)
current = _runtime_info(live / "bin" / "python", (3, 53, 1))
with patch(
- "hermes_cli.managed_uv.probe_sqlite_runtime",
+ "hermes_cli.runtime_repair.probe_sqlite_runtime",
return_value=current,
), \
patch(
- "hermes_cli.managed_uv._install_safe_python_generation"
+ "hermes_cli.runtime_repair._install_safe_python_generation"
) as mock_install:
- result = repair_vulnerable_runtime("uv", project_root=root)
+ result = repair_vulnerable_runtime(project_root=root)
assert result.status == "safe"
assert result.sqlite_before == "3.53.1"
@@ -465,7 +147,7 @@ class TestRuntimeRepair:
mock_install.assert_not_called()
def test_stage_candidate_sync_keeps_uv_project_config(self, tmp_path):
- from hermes_cli.managed_uv import _stage_candidate_venv
+ from hermes_cli.runtime_repair import _stage_candidate_venv
root = tmp_path / "checkout"
root.mkdir()
@@ -481,9 +163,9 @@ class TestRuntimeRepair:
calls.append((list(argv), kwargs.get("env")))
return MagicMock(returncode=0)
- with patch("hermes_cli.managed_uv.subprocess.run", side_effect=fake_run), \
+ with patch("hermes_cli.runtime_repair.subprocess.run", side_effect=fake_run), \
patch(
- "hermes_cli.managed_uv._smoke_candidate_venv",
+ "hermes_cli.runtime_repair._smoke_candidate_venv",
return_value=(True, "", None),
):
candidate = _stage_candidate_venv(
@@ -506,7 +188,7 @@ class TestRuntimeRepair:
assert "UV_NO_CONFIG" not in sync_env
def test_failed_candidate_preserves_live_venv(self, tmp_path):
- from hermes_cli.managed_uv import (
+ from hermes_cli.runtime_repair import (
_acquire_repair_lock,
_release_repair_lock,
repair_vulnerable_runtime,
@@ -521,18 +203,18 @@ class TestRuntimeRepair:
fixed = _runtime_info(candidate_python, (3, 53, 1))
with patch(
- "hermes_cli.managed_uv.probe_sqlite_runtime",
+ "hermes_cli.runtime_repair.probe_sqlite_runtime",
side_effect=[current, current],
), \
patch(
- "hermes_cli.managed_uv._install_safe_python_generation",
+ "hermes_cli.runtime_repair._install_safe_python_generation",
return_value=(generation, candidate_python, fixed),
), \
patch(
- "hermes_cli.managed_uv._stage_candidate_venv",
+ "hermes_cli.runtime_repair._stage_candidate_venv",
return_value=None,
):
- result = repair_vulnerable_runtime("uv", project_root=root)
+ result = repair_vulnerable_runtime(project_root=root)
assert result.status == "failed"
assert "replacement environment" in result.detail
@@ -551,7 +233,7 @@ class TestRuntimeRepair:
import os
import time as _time
- from hermes_cli.managed_uv import repair_vulnerable_runtime
+ from hermes_cli.runtime_repair import repair_vulnerable_runtime
root, live, sentinel = _make_runtime_install(tmp_path)
old_backup = root / f"{live.name}.stale.runtime-1-2-aaaa"
@@ -565,10 +247,10 @@ class TestRuntimeRepair:
current = _runtime_info(live / "bin" / "python", (3, 53, 1))
with patch(
- "hermes_cli.managed_uv.probe_sqlite_runtime",
+ "hermes_cli.runtime_repair.probe_sqlite_runtime",
return_value=current,
):
- result = repair_vulnerable_runtime("uv", project_root=root)
+ result = repair_vulnerable_runtime(project_root=root)
assert result.status == "safe"
assert not old_backup.exists(), "aged stale backup must be reclaimed"
@@ -578,7 +260,7 @@ class TestRuntimeRepair:
def test_successful_repair_removes_parked_backup(self, tmp_path):
"""After a successful cutover the parked venv is removed instead of
leaking ~1 GB at the project root forever (issue #73109)."""
- from hermes_cli.managed_uv import repair_vulnerable_runtime
+ from hermes_cli.runtime_repair import repair_vulnerable_runtime
root, live, sentinel = _make_runtime_install(tmp_path)
current = _runtime_info(live / "bin" / "python", (3, 50, 4))
@@ -594,22 +276,22 @@ class TestRuntimeRepair:
)
with patch(
- "hermes_cli.managed_uv.probe_sqlite_runtime",
+ "hermes_cli.runtime_repair.probe_sqlite_runtime",
side_effect=[current, current],
), \
patch(
- "hermes_cli.managed_uv._install_safe_python_generation",
+ "hermes_cli.runtime_repair._install_safe_python_generation",
return_value=(generation, candidate_python, fixed),
), \
patch(
- "hermes_cli.managed_uv._stage_candidate_venv",
+ "hermes_cli.runtime_repair._stage_candidate_venv",
return_value=candidate_venv,
), \
patch(
- "hermes_cli.managed_uv._smoke_candidate_venv",
+ "hermes_cli.runtime_repair._smoke_candidate_venv",
return_value=(True, "", fixed),
):
- result = repair_vulnerable_runtime("uv", project_root=root)
+ result = repair_vulnerable_runtime(project_root=root)
assert result.status == "repaired"
assert result.backup_venv is not None
@@ -622,7 +304,7 @@ class TestRuntimeRepair:
class TestRuntimeCutover:
def test_os_lock_blocks_concurrent_repair_and_releases(self, tmp_path):
- from hermes_cli.managed_uv import _acquire_repair_lock, _release_repair_lock
+ from hermes_cli.runtime_repair import _acquire_repair_lock, _release_repair_lock
runtime_root = tmp_path / ".hermes-runtime"
first = _acquire_repair_lock(runtime_root)
@@ -634,10 +316,8 @@ class TestRuntimeCutover:
assert second is not None
_release_repair_lock(second)
-
-
def test_post_swap_smoke_failure_rolls_back_live_venv(self, tmp_path):
- from hermes_cli.managed_uv import _cut_over_candidate
+ from hermes_cli.runtime_repair import _cut_over_candidate
root, live, sentinel = _make_runtime_install(tmp_path)
runtime_root = root / ".hermes-runtime"
@@ -647,7 +327,7 @@ class TestRuntimeCutover:
rejected_info = _runtime_info(candidate / "bin" / "python", (3, 50, 4))
with patch(
- "hermes_cli.managed_uv._smoke_candidate_venv",
+ "hermes_cli.runtime_repair._smoke_candidate_venv",
return_value=(False, "core import smoke failed", rejected_info),
):
ok, backup, info, detail = _cut_over_candidate(
@@ -660,30 +340,13 @@ class TestRuntimeCutover:
assert info == rejected_info
assert "post-cutover smoke failed" in detail
assert sentinel.read_text(encoding="utf-8") == "live"
- assert (live / "bin" / "python").read_text(encoding="utf-8") == (
- "live interpreter"
- )
+ assert (live / "bin" / "python").exists() or (
+ live / "Scripts" / "python.exe"
+ ).exists()
assert not candidate.exists()
assert not list(runtime_root.glob("venv-rejected-*"))
-
-
-# ---------------------------------------------------------------------------
-# _install_uv internals
-# ---------------------------------------------------------------------------
-
-class TestInstallUvInternals:
- def test_posix_sets_uv_unmanaged_install(self, tmp_path):
- target = tmp_path / "bin" / "uv"
- with patch("hermes_cli.managed_uv._install_uv_posix") as mock_posix:
- from hermes_cli.managed_uv import _install_uv
- _install_uv(target)
- mock_posix.assert_called_once()
- call_env = mock_posix.call_args[0][0]
- assert call_env["UV_UNMANAGED_INSTALL"] == str(tmp_path / "bin")
-
-
class TestRuntimeRequestMinorLine:
"""The repair must request the CPython minor line, not the exact patch.
@@ -695,7 +358,7 @@ class TestRuntimeRequestMinorLine:
"""
def test_requests_minor_line(self):
- from hermes_cli.managed_uv import _runtime_request
+ from hermes_cli.runtime_repair import _runtime_request
info = _runtime_info(Path("/venv/bin/python"), (3, 50, 4))
assert _runtime_request(info) == "3.11"
@@ -703,7 +366,7 @@ class TestRuntimeRequestMinorLine:
@staticmethod
def _run_generation(tmp_path, monkeypatch, current_version, candidate_version):
"""Drive _install_safe_python_generation with fakes; return result."""
- import hermes_cli.managed_uv as managed_uv
+ import hermes_cli.runtime_repair as runtime_repair
from hermes_cli.sqlite_runtime import SQLiteRuntimeInfo
state = {}
@@ -736,9 +399,9 @@ class TestRuntimeRequestMinorLine:
sqlite_version_string="3.50.4",
sqlite_source_id="old",
)
- monkeypatch.setattr(managed_uv.subprocess, "run", fake_run)
- monkeypatch.setattr(managed_uv, "probe_sqlite_runtime", fake_probe)
- return managed_uv._install_safe_python_generation(
+ monkeypatch.setattr(runtime_repair.subprocess, "run", fake_run)
+ monkeypatch.setattr(runtime_repair, "probe_sqlite_runtime", fake_probe)
+ return runtime_repair._install_safe_python_generation(
"uv", project_root=tmp_path, current=current
)
@@ -766,7 +429,6 @@ class TestPatchRetryOnVulnerableCandidate:
resolves to a DIFFERENT candidate Python version depending on which
exact version string was requested, so retries with explicit
patches can be distinguished from the initial bare-minor attempt."""
- import hermes_cli.managed_uv as managed_uv
from hermes_cli.sqlite_runtime import SQLiteRuntimeInfo
state = {"requested": None}
@@ -810,7 +472,7 @@ class TestPatchRetryOnVulnerableCandidate:
return fake_run, fake_probe
def _run(self, tmp_path, monkeypatch, *, vulnerable_versions, patch_list):
- import hermes_cli.managed_uv as managed_uv
+ import hermes_cli.runtime_repair as runtime_repair
from hermes_cli.sqlite_runtime import SQLiteRuntimeInfo
fake_run, fake_probe = self._versioned_probe_run(vulnerable_versions)
@@ -819,12 +481,12 @@ class TestPatchRetryOnVulnerableCandidate:
python_version=(3, 11, 14), sqlite_version=(3, 50, 4),
sqlite_version_string="3.50.4", sqlite_source_id="old",
)
- monkeypatch.setattr(managed_uv.subprocess, "run", fake_run)
- monkeypatch.setattr(managed_uv, "probe_sqlite_runtime", fake_probe)
+ monkeypatch.setattr(runtime_repair.subprocess, "run", fake_run)
+ monkeypatch.setattr(runtime_repair, "probe_sqlite_runtime", fake_probe)
monkeypatch.setattr(
- managed_uv, "_list_available_patches", lambda *a, **kw: patch_list
+ runtime_repair, "_list_available_patches", lambda *a, **kw: patch_list
)
- return managed_uv._install_safe_python_generation(
+ return runtime_repair._install_safe_python_generation(
"uv", project_root=tmp_path, current=current
)
@@ -841,15 +503,11 @@ class TestPatchRetryOnVulnerableCandidate:
assert candidate.python_version == (3, 11, 15)
assert not candidate.wal_reset_vulnerable
-
-
-
-
def test_retry_is_bounded_by_max_retries_constant(self, tmp_path, monkeypatch):
"""A very long patch list must not result in unbounded retries -- capped at
_MAX_PATCH_RETRIES attempts. After exhausting same-minor retries the
fallback tries the next minor line, which may succeed."""
- import hermes_cli.managed_uv as managed_uv
+ import hermes_cli.runtime_repair as runtime_repair
from hermes_cli.sqlite_runtime import SQLiteRuntimeInfo
@@ -870,12 +528,12 @@ class TestPatchRetryOnVulnerableCandidate:
install_calls.append(cmd[3])
return fake_run2(cmd, **kwargs)
- monkeypatch.setattr(managed_uv.subprocess, "run", counting_fake_run)
- monkeypatch.setattr(managed_uv, "probe_sqlite_runtime", fake_probe2)
+ monkeypatch.setattr(runtime_repair.subprocess, "run", counting_fake_run)
+ monkeypatch.setattr(runtime_repair, "probe_sqlite_runtime", fake_probe2)
monkeypatch.setattr(
- managed_uv, "_list_available_patches", lambda *a, **kw: huge_patch_list
+ runtime_repair, "_list_available_patches", lambda *a, **kw: huge_patch_list
)
- result = managed_uv._install_safe_python_generation(
+ result = runtime_repair._install_safe_python_generation(
"uv", project_root=tmp_path, current=current
)
# The same-minor retries are bounded, but the minor-line fallback
@@ -884,14 +542,14 @@ class TestPatchRetryOnVulnerableCandidate:
"Minor-line fallback should find a fixed 3.12 build"
)
# 1 initial bare-minor attempt + at most _MAX_PATCH_RETRIES retries.
- assert managed_uv._MAX_PATCH_RETRIES <= 5, (
+ assert runtime_repair._MAX_PATCH_RETRIES <= 5, (
"sanity: constant should stay small since each attempt is a "
"real download+install+probe cycle"
)
same_minor_explicit = [
call for call in install_calls if call.startswith("3.11.")
]
- assert len(same_minor_explicit) <= managed_uv._MAX_PATCH_RETRIES, (
+ assert len(same_minor_explicit) <= runtime_repair._MAX_PATCH_RETRIES, (
f"same-minor explicit retries must be capped: {same_minor_explicit}"
)
assert install_calls[0] == "3.11"
@@ -977,7 +635,7 @@ class TestMinorLineFallForward:
links fixed SQLite -- the `_list_available_patches(..., '3.12', ...)`
fallback branch must run, skip the already-tried bare resolution,
and succeed via the explicit patch."""
- import hermes_cli.managed_uv as managed_uv
+ import hermes_cli.runtime_repair as runtime_repair
install_calls = []
fake_run, fake_probe = self._mapped_run(
@@ -995,14 +653,14 @@ class TestMinorLineFallForward:
# Newest 3.12 is the same build the bare request resolved to.
"3.12": [(3, 12, 11), (3, 12, 10)],
}
- monkeypatch.setattr(managed_uv.subprocess, "run", fake_run)
- monkeypatch.setattr(managed_uv, "probe_sqlite_runtime", fake_probe)
+ monkeypatch.setattr(runtime_repair.subprocess, "run", fake_run)
+ monkeypatch.setattr(runtime_repair, "probe_sqlite_runtime", fake_probe)
monkeypatch.setattr(
- managed_uv, "_list_available_patches",
+ runtime_repair, "_list_available_patches",
lambda uv_bin, minor, **kw: patch_lists[minor],
)
- result = managed_uv._install_safe_python_generation(
+ result = runtime_repair._install_safe_python_generation(
"uv", project_root=tmp_path, current=self._current_3_11_14()
)
assert result is not None, (
@@ -1023,7 +681,7 @@ class TestMinorLineFallForward:
"""When every build on every supported minor line (3.11-3.13) is
vulnerable, the provisioner must give up with None -- and the total
install workload must stay bounded by _MAX_PATCH_RETRIES per line."""
- import hermes_cli.managed_uv as managed_uv
+ import hermes_cli.runtime_repair as runtime_repair
install_calls = []
resolutions = {"3.11": (3, 11, 14), "3.12": (3, 12, 30), "3.13": (3, 13, 30)}
@@ -1038,19 +696,19 @@ class TestMinorLineFallForward:
resolutions=resolutions, fixed_versions=set(),
install_calls=install_calls,
)
- monkeypatch.setattr(managed_uv.subprocess, "run", fake_run)
- monkeypatch.setattr(managed_uv, "probe_sqlite_runtime", fake_probe)
+ monkeypatch.setattr(runtime_repair.subprocess, "run", fake_run)
+ monkeypatch.setattr(runtime_repair, "probe_sqlite_runtime", fake_probe)
monkeypatch.setattr(
- managed_uv, "_list_available_patches",
+ runtime_repair, "_list_available_patches",
lambda uv_bin, minor, **kw: patch_lists[minor],
)
- result = managed_uv._install_safe_python_generation(
+ result = runtime_repair._install_safe_python_generation(
"uv", project_root=tmp_path, current=self._current_3_11_14()
)
assert result is None, "Nothing fixed anywhere: must give up cleanly"
- cap = managed_uv._MAX_PATCH_RETRIES
+ cap = runtime_repair._MAX_PATCH_RETRIES
# Per line: one bare request + at most _MAX_PATCH_RETRIES explicit
# patches; three lines total (3.11, 3.12, 3.13) and nothing beyond
# 3.13 (requires-python is <3.14).
@@ -1093,153 +751,51 @@ class TestListAvailablePatches:
)
def test_parses_and_sorts_newest_first(self, tmp_path, monkeypatch):
- import hermes_cli.managed_uv as managed_uv
+ import hermes_cli.runtime_repair as runtime_repair
def fake_run(cmd, **kwargs):
return SimpleNamespace(returncode=0, stdout=self.SAMPLE_OUTPUT, stderr="")
- monkeypatch.setattr(managed_uv.subprocess, "run", fake_run)
- result = managed_uv._list_available_patches(
+ monkeypatch.setattr(runtime_repair.subprocess, "run", fake_run)
+ result = runtime_repair._list_available_patches(
"uv", "3.11", cwd=tmp_path, env={}
)
assert result == [(3, 11, 15), (3, 11, 14)]
-
def test_subprocess_exception_returns_empty_list(self, tmp_path, monkeypatch):
- import hermes_cli.managed_uv as managed_uv
+ import hermes_cli.runtime_repair as runtime_repair
def fake_run(cmd, **kwargs):
raise OSError("uv binary not found")
- monkeypatch.setattr(managed_uv.subprocess, "run", fake_run)
- assert managed_uv._list_available_patches("uv", "3.11", cwd=tmp_path, env={}) == []
-
-
-# ---------------------------------------------------------------------------
-# _refresh_managed_uv_catalog + provisioning retry (issue #72093)
-# ---------------------------------------------------------------------------
-
-class TestRefreshManagedUvCatalog:
- """The managed uv is UV_UNMANAGED_INSTALL'd, so `uv self update` is
- disabled and its python-build-standalone catalog freezes at bootstrap
- age. python-build-standalone re-releases the same patch versions with
- fixed SQLite, so a stale catalog makes provisioning fail forever with
- no newer patch number to retry (issue #72093)."""
-
-
- def test_version_change_reports_true(self, tmp_path):
- import hermes_cli.managed_uv as managed_uv
+ monkeypatch.setattr(runtime_repair.subprocess, "run", fake_run)
+ assert runtime_repair._list_available_patches("uv", "3.11", cwd=tmp_path, env={}) == []
- versions = iter(["uv 0.1.0", "uv 0.2.0"])
- with patch("hermes_cli.managed_uv.get_hermes_home", return_value=tmp_path), \
- patch("hermes_cli.managed_uv._install_uv"), \
- patch(
- "hermes_cli.managed_uv._uv_version_string",
- side_effect=lambda _uv: next(versions),
- ):
- # Host-native path: the refresh only acts on the managed binary,
- # so the fixture must live at the real host's managed_uv_path()
- # (uv on POSIX, uv.exe on Windows) — no platform fake needed.
- uv_path = managed_uv.managed_uv_path()
- _make_executable(uv_path)
- assert managed_uv._refresh_managed_uv_catalog(str(uv_path)) is True
-
-
- def test_installer_failure_reports_false(self, tmp_path):
- import hermes_cli.managed_uv as managed_uv
-
- with patch("hermes_cli.managed_uv.get_hermes_home", return_value=tmp_path), \
- patch(
- "hermes_cli.managed_uv._install_uv",
- side_effect=RuntimeError("network down"),
- ):
- uv_path = managed_uv.managed_uv_path()
- _make_executable(uv_path)
- assert managed_uv._refresh_managed_uv_catalog(str(uv_path)) is False
-
-
[email protected](sys.platform == "win32",
- reason="POSIX-only: fixtures build the bin/ (not Scripts/) venv layout")
-class TestRepairRetriesAfterUvRefresh:
- def _run_repair(self, tmp_path, *, refresh_result, second_attempt):
- """Drive repair with the first provisioning attempt failing."""
- from hermes_cli.managed_uv import repair_vulnerable_runtime
-
- root, live, sentinel = _make_runtime_install(tmp_path)
- current = _runtime_info(live / "bin" / "python", (3, 50, 4))
- attempts = []
+class TestPmUvResolution:
+ """The repair resolves uv through pm — never a foreign uv, never its
+ own acquisition (the retired managed_uv half)."""
- def fake_install(uv_bin, *, project_root, current):
- attempts.append(uv_bin)
- if len(attempts) == 1:
- return None
- return second_attempt(project_root)
+ def test_pm_uv_unavailable_skips_without_touching_the_venv(
+ self, tmp_path, monkeypatch
+ ):
+ from hermes_cli.runtime_repair import repair_vulnerable_runtime
- with patch(
- "hermes_cli.managed_uv.probe_sqlite_runtime",
- return_value=current,
- ), \
- patch(
- "hermes_cli.managed_uv._install_safe_python_generation",
- side_effect=fake_install,
- ), \
- patch(
- "hermes_cli.managed_uv._refresh_managed_uv_catalog",
- return_value=refresh_result,
- ) as mock_refresh, \
- patch(
- "hermes_cli.managed_uv._stage_candidate_venv",
- return_value=None,
- ):
- result = repair_vulnerable_runtime("uv", project_root=root)
- return result, attempts, mock_refresh, sentinel
-
- def test_no_retry_when_refresh_did_not_change_uv(self, tmp_path):
- result, attempts, mock_refresh, sentinel = self._run_repair(
- tmp_path,
- refresh_result=False,
- second_attempt=lambda root: None,
+ root, live, sentinel = _make_runtime_install(
+ tmp_path, windows=sys.platform == "win32"
)
- assert result.status == "failed"
- assert len(attempts) == 1
- mock_refresh.assert_called_once_with("uv")
- assert sentinel.read_text(encoding="utf-8") == "live"
+ import importlib
- def test_retries_once_after_successful_refresh(self, tmp_path):
- result, attempts, mock_refresh, sentinel = self._run_repair(
- tmp_path,
- refresh_result=True,
- second_attempt=lambda root: None,
- )
- # Second attempt ran (and also failed) — exactly one retry, no loop.
- assert result.status == "failed"
- assert len(attempts) == 2
- mock_refresh.assert_called_once_with("uv")
- assert sentinel.read_text(encoding="utf-8") == "live"
+ pm_ensure = importlib.import_module("pm.ensure")
+ monkeypatch.setattr(pm_ensure, "uv", lambda *a, **k: (None, {}))
- def test_retry_success_proceeds_to_staging(self, tmp_path):
- def second_attempt(root):
- generation = root / ".hermes-runtime" / "python" / "generation-retry"
- candidate_python = generation / "bin" / "python"
- candidate_python.parent.mkdir(parents=True)
- candidate_python.write_text("candidate", encoding="utf-8")
- return generation, candidate_python, _runtime_info(
- candidate_python, (3, 53, 1)
- )
+ result = repair_vulnerable_runtime(project_root=root)
- result, attempts, mock_refresh, sentinel = self._run_repair(
- tmp_path,
- refresh_result=True,
- second_attempt=second_attempt,
- )
- # Provisioning succeeded on retry; staging (mocked to None) is what
- # failed — proving the retry result flows into the normal pipeline.
- assert result.status == "failed"
- assert "replacement environment" in result.detail
- assert len(attempts) == 2
+ assert result.status == "skipped"
+ assert "pinned uv unavailable" in result.detail
assert sentinel.read_text(encoding="utf-8") == "live"
+
class TestDefaultLiveVenv:
"""_default_live_venv() must cover BOTH install layouts (venv/ and .venv/).
@@ -1249,29 +805,32 @@ class TestDefaultLiveVenv:
"""
def _checkout(self, tmp_path, *dirs):
+ windows = sys.platform == "win32"
root = tmp_path / "checkout"
root.mkdir()
(root / "pyproject.toml").write_text("[project]\n", encoding="utf-8")
for d in dirs:
- bin_dir = root / d / "bin"
+ bin_dir = root / d / ("Scripts" if windows else "bin")
bin_dir.mkdir(parents=True)
- (bin_dir / "python").write_text("py", encoding="utf-8")
+ (bin_dir / ("python.exe" if windows else "python")).write_text(
+ "py", encoding="utf-8"
+ )
return root
def test_dot_venv_only_is_targeted(self, tmp_path):
- from hermes_cli.managed_uv import _default_live_venv
+ from hermes_cli.runtime_repair import _default_live_venv
root = self._checkout(tmp_path, ".venv")
assert _default_live_venv(root) == root / ".venv"
def test_managed_venv_takes_precedence(self, tmp_path):
- from hermes_cli.managed_uv import _default_live_venv
+ from hermes_cli.runtime_repair import _default_live_venv
root = self._checkout(tmp_path, "venv", ".venv")
assert _default_live_venv(root) == root / "venv"
def test_neither_layout_keeps_not_applicable(self, tmp_path):
- from hermes_cli.managed_uv import (
+ from hermes_cli.runtime_repair import (
_default_live_venv,
repair_vulnerable_runtime,
)
@@ -1279,7 +838,7 @@ class TestDefaultLiveVenv:
root = self._checkout(tmp_path)
# Neither venv nor .venv has an interpreter -> repair is not applicable.
assert _default_live_venv(root) == root / "venv"
- result = repair_vulnerable_runtime("uv", project_root=root)
+ result = repair_vulnerable_runtime(project_root=root)
assert result.status == "not-applicable"
@@ -1287,7 +846,7 @@ class TestVenvPythonUpdateBoundary:
"""``_venv_python`` must survive a hermes_constants predating its symbol.
``hermes update`` imports hermes_constants from the OLD checkout, ``git
- pull`` replaces that file, and the freshly-pulled managed_uv then runs its
+ pull`` replaces that file, and the freshly-pulled runtime_repair then runs its
lazy ``from hermes_constants import venv_python_path`` against the module
object already cached in ``sys.modules``. That cached module has no such
symbol, so the import raises — while naming the NEW file on disk, which
@@ -1304,7 +863,7 @@ class TestVenvPythonUpdateBoundary:
def test_recovers_when_the_cached_module_predates_the_symbol(self, monkeypatch):
import hermes_constants
- from hermes_cli.managed_uv import _venv_python
+ from hermes_cli.runtime_repair import _venv_python
# The stale in-memory module: the symbol the new code wants is absent,
# exactly as on an install that booted the pre-upgrade checkout. The
@@ -1325,7 +884,7 @@ class TestVenvPythonUpdateBoundary:
"""
import hermes_constants
- from hermes_cli.managed_uv import _venv_python
+ from hermes_cli.runtime_repair import _venv_python
monkeypatch.delattr(hermes_constants, "venv_python_path", raising=False)
@@ -1344,7 +903,7 @@ class TestVenvPythonUpdateBoundary:
def test_uses_the_real_helper_when_it_is_importable(self, monkeypatch):
"""The normal path never reloads — recovery stays a fallback."""
- from hermes_cli.managed_uv import _venv_python
+ from hermes_cli.runtime_repair import _venv_python
def _no_reload(module): # pragma: no cover - must not run
raise AssertionError("reload must not run when the import succeeds")
diff --git a/tests/hermes_cli/test_steward_detection.py b/tests/hermes_cli/test_steward_detection.py
new file mode 100644
index 00000000000..629e34557af
--- /dev/null
+++ b/tests/hermes_cli/test_steward_detection.py
@@ -0,0 +1,148 @@
+"""Steward detection reads the install stamp beside the code, not markers.
+
+``hermes_cli.steward`` decides whether a steward owns this tree (and
+therefore whether ``hermes update`` and the uninstaller must refuse code
+mutation). That is a fact about the INSTALL, so it comes from the two
+facts the tree itself carries: ``.git`` (a checkout we own) and the
+install stamp that ships with the code (``install-stamp.json``, written by
+``scripts/write_install_stamp.py`` with a required ``updateMechanism`` of
+``self``/``electron-updater``/``external``).
+"""
+
+import json
+
+import pytest
+
+from hermes_cli.steward import (
+ STEWARD_DESKTOP,
+ STEWARD_DOCKER,
+ STEWARD_NIX,
+ classify_install,
+ read_install_stamp,
+ sealed_steward,
+)
+
+
+def _stamp(root, *, mechanism="external", **fields):
+ root.mkdir(exist_ok=True)
+ path = root / "install-stamp.json"
+ payload = {"commit": "a" * 40, "updateMechanism": mechanism, **fields}
+ path.write_text(json.dumps(payload), encoding="utf-8")
+ return path
+
+
+class TestStampDrivenDetection:
+ @pytest.mark.parametrize(
+ ("distribution", "mechanism"),
+ [
+ (STEWARD_NIX, "external"),
+ (STEWARD_DOCKER, "external"),
+ (STEWARD_DESKTOP, "electron-updater"),
+ ],
+ )
+ def test_sealed_tree_names_its_steward(self, tmp_path, distribution, mechanism):
+ root = tmp_path / "install"
+ _stamp(root, mechanism=mechanism, distribution=distribution)
+ assert sealed_steward(root) == distribution
+ assert classify_install(root) == (distribution, False)
+
+ def test_git_checkout_is_not_steward_owned(self, tmp_path):
+ root = tmp_path / "checkout"
+ root.mkdir()
+ (root / ".git").mkdir()
+ assert sealed_steward(root) is None
+ assert classify_install(root) == ("git", True)
+
+ def test_git_beats_stamp(self, tmp_path):
+ """A checkout carrying a baked stamp (self-updating source install)
+ is still a checkout — the uninstaller may remove it."""
+ root = tmp_path / "checkout"
+ root.mkdir()
+ (root / ".git").mkdir()
+ _stamp(root, mechanism="self", distribution=None)
+ assert sealed_steward(root) is None
+
+ def test_worktree_gitfile_counts_as_checkout(self, tmp_path):
+ root = tmp_path / "worktree"
+ root.mkdir()
+ (root / ".git").write_text("gitdir: ../elsewhere\n", encoding="utf-8")
+ assert sealed_steward(root) is None
+
+ def test_missing_stamp_gives_unknown_steward(self, tmp_path):
+ """No .git and no stamp: we cannot prove the tree is ours — sealed
+ under an unknown steward, so code removal refuses."""
+ root = tmp_path / "bare"
+ root.mkdir()
+ assert sealed_steward(root) == "unknown"
+ assert classify_install(root) == ("unknown", False)
+
+ def test_malformed_stamp_degrades_to_unknown(self, tmp_path):
+ root = tmp_path / "install"
+ root.mkdir()
+ (root / "install-stamp.json").write_text("{not json", encoding="utf-8")
+ assert read_install_stamp(root) == {}
+ assert sealed_steward(root) == "unknown"
+
+
+class TestUpdateAdmission:
+ """The update admission gate refuses sealed trees with the steward's text."""
+
+ @pytest.fixture(autouse=True)
+ def _no_image_marker(self, tmp_path, monkeypatch):
+ import hermes_cli.image_provenance as ip
+
+ monkeypatch.setattr(ip, "IMAGE_PROVENANCE_PATH", tmp_path / "absent.json")
+
+ def test_desktop_app_stamp_refuses_update(self, tmp_path, monkeypatch):
+ from hermes_cli.update_contract import evaluate_update_admission
+
+ root = tmp_path / "payload"
+ _stamp(root, mechanism="electron-updater", distribution=STEWARD_DESKTOP)
+ refusal = evaluate_update_admission(root)
+ assert refusal is not None
+ assert refusal.code == STEWARD_DESKTOP
+ assert "desktop app" in refusal.message
+
+ def test_nix_stamp_refuses_update(self, tmp_path):
+ from hermes_cli.update_contract import evaluate_update_admission
+
+ root = tmp_path / "store-tree"
+ _stamp(root, mechanism="external", distribution=STEWARD_NIX)
+ refusal = evaluate_update_admission(root)
+ assert refusal is not None
+ assert refusal.code == "nix"
+ assert "Nix store" in refusal.message
+
+ def test_docker_stamp_refuses_with_docker_message(self, tmp_path):
+ from hermes_cli.update_contract import evaluate_update_admission
+
+ root = tmp_path / "image-tree"
+ _stamp(root, mechanism="external", distribution=STEWARD_DOCKER)
+ refusal = evaluate_update_admission(root)
+ assert refusal is not None
+ assert refusal.code == "docker"
+ assert "docker pull" in refusal.update_command
+
+ def test_git_checkout_is_admitted(self, tmp_path, monkeypatch):
+ from hermes_cli.update_contract import evaluate_update_admission
+
+ root = tmp_path / "checkout"
+ root.mkdir()
+ (root / ".git").mkdir()
+ monkeypatch.setattr(
+ "hermes_cli.config.detect_install_method", lambda *a, **k: "git"
+ )
+ assert evaluate_update_admission(root) is None
+
+ def test_unknown_steward_falls_through_to_heuristics(self, tmp_path, monkeypatch):
+ """A stampless gitless tree is not refused by the steward rung —
+ the pre-existing heuristics keep the final say (an unknown tree used
+ to be admitted, and stays admitted)."""
+ from hermes_cli.update_contract import evaluate_update_admission
+
+ root = tmp_path / "bare"
+ root.mkdir()
+ monkeypatch.setattr(
+ "hermes_cli.config.detect_install_method", lambda *a, **k: "unknown"
+ )
+ assert evaluate_update_admission(root) is None
diff --git a/tests/hermes_cli/test_uninstall_dry_run.py b/tests/hermes_cli/test_uninstall_dry_run.py
index ec74c8e5c18..1c3d7c90441 100644
--- a/tests/hermes_cli/test_uninstall_dry_run.py
+++ b/tests/hermes_cli/test_uninstall_dry_run.py
@@ -8,8 +8,11 @@ def test_dry_run_prints_plan_without_mutating(monkeypatch, tmp_path, capsys):
project_root = tmp_path / "hermes-agent"
hermes_home = tmp_path / ".hermes"
project_root.mkdir()
+ # A .git dir marks the tree as a removable git checkout — without it the
+ # install-kind gate refuses before the dry-run plan prints.
+ (project_root / ".git").mkdir()
hermes_home.mkdir()
- (hermes_home / "config.yaml").write_text("model: {}\n")
+ (hermes_home / "config.yaml").write_text("model: {}\n", encoding="utf-8")
called = False
diff --git a/tests/hermes_cli/test_uninstall_install_kind.py b/tests/hermes_cli/test_uninstall_install_kind.py
new file mode 100644
index 00000000000..5a8bb61bbfe
--- /dev/null
+++ b/tests/hermes_cli/test_uninstall_install_kind.py
@@ -0,0 +1,234 @@
+"""Tests for the install-kind uninstall gate + the data-only mode.
+
+The rule under test: only a git checkout may have its code removed by the
+uninstaller. Sealed trees (Nix, the bundled desktop app, Docker) refuse the
+code-removing modes with the steward's own instructions, and the one mode
+valid everywhere — ``data`` — removes user data without touching code.
+
+Adapted from the restack branch: detection here reads the install stamp
+(``install-stamp.json`` with its required ``updateMechanism``) through
+``hermes_cli.steward`` instead of restack's ``installation.tree``.
+"""
+
+import json
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+import hermes_cli.uninstall as un
+from hermes_cli.steward import (
+ STEWARD_DESKTOP,
+ STEWARD_DOCKER,
+ STEWARD_NIX,
+ steward_uninstall_message,
+)
+
+
+# ---------------------------------------------------------------------------
+# steward_uninstall_message
+# ---------------------------------------------------------------------------
+
+
+def test_steward_uninstall_messages_name_the_steward():
+ assert "Nix" in steward_uninstall_message(STEWARD_NIX)
+ assert "Docker" in steward_uninstall_message(STEWARD_DOCKER)
+ # Unknown stewards fall back to a generic refusal that still names them.
+ assert "somepkg" in steward_uninstall_message("somepkg")
+
+
+def test_steward_desktop_message_is_per_platform():
+ win = steward_uninstall_message(STEWARD_DESKTOP, platform="win32")
+ mac = steward_uninstall_message(STEWARD_DESKTOP, platform="darwin")
+ linux = steward_uninstall_message(STEWARD_DESKTOP, platform="linux")
+ assert "Installed apps" in win
+ assert "Trash" in mac
+ assert "AppImage" in linux
+
+
+def test_all_refusals_point_at_the_data_mode():
+ # Every refusal must leave the user a working next step for their data.
+ # CLI stewards point at the CLI flag; desktop refusals deliberately
+ # point at the app's own data path.
+ for steward in (STEWARD_NIX, STEWARD_DOCKER, "somepkg"):
+ assert "hermes uninstall --data" in steward_uninstall_message(steward)
+ for platform in ("win32", "darwin", "linux"):
+ message = steward_uninstall_message(STEWARD_DESKTOP, platform=platform)
+ assert "Settings -> About" in message
+
+
+# ---------------------------------------------------------------------------
+# code_removal_refusal — the gate itself
+# ---------------------------------------------------------------------------
+
+
+def _fake_project_root(monkeypatch, tmp_path: Path, *, git: bool, distribution: "str | None" = None) -> Path:
+ root = tmp_path / "hermes-agent"
+ root.mkdir()
+ if git:
+ (root / ".git").mkdir()
+ if distribution is not None:
+ # The code-scoped stamp (see hermes_cli.steward.BUILD_INFO_NAME).
+ (root / "install-stamp.json").write_text(
+ json.dumps({"distribution": distribution, "updateMechanism": "external"})
+ , encoding="utf-8")
+ monkeypatch.setattr(un, "get_project_root", lambda: root)
+ return root
+
+
+def test_git_checkout_allows_code_removal(monkeypatch, tmp_path):
+ _fake_project_root(monkeypatch, tmp_path, git=True)
+ assert un.code_removal_refusal() is None
+
+
+def test_sealed_nix_tree_refuses_code_removal(monkeypatch, tmp_path):
+ _fake_project_root(monkeypatch, tmp_path, git=False, distribution="nix")
+ refusal = un.code_removal_refusal()
+ assert refusal is not None
+ assert "Nix" in refusal
+
+
+def test_sealed_desktop_tree_refuses_code_removal(monkeypatch, tmp_path):
+ _fake_project_root(monkeypatch, tmp_path, git=False, distribution="desktop-app")
+ refusal = un.code_removal_refusal()
+ assert refusal is not None
+ assert "managed by the desktop app" in refusal
+
+
+def test_stampless_sealed_tree_still_refuses(monkeypatch, tmp_path):
+ # No .git and no stamp: we cannot prove the tree is ours, so refuse.
+ _fake_project_root(monkeypatch, tmp_path, git=False)
+ assert un.code_removal_refusal() is not None
+
+
+def test_run_uninstall_exits_on_sealed_tree(monkeypatch, tmp_path, capsys):
+ _fake_project_root(monkeypatch, tmp_path, git=False, distribution="nix")
+ args = SimpleNamespace(yes=True, full=True, dry_run=False)
+ with pytest.raises(SystemExit) as exc:
+ un.run_uninstall(args)
+ assert exc.value.code == 1
+ assert "Nix" in capsys.readouterr().out
+
+
+def test_run_gui_uninstall_exits_on_sealed_tree(monkeypatch, tmp_path, capsys):
+ _fake_project_root(monkeypatch, tmp_path, git=False, distribution="desktop-app")
+ args = SimpleNamespace(yes=True)
+ with pytest.raises(SystemExit) as exc:
+ un.run_gui_uninstall(args)
+ assert exc.value.code == 1
+ assert "managed by the desktop app" in capsys.readouterr().out
+
+
+# ---------------------------------------------------------------------------
+# run_data_uninstall — user data only, on any install kind
+# ---------------------------------------------------------------------------
+
+
+def _make_home(tmp_path: Path) -> Path:
+ home = tmp_path / ".hermes"
+ (home / "sessions").mkdir(parents=True)
+ (home / "sessions" / "s1.json").write_text("{}", encoding="utf-8")
+ (home / "logs").mkdir()
+ (home / "config.yaml").write_text("x: 1\n", encoding="utf-8")
+ (home / ".env").write_text("KEY=secret\n", encoding="utf-8")
+ agent = home / "hermes-agent"
+ (agent / "hermes_cli").mkdir(parents=True)
+ (agent / "hermes_cli" / "__init__.py").write_text("", encoding="utf-8")
+ return home
+
+
+def test_run_data_uninstall_removes_data_keeps_code(monkeypatch, tmp_path):
+ home = _make_home(tmp_path)
+ monkeypatch.setattr(un, "get_hermes_home", lambda: home)
+ import hermes_cli.gui_uninstall as gu
+
+ monkeypatch.setattr(gu, "desktop_userdata_dir", lambda: tmp_path / "electron-userdata-none")
+
+ un.run_data_uninstall(SimpleNamespace(yes=True))
+
+ # Data gone.
+ assert not (home / "config.yaml").exists()
+ assert not (home / ".env").exists()
+ assert not (home / "sessions").exists()
+ assert not (home / "logs").exists()
+ # Code untouched — even on a sealed tree the data mode never touches it.
+ assert (home / "hermes-agent" / "hermes_cli" / "__init__.py").exists()
+
+
+def test_run_data_uninstall_removes_electron_userdata(monkeypatch, tmp_path):
+ home = _make_home(tmp_path)
+ userdata = tmp_path / "electron-userdata"
+ userdata.mkdir()
+ (userdata / "connection.json").write_text("{}", encoding="utf-8")
+ monkeypatch.setattr(un, "get_hermes_home", lambda: home)
+ import hermes_cli.gui_uninstall as gu
+
+ monkeypatch.setattr(gu, "desktop_userdata_dir", lambda: userdata)
+
+ un.run_data_uninstall(SimpleNamespace(yes=True))
+
+ assert not userdata.exists()
+
+
+def test_run_data_uninstall_works_on_sealed_trees(monkeypatch, tmp_path):
+ # The whole point of the data mode: no code-removal gate applies.
+ home = _make_home(tmp_path)
+ (home / "hermes-agent" / "install-stamp.json").write_text(
+ json.dumps({"distribution": "nix", "updateMechanism": "external"})
+ , encoding="utf-8")
+ monkeypatch.setattr(un, "get_hermes_home", lambda: home)
+ import hermes_cli.gui_uninstall as gu
+
+ monkeypatch.setattr(gu, "desktop_userdata_dir", lambda: tmp_path / "none")
+
+ un.run_data_uninstall(SimpleNamespace(yes=True))
+
+ assert not (home / "config.yaml").exists()
+ assert (home / "hermes-agent").exists()
+
+
+# ---------------------------------------------------------------------------
+# gui_install_summary — steward facts for the desktop UI
+# ---------------------------------------------------------------------------
+
+
+def test_gui_summary_reports_steward_and_gate(monkeypatch, tmp_path):
+ import hermes_cli.gui_uninstall as gu
+ from hermes_cli import steward as st
+
+ home = tmp_path / ".hermes"
+ home.mkdir()
+ monkeypatch.setattr(gu, "packaged_gui_app_paths", lambda: [])
+ monkeypatch.setattr(gu, "desktop_userdata_dir", lambda: tmp_path / "none")
+
+ # Sealed nix tree → steward named, code removal denied.
+ monkeypatch.setattr(st, "classify_install", lambda root: ("nix", False))
+ summary = gu.gui_install_summary(home)
+ assert summary["steward"] == "nix"
+ assert summary["code_removal_allowed"] is False
+
+ # Git checkout → ours to remove.
+ monkeypatch.setattr(st, "classify_install", lambda root: ("git", True))
+ summary = gu.gui_install_summary(home)
+ assert summary["steward"] == "git"
+ assert summary["code_removal_allowed"] is True
+
+
+# ---------------------------------------------------------------------------
+# module entrypoint routing
+# ---------------------------------------------------------------------------
+
+
+def test_module_entrypoint_routes_data_mode(monkeypatch):
+ calls = []
+ monkeypatch.setattr(un, "run_data_uninstall", lambda args: calls.append(("data", args)))
+ monkeypatch.setattr(un, "run_gui_uninstall", lambda args: calls.append(("gui", args)))
+ monkeypatch.setattr(un, "run_uninstall", lambda args: calls.append(("agent", args)))
+
+ assert un.main(["--mode", "data"]) == 0
+ assert calls[-1][0] == "data"
+ assert un.main(["--mode", "gui"]) == 0
+ assert calls[-1][0] == "gui"
+ assert un.main(["--mode", "full"]) == 0
+ assert calls[-1][0] == "agent"
+ assert calls[-1][1].full is True
diff --git a/tests/hermes_cli/test_update_channel.py b/tests/hermes_cli/test_update_channel.py
new file mode 100644
index 00000000000..8a142c144da
--- /dev/null
+++ b/tests/hermes_cli/test_update_channel.py
@@ -0,0 +1,336 @@
+"""Per-install update-channel records (hermes_cli/update_channel.py).
+
+Channel is config, keyed by the install id (sha16 of the canonical
+install-root path — inline helper, to be deduped with
+boot_bootstrap._install_key at assembly), never home-global. Mechanism
+comes from the stamp; external installs have no channel at all.
+"""
+import hashlib
+import json
+from pathlib import Path
+
+import pytest
+
+from hermes_cli.update_channel import (
+ CHANNEL_MAIN,
+ CHANNEL_NIGHTLY,
+ CHANNEL_STABLE,
+ default_channel,
+ install_id,
+ resolve_update_channel,
+ set_install_channel,
+ stale_channel_records,
+)
+
+
+def _stamp(root: Path, mechanism: str, tag: str | None = None) -> None:
+ root.mkdir(parents=True, exist_ok=True)
+ stamp = {"schemaVersion": 2, "updateMechanism": mechanism}
+ if tag is not None:
+ stamp["tag"] = tag
+ (root / "install-stamp.json").write_text(json.dumps(stamp))
+
+
+def _config_for(root: Path, channel: str) -> dict:
+ return {
+ "update": {
+ "installs": {
+ install_id(root): {"path": str(root), "channel": channel}
+ }
+ }
+ }
+
+
+class TestInstallId:
+ def test_path_derived_and_stable(self, tmp_path):
+ """The id hashes the canonical PATH — same path, same id, no matter
+ what the tree contains (survives electron-updater artifact swaps)."""
+ root = tmp_path / "install"
+ root.mkdir()
+ before = install_id(root)
+ _stamp(root, "electron-updater") # contents change...
+ assert install_id(root) == before # ...id does not
+
+ def test_two_installs_two_ids(self, tmp_path):
+ a = tmp_path / "a"
+ b = tmp_path / "b"
+ a.mkdir()
+ b.mkdir()
+ assert install_id(a) != install_id(b)
+
+ def test_matches_the_state_folder_key_derivation(self, tmp_path):
+ """sha256(canonical path)[:16] — the boot_bootstrap._install_key
+ contract, recomputed independently so the inline helper cannot
+ drift before the assembly-time dedupe."""
+ root = tmp_path / "install"
+ root.mkdir()
+ expected = hashlib.sha256(
+ str(root.resolve()).encode("utf-8")
+ ).hexdigest()[:16]
+ assert install_id(root) == expected
+
+
+class TestResolve:
+ def test_per_install_record_wins(self, tmp_path):
+ root = tmp_path / "install"
+ _stamp(root, "self")
+ config = _config_for(root, "stable")
+ assert resolve_update_channel(config, root) == CHANNEL_STABLE
+
+ def test_multi_install_isolation(self, tmp_path):
+ """Two installs, one config: each resolves its own record and a
+ missing record falls to the mechanism default — never the sibling's."""
+ a = tmp_path / "a"
+ b = tmp_path / "b"
+ _stamp(a, "self")
+ _stamp(b, "self")
+ config = _config_for(a, "stable")
+ assert resolve_update_channel(config, a) == CHANNEL_STABLE
+ assert resolve_update_channel(config, b) == CHANNEL_MAIN
+
+ def test_defaults_by_mechanism(self, tmp_path):
+ source = tmp_path / "src"
+ bundle = tmp_path / "bundle"
+ _stamp(source, "self")
+ _stamp(bundle, "electron-updater", tag="v0.27.0")
+ assert default_channel(source) == CHANNEL_MAIN
+ assert default_channel(bundle) == CHANNEL_STABLE
+ assert resolve_update_channel({}, source) == CHANNEL_MAIN
+ assert resolve_update_channel({}, bundle) == CHANNEL_STABLE
+
+ def test_nightly_artifact_defaults_to_its_own_feed(self, tmp_path):
+ """A nightly bundle with no per-install record tracks nightly.
+
+ The artifact publishes to nightly.yml (product-identity.cjs keys the
+ feed on this same tag). Defaulting it to stable made the updater ask
+ for nightly.yml under the newest STABLE release, which 404s and
+ leaves a fresh nightly install unable to update at all.
+ """
+ root = tmp_path / "nightly-bundle"
+ _stamp(root, "electron-updater", tag="v0.28.0-nightly.20260819171926")
+ assert default_channel(root) == CHANNEL_NIGHTLY
+ assert resolve_update_channel({}, root) == CHANNEL_NIGHTLY
+
+ def test_legacy_date_only_nightly_tag_is_a_nightly(self, tmp_path):
+ root = tmp_path / "legacy-nightly"
+ _stamp(root, "electron-updater", tag="v0.28.0-nightly.20260818")
+ assert default_channel(root) == CHANNEL_NIGHTLY
+
+ def test_explicit_record_still_overrides_the_artifact_default(self, tmp_path):
+ """The tag only supplies the DEFAULT: an opt-out must still work."""
+ root = tmp_path / "nightly-bundle"
+ _stamp(root, "electron-updater", tag="v0.28.0-nightly.20260819171926")
+ assert resolve_update_channel(_config_for(root, "stable"), root) == CHANNEL_STABLE
+
+ def test_a_nightly_tag_on_a_source_install_is_not_a_nightly_channel(self, tmp_path):
+ """Only electron-updater bundles have release feeds to track."""
+ root = tmp_path / "src"
+ _stamp(root, "self", tag="v0.28.0-nightly.20260819171926")
+ assert default_channel(root) == CHANNEL_MAIN
+
+ def test_stampless_tree_defaults_to_main(self, tmp_path):
+ root = tmp_path / "bare"
+ root.mkdir()
+ assert resolve_update_channel({}, root) == CHANNEL_MAIN
+
+ def test_nightly_normalizes_to_main_for_source(self, tmp_path):
+ root = tmp_path / "src"
+ _stamp(root, "self")
+ config = _config_for(root, "nightly")
+ assert resolve_update_channel(config, root) == CHANNEL_MAIN
+
+ def test_nightly_stays_for_electron_updater(self, tmp_path):
+ root = tmp_path / "bundle"
+ _stamp(root, "electron-updater")
+ config = _config_for(root, "nightly")
+ assert resolve_update_channel(config, root) == CHANNEL_NIGHTLY
+
+ def test_garbage_record_falls_to_default(self, tmp_path):
+ root = tmp_path / "src"
+ _stamp(root, "self")
+ config = _config_for(root, "yolo")
+ assert resolve_update_channel(config, root) == CHANNEL_MAIN
+
+
+class TestSetChannel:
+ def _home(self, tmp_path, monkeypatch):
+ home = tmp_path / ".hermes"
+ home.mkdir(exist_ok=True)
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ return home
+
+ def test_set_resolve_round_trip(self, tmp_path, monkeypatch):
+ import yaml
+
+ home = self._home(tmp_path, monkeypatch)
+ root = tmp_path / "install"
+ _stamp(root, "self")
+
+ sha16 = set_install_channel("stable", root)
+ assert sha16 == install_id(root)
+
+ written = yaml.safe_load((home / "config.yaml").read_text())
+ record = written["update"]["installs"][sha16]
+ assert record["channel"] == "stable"
+ assert record["path"] == str(root)
+ assert resolve_update_channel(written, root) == CHANNEL_STABLE
+
+ def test_preserves_other_config_and_other_installs(self, tmp_path, monkeypatch):
+ import yaml
+
+ home = self._home(tmp_path, monkeypatch)
+ other = tmp_path / "other"
+ other.mkdir()
+ (home / "config.yaml").write_text(
+ yaml.safe_dump(
+ {
+ "model": {"provider": "nous"},
+ "update": {
+ "installs": {
+ install_id(other): {"path": str(other), "channel": "nightly"}
+ }
+ },
+ }
+ )
+ )
+ root = tmp_path / "install"
+ _stamp(root, "self")
+ set_install_channel("stable", root)
+
+ written = yaml.safe_load((home / "config.yaml").read_text())
+ assert written["model"] == {"provider": "nous"}
+ assert written["update"]["installs"][install_id(other)]["channel"] == "nightly"
+ assert written["update"]["installs"][install_id(root)]["channel"] == "stable"
+
+ def test_external_mechanism_refuses(self, tmp_path, monkeypatch):
+ self._home(tmp_path, monkeypatch)
+ root = tmp_path / "nix-tree"
+ _stamp(root, "external")
+ with pytest.raises(ValueError, match="owned by"):
+ set_install_channel("stable", root)
+
+ def test_bad_channel_refuses(self, tmp_path, monkeypatch):
+ self._home(tmp_path, monkeypatch)
+ root = tmp_path / "install"
+ _stamp(root, "self")
+ with pytest.raises(ValueError, match="unknown channel"):
+ set_install_channel("beta", root)
+
+
+class TestSetChannelCLI:
+ """cmd_update --set-channel: the switch texts (design record)."""
+
+ def _args(self, **kw):
+ from types import SimpleNamespace
+
+ base = dict(check=False, gateway=False, branch=None, channel=None,
+ set_channel=None, install_id=False, plan=False)
+ base.update(kw)
+ return SimpleNamespace(**base)
+
+ def test_stable_switch_from_nightly_is_an_honest_wait(self, capsys):
+ from unittest.mock import patch
+
+ from hermes_cli.main import cmd_update
+
+ with (
+ patch("hermes_cli.config.is_managed", return_value=False),
+ patch("hermes_cli.config.detect_install_method", return_value="unknown"),
+ patch("hermes_cli.update_channel.set_install_channel", return_value="a" * 16),
+ patch(
+ "hermes_cli.steward.read_install_stamp",
+ return_value={
+ "updateMechanism": "electron-updater",
+ "displayVersion": "0.28.0-nightly.20260818",
+ },
+ ),
+ ):
+ with pytest.raises(SystemExit) as exc:
+ cmd_update(self._args(set_channel="stable"))
+ assert exc.value.code == 0
+ out = capsys.readouterr().out
+ assert "0.28.0-nightly.20260818" in out # names where you are
+ assert "v0.28.0" in out # names the wait target
+ assert "hermes-agent.nousresearch.com" in out # the impatient path
+
+ def test_nightly_optin_warns_about_forward_incompatible_state(self, capsys):
+ from unittest.mock import patch
+
+ from hermes_cli.main import cmd_update
+
+ with (
+ patch("hermes_cli.config.is_managed", return_value=False),
+ patch("hermes_cli.config.detect_install_method", return_value="unknown"),
+ patch("hermes_cli.update_channel.set_install_channel", return_value="a" * 16),
+ ):
+ with pytest.raises(SystemExit) as exc:
+ cmd_update(self._args(set_channel="nightly"))
+ assert exc.value.code == 0
+ out = capsys.readouterr().out
+ assert "forward-incompatible" in out
+
+ def test_install_id_prints_and_exits(self, capsys):
+ from unittest.mock import patch
+
+ from hermes_cli.main import cmd_update
+
+ with (
+ patch("hermes_cli.config.is_managed", return_value=False),
+ patch("hermes_cli.update_channel.install_id", return_value="b" * 16),
+ ):
+ with pytest.raises(SystemExit) as exc:
+ cmd_update(self._args(install_id=True))
+ assert exc.value.code == 0
+ assert "b" * 16 in capsys.readouterr().out
+
+
+class TestDoctorStaleness:
+ def test_missing_path_flagged(self, tmp_path):
+ gone = tmp_path / "gone"
+ config = {
+ "update": {"installs": {"deadbeefdeadbeef": {"path": str(gone), "channel": "main"}}}
+ }
+ stale = stale_channel_records(config)
+ assert [(sha, reason) for sha, _r, reason in stale] == [
+ ("deadbeefdeadbeef", "missing")
+ ]
+
+ def test_replaced_install_flagged(self, tmp_path):
+ """The recorded path exists but keys to a different sha16 — the
+ record is a leftover from a tree that used to live elsewhere."""
+ root = tmp_path / "install"
+ root.mkdir()
+ config = {
+ "update": {"installs": {"0" * 16: {"path": str(root), "channel": "main"}}}
+ }
+ stale = stale_channel_records(config)
+ assert [(sha, reason) for sha, _r, reason in stale] == [("0" * 16, "replaced")]
+
+ def test_unclaimed_record_flagged(self, tmp_path, monkeypatch):
+ """sha16 matches the path but no installs/<sha16>/install.json exists."""
+ home = tmp_path / ".hermes"
+ home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ root = tmp_path / "install"
+ root.mkdir()
+ config = _config_for(root, "main")
+ stale = stale_channel_records(config)
+ assert [(sha, reason) for sha, _r, reason in stale] == [
+ (install_id(root), "unclaimed")
+ ]
+
+ def test_healthy_record_not_flagged(self, tmp_path, monkeypatch):
+ home = tmp_path / ".hermes"
+ home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ root = tmp_path / "install"
+ _stamp(root, "self")
+ # The live install-state record the sha16 must be claimed by
+ # (boot_bootstrap.ensure_install_dir writes this at boot; that
+ # module is landing in a parallel lane, so write the marker
+ # directly — the layout IS the contract).
+ state = home / "installs" / install_id(root)
+ state.mkdir(parents=True)
+ (state / "install.json").write_text(json.dumps({"root": str(root)}))
+ config = _config_for(root, "main")
+ assert stale_channel_records(config) == []
diff --git a/tests/hermes_cli/test_update_channel_stable.py b/tests/hermes_cli/test_update_channel_stable.py
new file mode 100644
index 00000000000..ce8db0b3601
--- /dev/null
+++ b/tests/hermes_cli/test_update_channel_stable.py
@@ -0,0 +1,130 @@
+"""Tests for the stable update channel (tag-tracking) in hermes_cli/update_cmd.py."""
+
+from unittest.mock import patch
+
+from hermes_cli.update_cmd import (
+ _latest_release_tag_from_ls_remote,
+ _parse_release_tag,
+ _stable_channel_active,
+)
+
+
+class TestParseReleaseTag:
+ def test_final_releases_parse(self):
+ assert _parse_release_tag("v0.17.0") == (0, 17, 0)
+ assert _parse_release_tag("v10.2.33") == (10, 2, 33)
+ assert _parse_release_tag(" v1.2.3 ") == (1, 2, 3)
+
+ def test_prereleases_and_garbage_rejected(self):
+ for tag in ("v1.2.3-rc1", "v1.2.3-beta.1", "v1.2", "1.2.3", "release-1", "vv1.2.3", ""):
+ assert _parse_release_tag(tag) is None, tag
+
+ def test_nightly_tags_never_reach_the_stable_channel(self):
+ """The inverse direction of the nightly channel: nightly tags are
+ version-suffixed (v0.28.0-nightly.20260818), and the stable
+ selector's no-suffix rule is what keeps a nightly prerelease from
+ ever winning a stable-channel update. If this shape ever parses,
+ stable users get nightlies."""
+ assert _parse_release_tag("v0.28.0-nightly.20260818") is None
+ assert _parse_release_tag("v1.0.0-nightly.1") is None
+
+ def test_calver_tags_rejected(self):
+ """Historical CalVer tags (v2026.7.20) must not win a numeric sort.
+
+ The major component is capped at three digits, the same rule as
+ _SEMVER_TAG_RE in scripts/write_install_stamp.py and
+ latestReleaseFromLsRemote in apps/desktop. A four-digit year would
+ rank above every SemVer release forever.
+ """
+ assert _parse_release_tag("v2026.7.20") is None
+ assert _parse_release_tag("v1000.0.0") is None
+ assert _parse_release_tag("v999.0.0") == (999, 0, 0)
+
+ def test_numeric_ordering_not_lexicographic(self):
+ """v0.10.0 must sort above v0.9.0 — the whole point of tuple parsing."""
+ newer, older = _parse_release_tag("v0.10.0"), _parse_release_tag("v0.9.0")
+ assert newer is not None and older is not None
+ assert newer > older
+
+
+class TestLatestReleaseTagFromLsRemote:
+ def test_picks_newest_final_release(self):
+ output = (
+ "aaa1\trefs/tags/v0.9.0\n"
+ "bbb2\trefs/tags/v0.10.0\n"
+ "ccc3\trefs/tags/v0.10.1-rc1\n"
+ "ddd4\trefs/tags/some-other-tag\n"
+ )
+ tag, sha = _latest_release_tag_from_ls_remote(output)
+ assert tag == "v0.10.0"
+ assert sha == "bbb2"
+
+ def test_peeled_sha_wins_for_annotated_tags(self):
+ output = (
+ "tagobj\trefs/tags/v1.0.0\n"
+ "commitsha\trefs/tags/v1.0.0^{}\n"
+ )
+ tag, sha = _latest_release_tag_from_ls_remote(output)
+ assert tag == "v1.0.0"
+ assert sha == "commitsha"
+
+ def test_no_release_tags(self):
+ assert _latest_release_tag_from_ls_remote("aaa\trefs/tags/nightly\n") == (None, None)
+ assert _latest_release_tag_from_ls_remote("") == (None, None)
+
+ def test_malformed_lines_ignored(self):
+ output = "garbage line no tab\naaa\trefs/heads/main\nbbb\trefs/tags/v2.0.0\n"
+ assert _latest_release_tag_from_ls_remote(output) == ("v2.0.0", "bbb")
+
+
+class _Args:
+ def __init__(self, branch=None, channel=None):
+ self.branch = branch
+ self.channel = channel
+
+
+class TestStableChannelActive:
+ def test_explicit_branch_always_wins(self):
+ """--branch means main-style behavior regardless of channel config."""
+ assert _stable_channel_active(_Args(branch="bb/gui")) is False
+
+ def test_transient_channel_flag_wins(self):
+ """--channel is the per-invocation override (--set-channel persists);
+ no config read happens when it is present."""
+ assert _stable_channel_active(_Args(channel="stable")) is True
+ assert _stable_channel_active(_Args(channel="main")) is False
+ # nightly on a source tree normalizes to main, never stable.
+ assert _stable_channel_active(_Args(channel="nightly")) is False
+
+ def test_per_install_record_activates(self, tmp_path, monkeypatch):
+ from hermes_cli.update_channel import install_id
+
+ root = tmp_path / "install"
+ root.mkdir()
+ (root / "install-stamp.json").write_text(
+ '{"schemaVersion": 2, "updateMechanism": "self"}'
+ )
+ config = {
+ "update": {"installs": {install_id(root): {"path": str(root), "channel": "stable"}}}
+ }
+ import hermes_cli.update_cmd as update_cmd
+
+ monkeypatch.setattr(update_cmd._m(), "PROJECT_ROOT", root)
+ with patch("hermes_cli.config.load_config", return_value=config):
+ assert _stable_channel_active(_Args()) is True
+
+ def test_no_record_stays_main(self, tmp_path, monkeypatch):
+ root = tmp_path / "install"
+ root.mkdir()
+ (root / "install-stamp.json").write_text(
+ '{"schemaVersion": 2, "updateMechanism": "self"}'
+ )
+ import hermes_cli.update_cmd as update_cmd
+
+ monkeypatch.setattr(update_cmd._m(), "PROJECT_ROOT", root)
+ with patch("hermes_cli.config.load_config", return_value={"update": {"installs": {}}}):
+ assert _stable_channel_active(_Args()) is False
+
+ def test_config_failure_defaults_to_main(self):
+ with patch("hermes_cli.config.load_config", side_effect=RuntimeError("boom")):
+ assert _stable_channel_active(_Args()) is False
diff --git a/tests/hermes_cli/test_update_fleet_restart_pending.py b/tests/hermes_cli/test_update_fleet_restart_pending.py
index f8390047a25..bdc9945f768 100644
--- a/tests/hermes_cli/test_update_fleet_restart_pending.py
+++ b/tests/hermes_cli/test_update_fleet_restart_pending.py
@@ -40,7 +40,11 @@ def _make_head_moved_side_effect(pre_sha="abc123", post_sha="def456"):
return SimpleNamespace(returncode=0, stdout="3\n", stderr="")
if joined.endswith("rev-parse HEAD"):
- if calls["n"] == 0:
+ # The update flow's own captures: pre-pull (first call) sees
+ # pre_sha, post-pull (second call) sees post_sha. get_version_info
+ # is mocked in _patch_update_deps so the startup banner makes no
+ # rev-parse calls of its own.
+ if calls["n"] < 1:
calls["n"] += 1
return SimpleNamespace(returncode=0, stdout=f"{pre_sha}\n", stderr="")
return SimpleNamespace(returncode=0, stdout=f"{post_sha}\n", stderr="")
@@ -99,9 +103,37 @@ def _patch_update_deps(monkeypatch, tmp_path, run_side_effect):
)
monkeypatch.setattr(hermes_main, "_write_update_incomplete_marker", lambda: None)
monkeypatch.setattr(hermes_main, "_clear_update_incomplete_marker", lambda: None)
+ # _install_hangup_protection wraps sys.stdout in a mirror stream that
+ # survives the test and breaks later capsys captures — no-op it.
+ monkeypatch.setattr(
+ hermes_main,
+ "_install_hangup_protection",
+ lambda gateway_mode=False: {
+ "prev_stdout": None, "prev_stderr": None,
+ "log_file": None, "installed": False,
+ },
+ )
+ monkeypatch.setattr(hermes_main, "_finalize_update_output", lambda *a, **k: None)
+ # _check_and_apply_config_migration → _run_migrate_config_fresh →
+ # _reload_config_modules() force-reloads hermes_cli.config via
+ # importlib, replacing the module object pytest's capsys + the config
+ # tests' patches target. No-op the reload so the config module stays
+ # stable for later tests in the same process.
+ monkeypatch.setattr(
+ "hermes_cli.update_cmd._reload_config_modules",
+ lambda *a, **k: None,
+ )
monkeypatch.setattr(
hermes_main, "_finish_dashboard_update_cleanup", lambda *a, **k: None
)
+ # The startup version-info probe runs git rev-parse HEAD (and the
+ # result is cached per-process, so whether it runs depends on test
+ # order). Mock it so the head-moved mock's call counting only sees the
+ # update flow's own pre/post captures.
+ monkeypatch.setattr(
+ "hermes_cli.version_info.get_version_info",
+ lambda *a, **k: SimpleNamespace(),
+ )
monkeypatch.setattr(hermes_main, "_build_web_ui", lambda *a, **k: None)
monkeypatch.setattr(
update_cmd, "_venv_core_imports_healthy", lambda: (True, "")
@@ -125,6 +157,17 @@ def _patch_update_deps(monkeypatch, tmp_path, run_side_effect):
"hermes_cli.update_inventory.collect_runtime_inventory",
lambda: SimpleNamespace(runtimes=[], to_dict=lambda: {}),
)
+ # The restart phase imports discovery fns fresh after
+ # _purge_stale_hermes_modules (the update reloads code in-place), so
+ # module-attr mocks are lost; stub os.kill so the conftest live-system
+ # guard never fires on real pids. No gateways are expected, so the
+ # post-restart fleet matrix must not demand rows.
+ import os as _os_mod
+
+ monkeypatch.setattr(_os_mod, "kill", lambda *a, **k: None)
+ monkeypatch.setattr(
+ hermes_main, "_fleet_probe_expected_runtimes", lambda *a, **k: False
+ )
def _update_args():
diff --git a/tests/hermes_cli/test_update_head_moved_gate.py b/tests/hermes_cli/test_update_head_moved_gate.py
index f363dac4117..0be6d7962e1 100644
--- a/tests/hermes_cli/test_update_head_moved_gate.py
+++ b/tests/hermes_cli/test_update_head_moved_gate.py
@@ -31,10 +31,12 @@ def _make_head_moved_side_effect(pre_sha="abc123", post_sha="def456"):
if "rev-list" in joined:
return SimpleNamespace(returncode=0, stdout="3\n", stderr="")
- # git rev-parse HEAD — first call (pre-pull) returns pre_sha,
- # subsequent calls (post-pull) return post_sha.
+ # git rev-parse HEAD — pre-pull capture (first call) sees pre_sha;
+ # post-pull capture (second call) sees post_sha. get_version_info
+ # is mocked in _patch_update_deps so the startup banner makes no
+ # rev-parse calls of its own.
if joined.endswith("rev-parse HEAD"):
- if calls["n"] == 0:
+ if calls["n"] < 1:
calls["n"] += 1
return SimpleNamespace(returncode=0, stdout=f"{pre_sha}\n", stderr="")
return SimpleNamespace(returncode=0, stdout=f"{post_sha}\n", stderr="")
@@ -103,6 +105,34 @@ def _patch_update_deps(monkeypatch, tmp_path, run_side_effect):
# Short-circuit the long tail: dependency install + desktop build.
monkeypatch.setattr(hermes_main, "_write_update_incomplete_marker", lambda: None)
monkeypatch.setattr(hermes_main, "_clear_update_incomplete_marker", lambda: None)
+ # _install_hangup_protection wraps sys.stdout in a mirror stream that
+ # survives the test and breaks later capsys captures — no-op it.
+ monkeypatch.setattr(
+ hermes_main,
+ "_install_hangup_protection",
+ lambda gateway_mode=False: {
+ "prev_stdout": None, "prev_stderr": None,
+ "log_file": None, "installed": False,
+ },
+ )
+ monkeypatch.setattr(hermes_main, "_finalize_update_output", lambda *a, **k: None)
+ # _check_and_apply_config_migration → _run_migrate_config_fresh →
+ # _reload_config_modules() force-reloads hermes_cli.config via
+ # importlib, replacing the module object pytest's capsys + the config
+ # tests' patches target. No-op the reload so the config module stays
+ # stable for later tests in the same process.
+ monkeypatch.setattr(
+ "hermes_cli.update_cmd._reload_config_modules",
+ lambda *a, **k: None,
+ )
+ # The startup version-info probe runs git rev-parse HEAD (and the
+ # result is cached per-process, so whether it runs depends on test
+ # order). Mock it so the head-moved mock's call counting only sees the
+ # update flow's own pre/post captures.
+ monkeypatch.setattr(
+ "hermes_cli.version_info.get_version_info",
+ lambda *a, **k: SimpleNamespace(),
+ )
# Gateway restart path (called after a successful update).
monkeypatch.setattr(hermes_main, "_finish_dashboard_update_cleanup", lambda *a: None)
# Keep the (now surfaced — #78574) gateway auto-restart phase away from
@@ -111,7 +141,45 @@ def _patch_update_deps(monkeypatch, tmp_path, run_side_effect):
import hermes_cli.gateway as hermes_gateway
monkeypatch.setattr(
- hermes_gateway, "find_gateway_pids", lambda all_profiles=False: []
+ hermes_gateway,
+ "find_gateway_pids",
+ lambda *a, **k: [],
+ )
+ # The gateway restart phase also probes per-profile processes; return
+ # nothing so no real pid reaches the drain/kill loop (the conftest
+ # live-system guard would block the os.kill).
+ monkeypatch.setattr(
+ hermes_gateway, "find_profile_gateway_processes", lambda *a, **k: []
+ )
+ # pm-era update flow: the venv re-sync after a pull runs
+ # `pm.ensure.sync_venv`, which needs a real uv/venv. The test env has
+ # neither, so short-circuit it — the head-moved gate is what's under
+ # test, not dependency sync. (pm.ensure the package attribute is the
+ # `ensure` function; the module is reached via importlib.)
+ import importlib
+
+ _pm_ensure_mod = importlib.import_module("pm.ensure")
+
+ monkeypatch.setattr(_pm_ensure_mod, "sync_venv", lambda *a, **k: None)
+ # Fleet-restart verification (#93406): no gateways are expected (the
+ # pid probe above returns nothing), so the post-restart version matrix
+ # must not demand rows or fail the update.
+ monkeypatch.setattr(
+ hermes_main,
+ "_fleet_probe_expected_runtimes",
+ lambda *a, **k: False,
+ )
+ # The gateway restart phase imports discovery functions fresh AFTER
+ # _purge_stale_hermes_modules drops every cached module (the update
+ # reloads code in-place), so monkeypatching hermes_cli.gateway
+ # attributes is lost. The phase may still attempt os.kill on real
+ # pids; stub os.kill so the conftest live-system guard never fires —
+ # this test asserts the head-moved gate, not process teardown.
+ import os as _os_mod
+
+ monkeypatch.setattr(_os_mod, "kill", lambda *a, **k: None)
+ monkeypatch.setattr(
+ hermes_gateway, "kill_gateway_processes", lambda *a, **k: []
)
monkeypatch.setattr(
hermes_gateway, "supports_systemd_services", lambda: False
diff --git a/tests/hermes_cli/test_update_inventory.py b/tests/hermes_cli/test_update_inventory.py
index 6550c0c5afb..92302d5311f 100644
--- a/tests/hermes_cli/test_update_inventory.py
+++ b/tests/hermes_cli/test_update_inventory.py
@@ -35,7 +35,7 @@ def fleet(monkeypatch, tmp_path):
monkeypatch.setattr("hermes_cli.gateway.supports_systemd_services", lambda: True)
monkeypatch.setattr("hermes_cli.gateway.find_profile_gateway_processes", lambda exclude_pids=None: [])
monkeypatch.setattr(
- "hermes_cli.build_info.get_code_identity",
+ "hermes_cli.version_info.get_code_identity",
lambda refresh=False: {"sha": "a" * 40, "short_sha": "a" * 8, "version": "1.0", "source": "git"},
)
monkeypatch.setattr("hermes_cli.config.detect_install_method", lambda *a, **k: "git")
@@ -105,7 +105,7 @@ class TestCollectInventory:
for target in (
"hermes_cli.config.detect_install_method",
- "hermes_cli.build_info.get_code_identity",
+ "hermes_cli.version_info.get_code_identity",
"hermes_cli.profiles._get_default_hermes_home",
"hermes_cli.gateway._get_service_pids",
"hermes_cli.gateway.find_profile_gateway_processes",
diff --git a/tests/hermes_cli/test_update_parked_branch_guard.py b/tests/hermes_cli/test_update_parked_branch_guard.py
index 2508606b3a1..fefdac51814 100644
--- a/tests/hermes_cli/test_update_parked_branch_guard.py
+++ b/tests/hermes_cli/test_update_parked_branch_guard.py
@@ -562,11 +562,11 @@ def test_update_up_to_date_path_does_not_repark_merged_branch(
class _StopFlow(Exception):
pass
- import hermes_cli.managed_uv as managed_uv
+ import pm
monkeypatch.setattr(
- managed_uv,
- "update_managed_uv",
+ pm,
+ "ensure",
lambda *a, **k: (_ for _ in ()).throw(_StopFlow()),
)
args = SimpleNamespace(branch=None, yes=False, force=False, force_venv=False)
diff --git a/tests/hermes_cli/test_update_receipt.py b/tests/hermes_cli/test_update_receipt.py
index cb7634fd0b1..8f309816525 100644
--- a/tests/hermes_cli/test_update_receipt.py
+++ b/tests/hermes_cli/test_update_receipt.py
@@ -268,7 +268,7 @@ class TestFleetClassification:
json.dumps(record), encoding="utf-8"
)
monkeypatch.setattr(
- "hermes_cli.build_info.get_code_identity",
+ "hermes_cli.version_info.get_code_identity",
lambda refresh=False: {"sha": expected_sha, "short_sha": expected_sha[:8],
"version": "1.0", "source": "git"},
)
@@ -354,7 +354,7 @@ class TestGatewayStatusStamping:
import gateway.status as gs
monkeypatch.setattr(
- "hermes_cli.build_info.get_code_identity",
+ "hermes_cli.version_info.get_code_identity",
lambda refresh=False: {"sha": "c" * 40, "short_sha": "c" * 8,
"version": "2.0", "source": "git"},
)
@@ -368,7 +368,7 @@ class TestGatewayStatusStamping:
def _boom(refresh=False):
raise RuntimeError("no build info")
- monkeypatch.setattr("hermes_cli.build_info.get_code_identity", _boom)
+ monkeypatch.setattr("hermes_cli.version_info.get_code_identity", _boom)
record = gs._build_runtime_status_record()
# Must not raise, and must not stamp bogus values.
assert "code_sha" not in record
@@ -377,17 +377,19 @@ class TestGatewayStatusStamping:
class TestCodeIdentity:
def test_get_code_identity_shape(self):
- from hermes_cli.build_info import get_code_identity
+ from hermes_cli.version_info import get_code_identity
identity = get_code_identity(refresh=True)
assert set(identity) == {"sha", "short_sha", "version", "source"}
# Running from a git checkout in CI/dev: sha resolves via git.
if identity["sha"]:
assert identity["short_sha"] == identity["sha"][:8]
- assert identity["source"] in ("git", "build-file")
+ # Running from a git checkout in CI/dev: git provenance; packaged
+ # installs would report their stamp source instead.
+ assert identity["source"] != "unknown"
def test_get_code_identity_cached(self):
- from hermes_cli.build_info import get_code_identity
+ from hermes_cli.version_info import get_code_identity
first = get_code_identity(refresh=True)
second = get_code_identity()
diff --git a/tests/hermes_cli/test_venv_sync.py b/tests/hermes_cli/test_venv_sync.py
new file mode 100644
index 00000000000..ea20c90d510
--- /dev/null
+++ b/tests/hermes_cli/test_venv_sync.py
@@ -0,0 +1,336 @@
+"""venv_sync must work on trees where the venv does not exist yet.
+
+It is the stdlib-only-at-import pre-venv entry point: the installers call
+it on a fresh clone before any dependency is importable, and post_update
+calls it after a tree swap when the venv is not trustworthy. Its
+behaviour is driven with a FAKE uv — the module's job is deciding
+whether/how to call uv and what to record, not resolving packages, and a
+fake makes every decision observable (argv, env, cwd) without network.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import stat
+import subprocess
+import sys
+import textwrap
+from pathlib import Path
+
+import pytest
+
+from hermes_cli import venv_sync
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+
+
+def _run_bare(snippet: str) -> subprocess.CompletedProcess:
+ """Run a snippet in an isolated interpreter (-I: no env, no user site)
+ from the repo root, so a bare import graph is what gets exercised."""
+ return subprocess.run(
+ [sys.executable, "-I", "-c", textwrap.dedent(snippet)],
+ capture_output=True,
+ text=True,
+ cwd=REPO_ROOT,
+ timeout=120,
+ )
+
+
+# ── the stdlib-only contract, RUN not parsed ─────────────────────────────
+
+
+class TestStdlibOnly:
+ def test_imports_and_answers_bare(self, tmp_path):
+ """The whole CLI surface must survive a stripped interpreter."""
+ result = _run_bare(
+ f"""
+ import sys
+ sys.path.insert(0, {str(REPO_ROOT)!r})
+ from hermes_cli import venv_sync
+ root = {str(tmp_path)!r}
+ out = venv_sync.sync(root, check=True)
+ assert out["state"] == "failed", out # empty dir: no pyproject
+ print("ok")
+ """
+ )
+ assert result.returncode == 0, result.stderr
+
+ def test_no_third_party_module_ends_up_loaded(self):
+ """Importing it must not drag in ANY non-stdlib module.
+
+ Check sys.modules after import, because a parser cannot see lazy
+ or conditional imports fire. First-party pm is allowed at SYNC
+ time but must not load at IMPORT time either — the bare import
+ happens on trees where even reading pm's ledger is premature.
+
+ Measure the *delta*: snapshot the foreign modules already loaded
+ before the import and only flag what the import adds. A hardcoded
+ allowlist of ".pth"-injected bootstrap names is not portable — the
+ interpreter loads ``.pth`` hooks at startup (setuptools'
+ ``_distutils_hack``, pywin32's ``pywin32_bootstrap``, the
+ editable-install ``__editable___…_finder``, ``_virtualenv``…) before
+ the snippet runs, and that set varies per platform and install
+ shape. A before/after diff is sensitive to the import and immune to
+ that harness noise.
+ """
+ result = _run_bare(
+ f"""
+ import sys
+ sys.path.insert(0, {str(REPO_ROOT)!r})
+ stdlib = set(sys.stdlib_module_names)
+
+ def _foreign():
+ return {{
+ name.split(".")[0]
+ for name, mod in sys.modules.items()
+ if mod is not None and getattr(mod, "__file__", None)
+ }} - stdlib
+
+ before = _foreign()
+ import hermes_cli.venv_sync
+ dragged_in = {{n for n in _foreign() - before if n != "hermes_cli"}}
+ assert not dragged_in, f"venv_sync loaded non-stdlib: {{dragged_in}}"
+ print("ok")
+ """
+ )
+ assert result.returncode == 0, result.stderr
+
+
+# ── behaviour, driven through a fake uv ──────────────────────────────────
+
+
+def _fake_uv(tmp_path: Path, exit_code: int = 0) -> tuple:
+ """A uv that records its invocation and exits as told.
+
+ Returns ``(binary_path, record_path)``; the binary shape is
+ platform-appropriate (a .bat trampoline on Windows, a shebang script
+ on POSIX) so subprocess can execute it directly.
+ """
+ record = tmp_path / "uv-calls.jsonl"
+ recorder = tmp_path / "uv_recorder.py"
+ recorder.write_text(
+ "import json, os, sys\n"
+ f"with open({str(record)!r}, 'a') as f:\n"
+ " f.write(json.dumps({\n"
+ " 'argv': sys.argv[1:],\n"
+ " 'cwd': os.getcwd(),\n"
+ " 'venv_env': os.environ.get('UV_PROJECT_ENVIRONMENT'),\n"
+ " 'virtual_env': os.environ.get('VIRTUAL_ENV'),\n"
+ " }) + '\\n')\n"
+ f"raise SystemExit({exit_code})\n",
+ encoding="utf-8",
+ )
+ if os.name == "nt":
+ binary = tmp_path / "uv.bat"
+ binary.write_text(
+ f'@echo off\r\n"{sys.executable}" "{recorder}" %*\r\n', encoding="utf-8"
+ )
+ else:
+ binary = tmp_path / "uv"
+ binary.write_text(
+ f'#!/bin/sh\nexec "{sys.executable}" "{recorder}" "$@"\n', encoding="utf-8"
+ )
+ binary.chmod(binary.stat().st_mode | stat.S_IEXEC)
+ return binary, record
+
+
+def _checkout(tmp_path: Path, name: str = "co") -> Path:
+ """A minimal tree venv_sync classifies as a checkout."""
+ root = tmp_path / name
+ (root / ".git").mkdir(parents=True)
+ (root / "pyproject.toml").write_text("[project]\nname='x'\n")
+ (root / "uv.lock").write_text("lock-v1\n")
+ return root
+
+
+def _wire_uv(monkeypatch, tmp_path: Path, exit_code: int = 0) -> Path:
+ """Point venv_sync's managed-uv resolution at a fake binary.
+
+ The resolution itself is pm's (pm.ensure.uv) and pm's ledger wiring
+ has its own tests; here the decision layer is under test, so the
+ seam is venv_sync._managed_uv.
+ """
+ binary, record = _fake_uv(tmp_path, exit_code)
+ monkeypatch.setattr(
+ venv_sync, "_managed_uv", lambda: (str(binary), dict(os.environ))
+ )
+ return record
+
+
+class TestCheckoutSync:
+ def test_a_stale_checkout_syncs_frozen_against_its_own_venv(
+ self, tmp_path, monkeypatch
+ ):
+ root = _checkout(tmp_path)
+ record = _wire_uv(monkeypatch, tmp_path)
+
+ out = venv_sync.sync(root)
+
+ assert out == {"state": "synced", "ok": True}
+ call = json.loads(record.read_text().splitlines()[0])
+ assert call["argv"] == ["sync", "--frozen"]
+ assert call["venv_env"] == str(root / "venv")
+ assert call["virtual_env"] is None # caller's venv must not leak in
+ assert Path(call["cwd"]) == root
+
+ def test_a_current_checkout_never_invokes_uv(self, tmp_path, monkeypatch):
+ """The stamp is the fast path: currency costs a file read."""
+ root = _checkout(tmp_path)
+ record = _wire_uv(monkeypatch, tmp_path)
+
+ assert venv_sync.sync(root)["state"] == "synced"
+ assert venv_sync.sync(root)["state"] == "current"
+ assert len(record.read_text().splitlines()) == 1 # one call total
+
+ def test_an_edited_pyproject_invalidates_the_stamp(
+ self, tmp_path, monkeypatch
+ ):
+ """Extras edits without a lock bump still re-sync."""
+ root = _checkout(tmp_path)
+ _wire_uv(monkeypatch, tmp_path)
+ assert venv_sync.sync(root)["state"] == "synced"
+
+ (root / "pyproject.toml").write_text("[project]\nname='y'\n")
+
+ assert venv_sync.sync(root)["state"] == "synced"
+
+ def test_a_lockless_tree_drops_the_frozen_flag(self, tmp_path, monkeypatch):
+ """A clone without uv.lock still syncs — unfrozen."""
+ root = _checkout(tmp_path)
+ (root / "uv.lock").unlink()
+ record = _wire_uv(monkeypatch, tmp_path)
+
+ assert venv_sync.sync(root)["state"] == "synced"
+ call = json.loads(record.read_text().splitlines()[0])
+ assert call["argv"] == ["sync"]
+
+ def test_a_failed_sync_writes_no_stamp(self, tmp_path, monkeypatch):
+ """A failure must leave the next run trying again, not skipping."""
+ root = _checkout(tmp_path)
+ _wire_uv(monkeypatch, tmp_path, exit_code=3)
+
+ out = venv_sync.sync(root)
+
+ assert out["state"] == "failed" and "3" in out["detail"]
+ assert venv_sync.read_stamp(root) == {}
+
+ def test_check_mode_reports_and_changes_nothing(self, tmp_path, monkeypatch):
+ root = _checkout(tmp_path)
+ record = _wire_uv(monkeypatch, tmp_path)
+
+ out = venv_sync.sync(root, check=True)
+
+ assert out["state"] == "would-sync"
+ assert not record.exists() # no uv call
+ assert venv_sync.read_stamp(root) == {}
+
+ def test_no_managed_uv_is_a_failure_that_names_the_fix(
+ self, tmp_path, monkeypatch
+ ):
+ root = _checkout(tmp_path)
+ # pm has nothing installed here and may not lazy-install.
+ monkeypatch.setenv("HERMES_RUNTIME_DIR", str(tmp_path / "empty-store"))
+ monkeypatch.setenv("HERMES_DISABLE_LAZY_INSTALLS", "1")
+
+ out = venv_sync.sync(root)
+
+ assert out["state"] == "failed"
+ assert "pm install" in out["detail"]
+
+ def test_own_tree_delegates_to_pms_venv_ledger(self, tmp_path, monkeypatch):
+ """When the root IS the running tree, pm.sync_venv owns the work
+ (one extras ledger, one authority) — no direct uv drive."""
+ root = _checkout(tmp_path)
+ from pm import paths as pm_paths
+
+ monkeypatch.setattr(pm_paths, "repo_root", lambda: root)
+ calls = []
+
+ import pm
+
+ monkeypatch.setattr(pm, "sync_venv", lambda explicit=False: calls.append(explicit))
+
+ out = venv_sync.sync(root)
+
+ assert out == {"state": "synced", "ok": True}
+ assert calls == [True]
+
+
+class TestSealedTrees:
+ def test_a_sealed_tree_is_a_clean_noop(self, tmp_path, monkeypatch):
+ """The desktop payload and nix bundle must not fail, must not sync."""
+ root = tmp_path / "sealed"
+ root.mkdir()
+ (root / "install-stamp.json").write_text(
+ json.dumps({"commit": "abc123", "payload": "full", "updateMechanism": "electron-updater"})
+ )
+ record = _wire_uv(monkeypatch, tmp_path)
+
+ out = venv_sync.sync(root)
+
+ assert out == {"state": "sealed", "ok": True}
+ assert not record.exists()
+
+ def test_a_dev_tree_with_both_stamp_and_git_is_a_checkout(
+ self, tmp_path, monkeypatch
+ ):
+ root = _checkout(tmp_path)
+ (root / "install-stamp.json").write_text(
+ json.dumps({"commit": "abc", "updateMechanism": "electron-updater"})
+ )
+ _wire_uv(monkeypatch, tmp_path)
+
+ assert venv_sync.sync(root)["state"] == "synced"
+
+ def test_a_stamp_without_update_mechanism_is_a_build_lane_bug(self, tmp_path):
+ root = tmp_path / "sealed"
+ root.mkdir()
+ (root / "install-stamp.json").write_text(json.dumps({"commit": "abc"}))
+ with pytest.raises(RuntimeError, match="updateMechanism"):
+ venv_sync.sync(root)
+
+
+class TestCliContract:
+ def test_json_output_and_exit_codes(self, tmp_path):
+ """post_update and the installers read exactly this."""
+ root = tmp_path / "sealed"
+ root.mkdir()
+ (root / "install-stamp.json").write_text(
+ json.dumps({"commit": "x", "updateMechanism": "electron-updater"})
+ )
+
+ proc = subprocess.run(
+ [
+ sys.executable,
+ "-m",
+ "hermes_cli.venv_sync",
+ "--project-root",
+ str(root),
+ "--json",
+ ],
+ capture_output=True,
+ text=True,
+ cwd=REPO_ROOT,
+ )
+
+ assert proc.returncode == 0, proc.stderr
+ assert json.loads(proc.stdout) == {"state": "sealed", "ok": True}
+
+ def test_failure_exits_nonzero(self, tmp_path):
+ proc = subprocess.run(
+ [
+ sys.executable,
+ "-m",
+ "hermes_cli.venv_sync",
+ "--project-root",
+ str(tmp_path), # empty dir: no pyproject, no stamp
+ "--json",
+ ],
+ capture_output=True,
+ text=True,
+ cwd=REPO_ROOT,
+ )
+
+ assert proc.returncode == 1
+ assert json.loads(proc.stdout)["state"] == "failed"
diff --git a/tests/hermes_cli/test_version_info.py b/tests/hermes_cli/test_version_info.py
new file mode 100644
index 00000000000..c82c57d42cd
--- /dev/null
+++ b/tests/hermes_cli/test_version_info.py
@@ -0,0 +1,201 @@
+import json
+from unittest.mock import MagicMock, patch
+
+from hermes_cli.version_info import (
+ VersionInfo,
+ _derived_version,
+ _reset_version_info_cache,
+ _resolve_stamp_file,
+ _stamp_version_info,
+ get_version_info,
+)
+
+
+from hermes_cli import __release_date__ as RELEASE_DATE
+from hermes_cli import __version__ as VERSION
+
+
+def setup_function():
+ _reset_version_info_cache()
+
+
+def test_derived_version_shows_plus_question_for_dirty_unknown_distance():
+ assert _derived_version("0.19.0", None, dirty=True) == "0.19.0+?"
+ assert _derived_version("0.19.0", None, dirty=False) == "0.19.0"
+ assert _derived_version("0.19.0", 5, dirty=True) == "0.19.0+5"
+ assert _derived_version("0.19.0", 0, dirty=True) == "0.19.0"
+
+
+def test_stamp_version_info_reads_nix_stamp(tmp_path, monkeypatch):
+ stamp = {
+ "schemaVersion": 2,
+ "commit": "a" * 40,
+ "branch": "feature/version",
+ "baseVersion": "0.19.0",
+ "displayVersion": "0.19.0+3",
+ "distance": 3,
+ "dirty": False,
+ "source": "nix",
+ "distribution": "nix",
+ "updateMechanism": "external",
+ }
+ stamp_file = tmp_path / "install-stamp.json"
+ stamp_file.write_text(json.dumps(stamp))
+ monkeypatch.setattr("hermes_cli.version_info._resolve_stamp_file", lambda: stamp_file)
+
+ info = get_version_info()
+
+ assert info == VersionInfo("0.19.0", "0.19.0+3", 3, "a" * 40, "feature/version", "nix", distribution="nix")
+
+
+def test_stamp_version_info_preserves_ci_provenance_and_docker_distribution(tmp_path, monkeypatch):
+ stamp = {"commit": "d" * 40, "source": "ci", "distribution": "docker", "updateMechanism": "external"}
+ stamp_file = tmp_path / "install-stamp.json"
+ stamp_file.write_text(json.dumps(stamp))
+ monkeypatch.setattr("hermes_cli.version_info._resolve_stamp_file", lambda: stamp_file)
+
+ info = get_version_info()
+
+ assert info.source == "ci"
+ assert info.distribution == "docker"
+
+
+def test_stamp_version_info_preserves_missing_branch(tmp_path, monkeypatch):
+ stamp = {
+ "schemaVersion": 2,
+ "commit": "b" * 40,
+ "branch": None,
+ "baseVersion": "0.19.0",
+ "displayVersion": "0.19.0+?",
+ "distance": None,
+ "dirty": True,
+ "source": "docker",
+ "updateMechanism": "external",
+ }
+ stamp_file = tmp_path / "install-stamp.json"
+ stamp_file.write_text(json.dumps(stamp))
+ monkeypatch.setattr("hermes_cli.version_info._resolve_stamp_file", lambda: stamp_file)
+
+ info = get_version_info()
+
+ assert info == VersionInfo("0.19.0", "0.19.0+?", None, "b" * 40, None, "docker", True)
+
+
+def test_stamp_version_info_ignores_fallback_commit(tmp_path, monkeypatch):
+ """All-zero commit means the stamp has no real SHA — skip it."""
+ stamp = {
+ "schemaVersion": 2,
+ "commit": "0" * 40,
+ "branch": "main",
+ "source": "fallback",
+ "updateMechanism": "self",
+ }
+ stamp_file = tmp_path / "install-stamp.json"
+ stamp_file.write_text(json.dumps(stamp))
+ monkeypatch.setattr("hermes_cli.version_info._resolve_stamp_file", lambda: stamp_file)
+ monkeypatch.setattr("hermes_cli.version_info._resolve_repo_dir", lambda: None)
+
+ info = get_version_info()
+
+ assert info.source == "unknown"
+ assert info.commit is None
+
+
+def test_stamp_version_info_returns_none_when_file_missing(tmp_path, monkeypatch):
+ monkeypatch.setattr("hermes_cli.version_info._resolve_stamp_file", lambda: None)
+ assert _stamp_version_info() is None
+
+
+def test_get_version_info_counts_commits_after_semver_tag(tmp_path, monkeypatch):
+ repo = tmp_path / "repo"
+ (repo / ".git").mkdir(parents=True)
+ monkeypatch.setattr("hermes_cli.version_info._resolve_stamp_file", lambda: None)
+ monkeypatch.setattr("hermes_cli.version_info._resolve_repo_dir", lambda: repo)
+
+ def run(command, **_kwargs):
+ output = {
+ ("git", "rev-parse", "HEAD"): "b" * 40,
+ ("git", "branch", "--show-current"): "feature/version",
+ ("git", "status", "--porcelain", "-uno"): "",
+ ("git", "rev-list", "--count", f"v{VERSION}..HEAD"): "3",
+ ("git", "log", "-1", "--format=%ct", "HEAD"): "1718662620",
+ }[tuple(command)]
+ return MagicMock(returncode=0, stdout=f"{output}\n")
+
+ with patch("hermes_cli.version_info.subprocess.run", side_effect=run):
+ info = get_version_info()
+
+ assert info == VersionInfo(VERSION, f"{VERSION}+3", 3, "b" * 40, "feature/version", "git", False, 1718662620)
+
+
+def test_get_version_info_falls_back_to_legacy_release_date_tag(tmp_path, monkeypatch):
+ repo = tmp_path / "repo"
+ (repo / ".git").mkdir(parents=True)
+ monkeypatch.setattr("hermes_cli.version_info._resolve_stamp_file", lambda: None)
+ monkeypatch.setattr("hermes_cli.version_info._resolve_repo_dir", lambda: repo)
+
+ calls = []
+
+ def run(command, **_kwargs):
+ calls.append(tuple(command))
+ if tuple(command) == ("git", "rev-list", "--count", f"v{VERSION}..HEAD"):
+ return MagicMock(returncode=1, stdout="")
+ output = {
+ ("git", "rev-parse", "HEAD"): "c" * 40,
+ ("git", "branch", "--show-current"): "",
+ ("git", "status", "--porcelain", "-uno"): " M hermes_cli/version_info.py",
+ ("git", "rev-list", "--count", f"v{RELEASE_DATE}..HEAD"): "2",
+ ("git", "log", "-1", "--format=%ct", "HEAD"): "1718662620",
+ }[tuple(command)]
+ return MagicMock(returncode=0, stdout=f"{output}\n")
+
+ with patch("hermes_cli.version_info.subprocess.run", side_effect=run):
+ info = get_version_info()
+
+ assert info.derived_version == f"{VERSION}+2"
+ assert info.branch is None
+ assert info.dirty is True
+ assert ("git", "rev-list", "--count", f"v{RELEASE_DATE}..HEAD") in calls
+
+
+def test_get_version_info_unknown_when_no_stamp_and_no_git(monkeypatch):
+ from pathlib import Path
+
+ monkeypatch.setattr("hermes_cli.version_info._resolve_stamp_file", lambda: None)
+ monkeypatch.setattr("hermes_cli.version_info._resolve_repo_dir", lambda: None)
+
+ info = get_version_info()
+
+ assert info.base_version == VERSION
+ assert info.derived_version == VERSION
+ assert info.distance is None
+ assert info.commit is None
+ assert info.source == "unknown"
+
+
+def test_resolve_stamp_file_honors_install_root(tmp_path, monkeypatch):
+ """Sealed installs (the Nix wrapper) point HERMES_INSTALL_ROOT at the stamp dir."""
+ stamp = {"commit": "e" * 40, "source": "nix", "distribution": "nix", "updateMechanism": "external"}
+ (tmp_path / "install-stamp.json").write_text(json.dumps(stamp))
+ monkeypatch.setenv("HERMES_INSTALL_ROOT", str(tmp_path))
+
+ assert _resolve_stamp_file() == tmp_path / "install-stamp.json"
+
+ info = get_version_info()
+ assert info.commit == "e" * 40
+ assert info.source == "nix"
+ assert info.distribution == "nix"
+
+
+def test_resolve_stamp_file_install_root_without_stamp_is_none(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_INSTALL_ROOT", str(tmp_path))
+ assert _resolve_stamp_file() is None
+
+
+def test_resolve_stamp_file_falls_back_to_code_root_when_env_unset(tmp_path, monkeypatch):
+ monkeypatch.delenv("HERMES_INSTALL_ROOT", raising=False)
+ stamp = {"commit": "f" * 40, "source": "docker", "updateMechanism": "external"}
+ (tmp_path / "install-stamp.json").write_text(json.dumps(stamp))
+ monkeypatch.setattr("hermes_cli.version_info._CODE_ROOT", tmp_path)
+
+ assert _resolve_stamp_file() == tmp_path / "install-stamp.json"
diff --git a/tests/hermes_cli/test_windows_native_docs.py b/tests/hermes_cli/test_windows_native_docs.py
index 2594ff8d48d..b996d0b5196 100644
--- a/tests/hermes_cli/test_windows_native_docs.py
+++ b/tests/hermes_cli/test_windows_native_docs.py
@@ -15,7 +15,7 @@ def test_windows_native_install_path_docs_match_installer() -> None:
"C:\\Users\\<you>\\AppData\\Local\\hermes\\bin\\hermes.exe"
) in doc
# Installer exposes $HermesHome\bin, and must copy the launchers into it.
- assert '$hermesBin = "$HermesHome\\bin"' in install
+ assert 'Join-Path $HermesHome "bin"' in install
assert "hermes.exe" in install and "hermes-acp.exe" in install
# Guard against regressions to either legacy layout.
assert '$hermesBin = "$InstallDir\\venv\\Scripts"' not in install
diff --git a/tests/installation/__init__.py b/tests/installation/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/tests/installation/test_update_mechanism.py b/tests/installation/test_update_mechanism.py
new file mode 100644
index 00000000000..55ada0a31ee
--- /dev/null
+++ b/tests/installation/test_update_mechanism.py
@@ -0,0 +1,69 @@
+"""The stamp's required ``updateMechanism`` field — the writer's contract.
+
+Writer: scripts/write_install_stamp.py refuses to build a stamp without a
+valid mechanism. Stamp readers HARD-FAIL a stamp missing the field: a
+mechanism-less stamp is a build-lane bug, and guessing would misroute
+updates for every install of that artifact. (The reader-side tests land
+with the reader port; the build-lane pin tests land when the packager
+lanes are wired to this writer.)
+"""
+import json
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+REPO_ROOT = Path(__file__).parent.parent.parent
+sys.path.insert(0, str(REPO_ROOT / "scripts"))
+
+from write_install_stamp import UPDATE_MECHANISMS, build_stamp # noqa: E402
+
+
+class TestWriter:
+ @pytest.mark.parametrize("mechanism", UPDATE_MECHANISMS)
+ def test_valid_mechanisms_are_emitted(self, mechanism):
+ stamp = build_stamp(
+ commit="a" * 40, source="ci", update_mechanism=mechanism
+ )
+ assert stamp["updateMechanism"] == mechanism
+
+ def test_invalid_mechanism_refused(self):
+ with pytest.raises(SystemExit):
+ build_stamp(commit="a" * 40, update_mechanism="carrier-pigeon")
+
+ def test_mechanism_is_required_by_the_cli(self, tmp_path):
+ """argparse enforces --update-mechanism; a lane that forgets it dies."""
+ out = tmp_path / "install-stamp.json"
+ result = subprocess.run(
+ [
+ sys.executable,
+ str(REPO_ROOT / "scripts" / "write_install_stamp.py"),
+ "--output", str(out),
+ "--commit", "b" * 40,
+ ],
+ capture_output=True,
+ text=True,
+ timeout=30,
+ )
+ assert result.returncode != 0
+ assert "--update-mechanism" in result.stderr
+ assert not out.exists()
+
+ def test_cli_emits_the_field(self, tmp_path):
+ out = tmp_path / "install-stamp.json"
+ result = subprocess.run(
+ [
+ sys.executable,
+ str(REPO_ROOT / "scripts" / "write_install_stamp.py"),
+ "--output", str(out),
+ "--commit", "c" * 40,
+ "--distribution", "docker",
+ "--update-mechanism", "external",
+ ],
+ capture_output=True,
+ text=True,
+ timeout=30,
+ )
+ assert result.returncode == 0, result.stderr
+ assert json.loads(out.read_text(encoding="utf-8-sig"))["updateMechanism"] == "external"
diff --git a/tests/scripts/test_release_nightly.py b/tests/scripts/test_release_nightly.py
new file mode 100644
index 00000000000..f49edd84ed3
--- /dev/null
+++ b/tests/scripts/test_release_nightly.py
@@ -0,0 +1,301 @@
+"""Nightly release plumbing in scripts/release.py.
+
+The nightly channel's whole safety story is tag SHAPES: nightly tags
+carry a -nightly.YYYYMMDD suffix, every stable selector requires the
+no-suffix shape, and the version math (next-MINOR over stable) makes
+electron-updater's semver ordering implement both channel-switch
+directions. These tests pin the shapes and the math; the workflow only
+provides credentials.
+"""
+
+import importlib.util
+from datetime import datetime, timezone
+from pathlib import Path
+
+import pytest
+
+_RELEASE_PATH = Path(__file__).resolve().parents[2] / "scripts" / "release.py"
+_SPEC = importlib.util.spec_from_file_location("hermes_release_nightly", _RELEASE_PATH)
+assert _SPEC and _SPEC.loader
+release = importlib.util.module_from_spec(_SPEC)
+_SPEC.loader.exec_module(release)
+
+
+class TestNightlyTagShape:
+ def test_nightly_tag_for_date_is_next_patch(self):
+ """The authority's math: current stable's patch + 1, any patch."""
+ assert release.nightly_tag_for_date("0.27.4", "20260818103000") == "v0.27.5-nightly.20260818103000"
+ assert release.nightly_tag_for_date("1.4.0", "20261231235959") == "v1.4.1-nightly.20261231235959"
+
+ def test_v_prefixed_stable_tag_accepted(self):
+ """cmd_nightly passes the stable TAG (with the v) — the authority
+ strips it, so both forms produce the same tag."""
+ assert release.nightly_tag_for_date("v0.27.4", "20260818103000") == "v0.27.5-nightly.20260818103000"
+
+ def test_shape_round_trips_through_the_nightly_matcher(self):
+ tag = release.nightly_tag_for_date("0.27.4", "20260818103000")
+ assert release._NIGHTLY_TAG_RE.fullmatch(tag)
+
+ def test_legacy_date_only_shape_still_matches(self):
+ """Readers stay tolerant of the original 8-digit suffix so an
+ already-published nightly keeps parsing (prune, last-nightly)."""
+ assert release._NIGHTLY_TAG_RE.fullmatch("v0.28.0-nightly.20260818")
+
+ def test_nightly_shape_is_invisible_to_the_stable_selector(self):
+ """THE invariant: a nightly tag must never parse as stable —
+ otherwise stable users update onto nightlies."""
+ for tag in (
+ release.nightly_tag_for_date("0.27.4", "20260818103000"),
+ "v0.28.0-nightly.20260818",
+ ):
+ assert release._SEMVER_TAG_RE.fullmatch(tag) is None, tag
+
+ def test_stable_shape_is_invisible_to_the_nightly_matcher(self):
+ assert release._NIGHTLY_TAG_RE.fullmatch("v0.27.2") is None
+ # Legacy CalVer must not match either (v2026.7.20 has 20-prefixed
+ # components that could fool a sloppy pattern).
+ assert release._NIGHTLY_TAG_RE.fullmatch("v2026.7.20") is None
+
+ def test_same_day_nightlies_order_chronologically(self):
+ """Second precision exists so manual fires can stack in one day;
+ fixed-length pure-numeric identifiers order the same lexically
+ (git -v:refname) and numerically (semver prerelease compare)."""
+ a = release.nightly_tag_for_date("0.27.4", "20260818090000")
+ b = release.nightly_tag_for_date("0.27.4", "20260818171500")
+ assert a < b # lexical == chronological at fixed length
+
+ def test_nightly_outversions_current_stable_loses_to_next_patch(self):
+ """The semver ordering that makes both channel switches work,
+ checked with packaging's canonical comparison when available,
+ else by electron-updater's documented precedence rules."""
+ try:
+ from packaging.version import Version
+ except ImportError:
+ pytest.skip("packaging not installed in this env")
+ nightly = Version("0.27.5-nightly.20260818103000".replace("-nightly.", "a"))
+ assert Version("0.27.4") < nightly < Version("0.27.5")
+
+
+class TestNightlyDateStamps:
+ def test_prune_cutoff_uses_the_tag_date(self):
+ """The prune window keys on the tag's own YYYYMMDD prefix, for
+ both suffix shapes — a 14-digit suffix compared whole against an
+ 8-digit cutoff would be decided by string length, not by day."""
+ legacy = release._NIGHTLY_TAG_RE.fullmatch("v0.27.1-nightly.20260801")
+ stamped = release._NIGHTLY_TAG_RE.fullmatch("v0.27.1-nightly.20260801235959")
+ assert legacy and legacy.group(0).split("-nightly.")[1][:8] == "20260801"
+ assert stamped and stamped.group(0).split("-nightly.")[1][:8] == "20260801"
+
+
+class TestNightlyBuildNumberGuards:
+ """The MSIX nightly build number is minutes-since-the-last-stable.
+ Two nightlies of the same line cut in the same minute would share a
+ build number → identical MSIX version → App Installer refuses the
+ second. cmd_nightly refuses that; it also refuses a nightly whose
+ stable base is >45 days old (the 16-bit MSIX component would
+ overflow)."""
+
+ def test_same_minute_same_line_refused(self, monkeypatch, tmp_path):
+ import subprocess
+ from types import SimpleNamespace
+
+ calls: list[list[str]] = []
+
+ def fake_run(cmd, *a, **kw):
+ calls.append(list(cmd))
+ return subprocess.CompletedProcess(cmd, 0, stdout="url", stderr="")
+
+ def fake_git_result(*args, **kw):
+ # rev-parse --verify must MISS so we reach the guard, not the
+ # "tag already exists" short-circuit.
+ return subprocess.CompletedProcess(args, 1, "", "")
+
+ monkeypatch.setattr(release, "get_last_tag", lambda: "v0.27.1")
+ monkeypatch.setattr(release, "get_last_nightly_tag", lambda: "v0.27.2-nightly.20260818103045")
+ monkeypatch.setattr(release, "git_result", fake_git_result)
+ monkeypatch.setattr(subprocess, "run", fake_run)
+ monkeypatch.delenv("GITHUB_OUTPUT", raising=False)
+
+ release.cmd_nightly(SimpleNamespace(date="20260818103000", publish=True, remote="origin"))
+ assert calls == [], "same-minute same-line re-cut must not create a release"
+
+ def test_same_minute_new_line_allowed(self, monkeypatch, tmp_path):
+ """A fresh stable bumps the line; a same-minute cut on the new line
+ outversions the old line by its patch component, so no collision."""
+ import subprocess
+ from types import SimpleNamespace
+
+ captured: list[list[str]] = []
+
+ def fake_run(cmd, *a, **kw):
+ captured.append(list(cmd))
+ return subprocess.CompletedProcess(cmd, 0, stdout="url", stderr="")
+
+ def fake_git_result(*args, **kw):
+ return subprocess.CompletedProcess(args, 1 if "rev-parse" in args else 0, "", "")
+
+ monkeypatch.setattr(release, "get_last_tag", lambda: "v0.28.0")
+ monkeypatch.setattr(release, "get_last_nightly_tag", lambda: "v0.27.2-nightly.20260818103045")
+ monkeypatch.setattr(release, "get_commits", lambda **kw: [{"hash": "a" * 40, "subject": "feat: x", "author": "e"}])
+ monkeypatch.setattr(release, "generate_changelog", lambda *a, **kw: "notes")
+ monkeypatch.setattr(release, "resolve_push_remote", lambda r: "origin")
+ monkeypatch.setattr(release, "remote_github_repo", lambda r: "o/r")
+ monkeypatch.setattr(release, "git", lambda *a, **kw: "1786017600" if a and a[0] == "log" else "")
+ monkeypatch.setattr(release, "REPO_ROOT", tmp_path)
+ monkeypatch.setattr(release.git_result, "__defaults__", ())
+ monkeypatch.setattr(release, "git_result", fake_git_result)
+ monkeypatch.setattr(subprocess, "run", fake_run)
+ monkeypatch.delenv("GITHUB_OUTPUT", raising=False)
+
+ release.cmd_nightly(SimpleNamespace(date="20260818103000", publish=True, remote="origin"))
+ create = [c for c in captured if c[:3] == ["gh", "release", "create"]]
+ assert len(create) == 1, captured
+
+ def test_stable_base_older_than_45_days_refused(self, monkeypatch, tmp_path):
+ """Minutes-since-stable crosses the 16-bit MSIX component at 45.5
+ days; a nightly cut on an older stable cannot carry a legal build
+ number — refuse loudly (exit 1), never clamp."""
+ import subprocess
+ import sys
+ from types import SimpleNamespace
+
+ # Stable v0.27.1 committed 2026-07-01; nightly cut 2026-08-29.
+ old_epoch = str(int(datetime(2026, 7, 1, tzinfo=timezone.utc).timestamp()))
+ monkeypatch.setattr(release, "get_last_tag", lambda: "v0.27.1")
+ monkeypatch.setattr(release, "get_last_nightly_tag", lambda: None)
+ monkeypatch.setattr(release, "get_commits", lambda **kw: [{"hash": "a" * 40, "subject": "feat: x", "author": "e"}])
+ monkeypatch.setattr(release, "git", lambda *a, **kw: old_epoch if a and a[0] == "log" else "")
+ monkeypatch.setattr(release, "REPO_ROOT", tmp_path)
+ monkeypatch.setattr(release, "git_result", lambda *a, **kw: subprocess.CompletedProcess(a, 1, "", ""))
+ monkeypatch.delenv("GITHUB_OUTPUT", raising=False)
+
+ with pytest.raises(SystemExit) as exc:
+ release.cmd_nightly(SimpleNamespace(date="20260829000000", publish=True, remote="origin"))
+ assert exc.value.code == 1
+
+
+class TestNightlyIsDrafted:
+ """A nightly is created as a DRAFT prerelease.
+
+ A published release with no installers staged is one users can
+ reach and cannot use. The desktop matrix stages the installers to the
+ R2 bucket (releases/tag/<tag>/), the finalize job publishes the
+ feeds, and the nightly workflow publishes the release only after
+ that matrix is green.
+ """
+
+ def _create_argv(self, monkeypatch, tmp_path):
+ """The argv of the `gh release create` cmd_nightly would run."""
+ import subprocess
+ from types import SimpleNamespace
+
+ captured: list[list[str]] = []
+
+ def fake_run(cmd, *a, **kw):
+ captured.append(list(cmd))
+ return subprocess.CompletedProcess(cmd, 0, stdout="url", stderr="")
+
+ def fake_git_result(*args, **kw):
+ # `rev-parse --verify --quiet refs/tags/<tag>` must MISS, or
+ # cmd_nightly short-circuits on "tag already exists".
+ code = 1 if "rev-parse" in args else 0
+ return subprocess.CompletedProcess(args, code, "", "")
+
+ monkeypatch.setattr(release, "get_last_tag", lambda: "v0.27.0")
+ monkeypatch.setattr(release, "get_last_nightly_tag", lambda: None)
+ monkeypatch.setattr(release, "get_commits", lambda **kw: [{"hash": "a" * 40, "subject": "feat: x", "author": "e"}])
+ monkeypatch.setattr(release, "generate_changelog", lambda *a, **kw: "notes")
+ monkeypatch.setattr(release, "resolve_push_remote", lambda r: "origin")
+ monkeypatch.setattr(release, "remote_github_repo", lambda r: "o/r")
+ monkeypatch.setattr(release, "git_result", fake_git_result)
+ monkeypatch.setattr(release, "git", lambda *a, **kw: "")
+ monkeypatch.setattr(release, "REPO_ROOT", tmp_path)
+ monkeypatch.setattr(subprocess, "run", fake_run)
+ monkeypatch.delenv("GITHUB_OUTPUT", raising=False)
+
+ release.cmd_nightly(SimpleNamespace(date="20260818103000", publish=True, remote="origin"))
+ return next(c for c in captured if c[:3] == ["gh", "release", "create"])
+
+ def test_created_as_a_draft_prerelease(self, monkeypatch, tmp_path):
+ argv = self._create_argv(monkeypatch, tmp_path)
+ assert "--draft" in argv, argv
+ assert "--prerelease" in argv, argv
+
+ def test_refuses_to_invent_a_tag(self, monkeypatch, tmp_path):
+ """Without --verify-tag, gh creates a missing tag from the default
+ branch tip, which would release a different commit than the one
+ the nightly math tagged."""
+ assert "--verify-tag" in self._create_argv(monkeypatch, tmp_path)
+
+
+class TestNightlyStartsItsOwnBuild:
+ """release.py dispatches the desktop build for the tag it just cut.
+
+ workflow_dispatch is one of only two events GITHUB_TOKEN may raise, so
+ it is the only trigger that serves the scheduled nightly: that run
+ pushes its tag as github-actions[bot], and a bot-pushed tag starts no
+ workflow run. Dispatching from release.py gives the scheduled nightly,
+ a hand-cut nightly, and a stable release one identical mechanism.
+ """
+
+ def _calls(self, monkeypatch, tmp_path):
+ import subprocess
+ from types import SimpleNamespace
+
+ captured: list[list[str]] = []
+
+ def fake_run(cmd, *a, **kw):
+ captured.append(list(cmd))
+ return subprocess.CompletedProcess(cmd, 0, stdout="url", stderr="")
+
+ monkeypatch.setattr(release, "get_last_tag", lambda: "v0.27.0")
+ monkeypatch.setattr(release, "get_last_nightly_tag", lambda: None)
+ monkeypatch.setattr(release, "get_commits", lambda **kw: [{"hash": "a" * 40, "subject": "feat: x", "author": "e"}])
+ monkeypatch.setattr(release, "generate_changelog", lambda *a, **kw: "notes")
+ monkeypatch.setattr(release, "resolve_push_remote", lambda r: "origin")
+ monkeypatch.setattr(release, "remote_github_repo", lambda r: "o/r")
+ monkeypatch.setattr(
+ release, "git_result",
+ lambda *a, **kw: subprocess.CompletedProcess(a, 1 if "rev-parse" in a else 0, "", ""),
+ )
+ monkeypatch.setattr(release, "git", lambda *a, **kw: "")
+ monkeypatch.setattr(release, "REPO_ROOT", tmp_path)
+ monkeypatch.setattr(release.shutil, "which", lambda x: "/usr/bin/gh")
+ monkeypatch.setattr(subprocess, "run", fake_run)
+ monkeypatch.delenv("GITHUB_OUTPUT", raising=False)
+
+ release.cmd_nightly(SimpleNamespace(date="20260818103000", publish=True, remote="origin"))
+ return captured
+
+ def test_dispatches_the_build_for_the_tag_it_cut(self, monkeypatch, tmp_path):
+ calls = self._calls(monkeypatch, tmp_path)
+ dispatch = next(c for c in calls if c[:3] == ["gh", "workflow", "run"])
+ # get_last_tag is patched to v0.27.0 → the authority's patch+1 math
+ # cuts v0.27.1-nightly.20260818103000.
+ tag = "v0.27.1-nightly.20260818103000"
+
+ assert "desktop-bundled-release.yml" in dispatch
+ # The tag travels as the INPUT the build reads. The workflow FILE
+ # itself is dispatched from the default branch — a tag-dispatched
+ # run scopes actions/cache under refs/heads/refs/tags/<tag>, a
+ # mangled per-tag scope no later nightly can restore.
+ assert f"tag={tag}" in dispatch
+ assert "--ref" in dispatch and dispatch[dispatch.index("--ref") + 1] != tag
+ # Without this the build produces artifacts and attaches nothing.
+ assert "upload_release=true" in dispatch
+
+ def test_the_draft_exists_before_the_build_starts(self, monkeypatch, tmp_path):
+ """Ordering is the whole point of dispatching rather than relying
+ on the tag push: the build's upload step fails on a missing
+ release, so the draft has to be there first."""
+ calls = self._calls(monkeypatch, tmp_path)
+ create = next(i for i, c in enumerate(calls) if c[:3] == ["gh", "release", "create"])
+ dispatch = next(i for i, c in enumerate(calls) if c[:3] == ["gh", "workflow", "run"])
+ assert create < dispatch
+
+ def test_a_failed_dispatch_does_not_sink_the_release(self, monkeypatch, tmp_path):
+ """The tag and draft are already pushed by then. Report the manual
+ command and leave them; raising would strand a half-made release."""
+ assert release.dispatch_desktop_build.__doc__
+ monkeypatch.setattr(release.shutil, "which", lambda x: None)
+ assert release.dispatch_desktop_build("v0.28.0-nightly.20260818103000", "o/r") is False
diff --git a/tests/scripts/test_release_tags.py b/tests/scripts/test_release_tags.py
new file mode 100644
index 00000000000..c5da4e29138
--- /dev/null
+++ b/tests/scripts/test_release_tags.py
@@ -0,0 +1,96 @@
+"""Release-tag policy: new releases use semver, old CalVer tags remain readable."""
+
+import importlib.util
+from pathlib import Path
+
+import pytest
+
+
+_RELEASE_PATH = Path(__file__).resolve().parents[2] / "scripts" / "release.py"
+_SPEC = importlib.util.spec_from_file_location("hermes_release", _RELEASE_PATH)
+assert _SPEC and _SPEC.loader
+release = importlib.util.module_from_spec(_SPEC)
+_SPEC.loader.exec_module(release)
+
+
+def test_release_tag_uses_the_semver_version():
+ assert release.release_tag_for_version("0.20.0") == "v0.20.0"
+
+
+def test_last_tag_prefers_semver_over_newer_looking_legacy_calver(monkeypatch):
+ monkeypatch.setattr(
+ release,
+ "git",
+ lambda *_args: "v2026.7.20\nv0.20.0\nv0.19.0",
+ )
+
+ assert release.get_last_tag() == "v0.20.0"
+
+
+def test_last_tag_falls_back_to_legacy_calver_history(monkeypatch):
+ monkeypatch.setattr(release, "git", lambda *_args: "v2026.7.20\nv2026.7.7")
+
+ assert release.get_last_tag() == "v2026.7.20"
+
+
+class _FakeResult:
+ def __init__(self, stdout: str = "", returncode: int = 0):
+ self.stdout = stdout
+ self.returncode = returncode
+ self.stderr = ""
+
+
+def _remotes(monkeypatch, names: list[str]):
+ monkeypatch.setattr(
+ release, "git_result", lambda *_args, **_kw: _FakeResult("\n".join(names))
+ )
+
+
+def test_single_remote_is_used_without_a_flag(monkeypatch):
+ _remotes(monkeypatch, ["origin"])
+
+ assert release.resolve_push_remote(None) == "origin"
+
+
+def test_multiple_remotes_require_an_explicit_flag(monkeypatch):
+ _remotes(monkeypatch, ["fork", "origin"])
+
+ with pytest.raises(SystemExit, match="pass --remote"):
+ release.resolve_push_remote(None)
+
+
+def test_explicit_remote_is_honored_among_many(monkeypatch):
+ _remotes(monkeypatch, ["fork", "origin"])
+
+ assert release.resolve_push_remote("fork") == "fork"
+
+
+def test_unknown_remote_is_rejected(monkeypatch):
+ _remotes(monkeypatch, ["fork", "origin"])
+
+ with pytest.raises(SystemExit, match="not configured"):
+ release.resolve_push_remote("upstream")
+
+
+def test_no_remotes_is_rejected(monkeypatch):
+ _remotes(monkeypatch, [])
+
+ with pytest.raises(SystemExit, match="no git remotes"):
+ release.resolve_push_remote(None)
+
+
+def test_github_repo_parsed_from_ssh_and_https_urls(monkeypatch):
+ urls = {
+ "fork": "[email protected]:ethernet8023/hermes-agent.git",
+ "origin": "https://github.com/NousResearch/hermes-agent",
+ "gitlab": "[email protected]:someone/elsewhere.git",
+ }
+ monkeypatch.setattr(
+ release,
+ "git_result",
+ lambda *args, **_kw: _FakeResult(urls[args[-1]]),
+ )
+
+ assert release.remote_github_repo("fork") == "ethernet8023/hermes-agent"
+ assert release.remote_github_repo("origin") == "NousResearch/hermes-agent"
+ assert release.remote_github_repo("gitlab") is None
diff --git a/tests/scripts/test_render_builds_table.py b/tests/scripts/test_render_builds_table.py
new file mode 100644
index 00000000000..07b31266e6c
--- /dev/null
+++ b/tests/scripts/test_render_builds_table.py
@@ -0,0 +1,143 @@
+"""render-builds-table.py: tables from REAL bucket object names, spliced idempotently.
+
+The contract: table rows exist only for objects that are actually in the
+R2 bucket for the tag's exact version (missing artifact = missing row,
+never a dead link), links point at the R2 public URL, msixbundle / zip /
+feed manifests stay out, and re-rendering replaces the previous block
+instead of stacking a second one.
+
+Adapted from the restack suite for this branch's artifact shapes: the
+Windows per-arch artifact here is .msix (the msixbundle folds both arches
+and stays out of the tables), not the NSIS .exe.
+"""
+
+import importlib.util
+from pathlib import Path
+
+_SCRIPT = Path(__file__).resolve().parents[2] / "scripts" / "render-builds-table.py"
+_SPEC = importlib.util.spec_from_file_location("render_builds_table", _SCRIPT)
+assert _SPEC and _SPEC.loader
+rbt = importlib.util.module_from_spec(_SPEC)
+_SPEC.loader.exec_module(rbt)
+
+
+ASSETS = [
+ "releases/tag/v0.28.0/HermesBundled-0.28.0-mac-arm64.dmg",
+ "releases/tag/v0.28.0/HermesBundled-0.28.0-mac-arm64.zip", # updater delta target — no row
+ "releases/tag/v0.28.0/HermesBundled-0.28.0-win-x64.msix",
+ "releases/tag/v0.28.0/HermesBundled-0.28.0-win-arm64.msix",
+ "releases/tag/v0.28.0/HermesBundled-0.28.0-win.msixbundle", # store/sideload channel — no row
+ "releases/tag/v0.28.0/HermesBundled-0.28.0-linux-x64.AppImage",
+ "releases/tag/v0.28.0/HermesLight-0.28.0-win-x64.msix",
+ "latest.yml", # feed manifest — no row
+ "light.yml",
+ "releases/tag/v0.28.0/HermesBundled-0.28.0-win-x64.msix.blockmap", # no row
+]
+
+BASE_URL = "https://releases.example.com"
+
+
+class TestParseAssets:
+ def test_only_table_shaped_assets_parse(self):
+ parsed = rbt.parse_assets(ASSETS)
+ assert ("mac", "arm64") in parsed["HermesBundled"]
+ assert ("win", "x64") in parsed["HermesBundled"]
+ assert ("win", "arm64") in parsed["HermesBundled"]
+ assert ("linux", "x64") in parsed["HermesBundled"]
+ assert len(parsed["HermesBundled"]) == 4 # zip/msixbundle/blockmap/yml excluded
+ assert parsed["HermesLight"] == {("win", "x64"): ("releases/tag/v0.28.0/HermesLight-0.28.0-win-x64.msix", "msix")}
+
+ def test_nightly_versions_parse(self):
+ parsed = rbt.parse_assets(["releases/tag/v0.28.0-nightly.20260818/HermesBundled-0.28.0-nightly.20260818-win-x64.msix"])
+ assert ("win", "x64") in parsed["HermesBundled"]
+
+ def test_flat_names_still_parse(self):
+ # Names without the releases/tag/ prefix (e.g. from a plain list) are
+ # handled too — the shape match runs on the basename either way.
+ parsed = rbt.parse_assets(["HermesBundled-0.28.0-win-x64.msix"])
+ assert parsed["HermesBundled"][("win", "x64")] == ("HermesBundled-0.28.0-win-x64.msix", "msix")
+
+
+class TestFilterNamesForVersion:
+ def test_stable_tag_does_not_match_nightly_objects(self):
+ # '0.28.0' is a prefix of '0.28.0-nightly...' — the filter must be
+ # exact, or a stable table would list nightly binaries.
+ names = [
+ "releases/tag/v0.28.0/HermesBundled-0.28.0-mac-arm64.dmg",
+ "releases/tag/v0.28.0-nightly.20260818/HermesBundled-0.28.0-nightly.20260818-win-x64.msix",
+ "releases/tag/v0.29.0/HermesBundled-0.29.0-win-x64.msix",
+ "latest.yml",
+ ]
+ assert rbt.filter_names_for_version(names, "0.28.0") == [
+ "releases/tag/v0.28.0/HermesBundled-0.28.0-mac-arm64.dmg",
+ ]
+
+ def test_nightly_tag_matches_its_objects(self):
+ names = [
+ "releases/tag/v0.28.0-nightly.20260818/HermesBundled-0.28.0-nightly.20260818-win-x64.msix",
+ "releases/tag/v0.28.0-nightly.20260818/HermesBundled-0.28.0-nightly.20260818-win-x64.msix.blockmap",
+ "releases/tag/v0.28.0-nightly.20260817/HermesBundled-0.28.0-nightly.20260817-win-arm64.msix",
+ "releases/tag/v0.28.0/HermesBundled-0.28.0-mac-arm64.dmg",
+ ]
+ assert rbt.filter_names_for_version(names, "0.28.0-nightly.20260818") == [
+ "releases/tag/v0.28.0-nightly.20260818/HermesBundled-0.28.0-nightly.20260818-win-x64.msix",
+ ]
+
+
+class TestRenderAndSplice:
+ def test_rows_only_for_present_assets(self):
+ block = rbt.render_tables(rbt.parse_assets(ASSETS), BASE_URL)
+ assert f"{BASE_URL}/releases/tag/v0.28.0/HermesBundled-0.28.0-mac-arm64.dmg" in block
+ assert "HermesBundled-0.28.0-win.msixbundle" not in block
+ assert ".zip" not in block
+ assert ".blockmap" not in block
+ # A leg that never uploaded leaves no row at all.
+ assert "linux-arm64" not in block
+
+ def test_links_point_at_the_r2_base_url(self):
+ block = rbt.render_tables(rbt.parse_assets(ASSETS), BASE_URL)
+ assert "github.com" not in block
+ assert f"{BASE_URL}/releases/tag/v0.28.0/HermesLight-0.28.0-win-x64.msix" in block
+
+ def test_base_url_trailing_slash_is_stripped(self):
+ block = rbt.render_tables(rbt.parse_assets(ASSETS), f"{BASE_URL}/")
+ assert f"{BASE_URL}/releases/tag/v0.28.0/HermesBundled-0.28.0-mac-arm64.dmg" in block
+ assert f"{BASE_URL}//releases" not in block
+
+ def test_splice_replaces_marker_and_is_idempotent(self):
+ body = f"# Notes\n\n{rbt.MARKER}\n\n## Changes"
+ block = rbt.render_tables(rbt.parse_assets(ASSETS), BASE_URL)
+ once = rbt.splice(body, block)
+ assert "## Downloads" in once
+ assert once.count(rbt.MARKER) == 1
+ # Second render (e.g. a re-run with more assets) replaces, not stacks.
+ twice = rbt.splice(once, block)
+ assert twice.count("## Downloads") == 1
+ assert twice.count(rbt.END_MARKER) == 1
+
+ def test_no_marker_leaves_body_alone(self):
+ block = rbt.render_tables(rbt.parse_assets(ASSETS), BASE_URL)
+ assert rbt.splice("no marker here", block) == "no marker here"
+
+
+class TestPendingPlaceholder:
+ def test_final_render_replaces_the_pending_link(self):
+ # The lifecycle: marker → pending link (builds-pending job) →
+ # tables (builds-table job). The link must not survive step 3.
+ body = f"# Notes\n\n{rbt.MARKER}\n\n## Changes"
+ pending = rbt.render_pending("https://github.com/o/r/actions/runs/123")
+ with_pending = rbt.splice(body, pending)
+ assert "actions/runs/123" in with_pending
+ assert with_pending.count(rbt.MARKER) == 1 # wrapper survives for step 3
+ tables = rbt.render_tables(rbt.parse_assets(ASSETS), BASE_URL)
+ final = rbt.splice(with_pending, tables)
+ assert "actions/runs/123" not in final
+ assert "## Downloads" in final
+ assert final.count(rbt.END_MARKER) == 1
+
+ def test_pending_rerender_replaces_not_stacks(self):
+ once = rbt.splice(rbt.MARKER, rbt.render_pending("https://x/runs/1"))
+ twice = rbt.splice(once, rbt.render_pending("https://x/runs/2"))
+ assert "https://x/runs/1" not in twice
+ assert twice.count("https://x/runs/2") == 1
+ assert twice.count(rbt.END_MARKER) == 1
diff --git a/tests/scripts/test_write_install_stamp.py b/tests/scripts/test_write_install_stamp.py
new file mode 100644
index 00000000000..87de3500583
--- /dev/null
+++ b/tests/scripts/test_write_install_stamp.py
@@ -0,0 +1,103 @@
+import pytest
+
+from scripts.write_install_stamp import build_stamp
+
+
+def test_build_stamp_keeps_provenance_separate_from_distribution():
+ stamp = build_stamp(commit="a" * 40, source="ci", distribution="docker", update_mechanism="external")
+
+ assert stamp["source"] == "ci"
+ assert stamp["distribution"] == "docker"
+
+
+def test_default_build_is_a_bootstrap_artifact_regardless_of_tag(monkeypatch):
+ monkeypatch.delenv("HERMES_DESKTOP_VARIANT", raising=False)
+ monkeypatch.setenv("HERMES_PAYLOAD_TAG", "v9.9.9")
+
+ stamp = build_stamp(commit="a" * 40, update_mechanism="self")
+
+ assert stamp["payload"] == "bootstrap"
+ assert stamp["tag"] is None
+
+
+def test_explicit_bootstrap_variant_matches_the_default(monkeypatch):
+ monkeypatch.setenv("HERMES_DESKTOP_VARIANT", "bootstrap")
+ monkeypatch.setenv("HERMES_PAYLOAD_TAG", "v9.9.9")
+
+ stamp = build_stamp(commit="a" * 40, update_mechanism="self")
+
+ assert stamp["payload"] == "bootstrap"
+ assert stamp["tag"] is None
+
+
+def test_bundled_variant_records_payload_and_tag(monkeypatch):
+ monkeypatch.setenv("HERMES_DESKTOP_VARIANT", "bundled")
+ monkeypatch.setenv("HERMES_PAYLOAD_TAG", "v0.18.0")
+
+ stamp = build_stamp(commit="b" * 40, update_mechanism="self")
+
+ assert stamp["payload"] == "bundled"
+ assert stamp["tag"] == "v0.18.0"
+
+
+def test_light_variant_records_payload_and_tag(monkeypatch):
+ monkeypatch.setenv("HERMES_DESKTOP_VARIANT", "light")
+ monkeypatch.setenv("HERMES_PAYLOAD_TAG", "v0.18.0")
+
+ stamp = build_stamp(commit="b" * 40, update_mechanism="self")
+
+ assert stamp["payload"] == "light"
+ assert stamp["tag"] == "v0.18.0"
+
+
[email protected]("variant", ["bundled", "light"])
+def test_self_updating_variants_without_tag_stop_the_build(monkeypatch, variant):
+ monkeypatch.setenv("HERMES_DESKTOP_VARIANT", variant)
+ monkeypatch.delenv("HERMES_PAYLOAD_TAG", raising=False)
+
+ with pytest.raises(SystemExit, match="HERMES_PAYLOAD_TAG"):
+ build_stamp(commit="b" * 40, update_mechanism="self")
+
+
+def test_unknown_variant_stops_the_build(monkeypatch):
+ monkeypatch.setenv("HERMES_DESKTOP_VARIANT", "chonky")
+ monkeypatch.setenv("HERMES_PAYLOAD_TAG", "v0.18.0")
+
+ with pytest.raises(SystemExit, match="unknown HERMES_DESKTOP_VARIANT"):
+ build_stamp(commit="b" * 40, update_mechanism="self")
+
+
+def test_desktop_app_is_a_valid_distribution():
+ stamp = build_stamp(commit="c" * 40, source="ci", distribution="desktop-app", update_mechanism="electron-updater")
+
+ assert stamp["distribution"] == "desktop-app"
+
+
+def test_distribution_defaults_to_null():
+ stamp = build_stamp(commit="c" * 40, update_mechanism="self")
+
+ assert stamp["distribution"] is None
+
+
+def test_cli_accepts_desktop_app_distribution(tmp_path):
+ import json
+ import subprocess
+ import sys
+ from pathlib import Path
+
+ out = tmp_path / "stamp.json"
+ repo_root = Path(__file__).resolve().parents[2]
+ result = subprocess.run(
+ [
+ sys.executable,
+ str(repo_root / "scripts" / "write_install_stamp.py"),
+ "--output", str(out),
+ "--commit", "d" * 40,
+ "--distribution", "desktop-app",
+ "--update-mechanism", "electron-updater",
+ ],
+ capture_output=True, text=True,
+ )
+
+ assert result.returncode == 0, result.stderr
+ assert json.loads(out.read_text(encoding="utf-8-sig"))["distribution"] == "desktop-app"
diff --git a/tests/skills/test_google_workspace_setup_deps.py b/tests/skills/test_google_workspace_setup_deps.py
index bf776f28f7c..306e33a0778 100644
--- a/tests/skills/test_google_workspace_setup_deps.py
+++ b/tests/skills/test_google_workspace_setup_deps.py
@@ -3,12 +3,11 @@
GHSA-j5g9-f88f-gfj3 (HIGH) — Decompression Bomb DoS via unbounded gzip/deflate
response handling. Fixed in httplib2 0.32.0.
-There are three install paths for google-workspace dependencies:
+There are two install paths for google-workspace dependencies:
1. pyproject.toml [project.optional-dependencies].google
- 2. tools/lazy_deps.py LAZY_DEPS['skill.google_workspace']
- 3. skills/productivity/google-workspace/scripts/setup.py REQUIRED_PACKAGES
+ 2. skills/productivity/google-workspace/scripts/setup.py REQUIRED_PACKAGES
-This test ensures path 3 stays pinned and consistent with the other two.
+This test ensures path 2 stays pinned and consistent with path 1.
"""
from __future__ import annotations
@@ -26,7 +25,6 @@ PYPROJECT_TOML = REPO_ROOT / "pyproject.toml"
# ---------------------------------------------------------------------------
_GOOGLE_EXTRA_KEY = "google"
-_LAZY_DEPS_KEY = "skill.google_workspace"
def _parse_setup_py_required_packages() -> list[str]:
@@ -52,13 +50,6 @@ def _parse_pyproject_google_extra() -> list[str]:
return list(optional_deps[_GOOGLE_EXTRA_KEY])
-def _parse_lazy_deps_google_workspace() -> list[str]:
- """Return the real LAZY_DEPS entry for skill.google_workspace."""
- from tools.lazy_deps import LAZY_DEPS
-
- return list(LAZY_DEPS[_LAZY_DEPS_KEY])
-
-
def _extract_pins(packages: list[str]) -> dict[str, str]:
"""Extract pinned versions: {package_name: version} for entries with == pin."""
pins: dict[str, str] = {}
@@ -123,45 +114,14 @@ class TestGoogleWorkspaceSetupDepsPins:
f" pyproject.toml google: {pyproject_pins}"
)
- def test_setup_py_pins_match_lazy_deps(self):
- """httplib2 pin in setup.py must match tools/lazy_deps.py skill.google_workspace."""
- required_packages = _parse_setup_py_required_packages()
- lazy_packages = _parse_lazy_deps_google_workspace()
-
- required_pins = _extract_pins(required_packages)
- lazy_pins = _extract_pins(lazy_packages)
-
- for pkg in ("httplib2", "google-api-python-client", "google-auth-oauthlib", "google-auth-httplib2"):
- setup_ver = required_pins.get(pkg)
- lazy_ver = lazy_pins.get(pkg)
- if setup_ver is None and lazy_ver is None:
- continue
- assert lazy_ver is not None, (
- f"{pkg} is pinned in setup.py ({setup_ver}) but NOT in lazy_deps.py.\n"
- f" setup.py: {required_pins}\n"
- f" lazy_deps.py: {lazy_pins}"
- )
- assert setup_ver is not None, (
- f"{pkg} is pinned in lazy_deps.py ({lazy_ver}) but NOT in setup.py.\n"
- f" lazy_deps.py: {lazy_pins}\n"
- f" setup.py: {required_pins}"
- )
- assert setup_ver == lazy_ver, (
- f"{pkg} pin mismatch: setup.py has {setup_ver}, lazy_deps.py has {lazy_ver}.\n"
- f" setup.py: {required_pins}\n"
- f" lazy_deps.py: {lazy_pins}"
- )
-
def test_all_google_packages_are_pinned_in_all_paths(self):
- """Every google workspace package that is version-pinned in any path must appear in all three."""
+ """Every google workspace package that is version-pinned in any path must appear in both."""
pyproject_packages = _parse_pyproject_google_extra()
- lazy_packages = _parse_lazy_deps_google_workspace()
setup_packages = _parse_setup_py_required_packages()
all_pins: dict[str, set[str]] = {}
for label, pkgs in [
("pyproject.toml", pyproject_packages),
- ("lazy_deps.py", lazy_packages),
("setup.py", setup_packages),
]:
for pkg in pkgs:
@@ -175,7 +135,7 @@ class TestGoogleWorkspaceSetupDepsPins:
f"{pkg} has inconsistent pins across install paths:\n"
+ "\n".join(f" {e}" for e in sorted(entries))
)
- assert len(entries) == 3, (
- f"{pkg} is not pinned in all three install paths. Found {len(entries)}/3:\n"
+ assert len(entries) == 2, (
+ f"{pkg} is not pinned in all install paths. Found {len(entries)}/2:\n"
+ "\n".join(f" {e}" for e in sorted(entries))
)
diff --git a/tests/test_engines_satisfiable.py b/tests/test_engines_satisfiable.py
index 8ce67810db8..72ef27267d9 100644
--- a/tests/test_engines_satisfiable.py
+++ b/tests/test_engines_satisfiable.py
@@ -19,6 +19,7 @@ declare and the toolchain that has to satisfy it.
from __future__ import annotations
import json
+import re
from pathlib import Path
import pytest
@@ -108,21 +109,23 @@ class TestEnginesAreSatisfiable:
def test_node_floor_is_met_by_the_managed_runtime(self):
"""The Node major the installers provision must clear engines.node."""
node_range = _root_manifest()["engines"]["node"]
- install_sh = (REPO_ROOT / "scripts" / "install.sh").read_text()
- for line in install_sh.splitlines():
- if line.startswith("NODE_VERSION="):
- managed_major = int(line.split("=", 1)[1].strip().strip('"').strip("'"))
- break
- else: # pragma: no cover - install.sh always defines it
- pytest.fail("install.sh does not define NODE_VERSION")
-
- # install.sh fetches latest-v{major}.x, not {major}.0.0. Use a high
- # representative release from that major so ranges that enumerate LTS
- # lines (rather than one continuous floor) are checked correctly.
- managed_release = f"{managed_major}.999.999"
- assert _satisfies_range(managed_release, node_range), (
- f"engines.node is {node_range!r} but install.sh provisions Node "
- f"{managed_major}.x. The runtime we ship must satisfy the floor we "
+ # pm-era install: node is a pm package pinned in pm/lock.json (the
+ # installers stage it via `pm`, not a NODE_VERSION shell var).
+ lock = json.loads((REPO_ROOT / "pm" / "lock.json").read_text(encoding="utf-8"))
+ node_pin = lock["packages"]["node"]["version"]
+ managed_major = int(node_pin.split(".")[0])
+
+ # pm fetches the exact pinned version, so compare on the major: the
+ # pinned node line must clear the floor. A floor in a HIGHER major
+ # than we provision can never be met.
+ floor_majors = [
+ int(m.group(1))
+ for m in re.finditer(r">=\s*v?(\d+)", node_range)
+ ]
+ assert floor_majors, f"cannot read a floor out of {node_range!r}"
+ assert managed_major >= min(floor_majors), (
+ f"engines.node is {node_range!r} but pm/lock.json pins Node "
+ f"{node_pin}. The runtime we ship must satisfy the floor we "
"declare, or the install we just performed cannot install deps."
)
@@ -133,23 +136,28 @@ class TestEnginesAreSatisfiable:
`npm ci` with EBADENGINE (#80769).
"""
npm_range = _root_manifest()["engines"]["npm"]
- install_sh = (REPO_ROOT / "scripts" / "install.sh").read_text()
- for line in install_sh.splitlines():
- if line.startswith("NODE_VERSION="):
- managed_major = int(line.split("=", 1)[1].strip().strip('"').strip("'"))
- break
- else: # pragma: no cover
- pytest.fail("install.sh does not define NODE_VERSION")
- stock_npm = _STOCK_NPM_BY_NODE_MAJOR.get(managed_major)
- assert stock_npm is not None, (
- f"install.sh NODE_VERSION={managed_major} is not in the known "
- f"stock map {_STOCK_NPM_BY_NODE_MAJOR}"
- )
- assert _satisfies_range(stock_npm, npm_range), (
- f"install.sh provisions Node {managed_major}.x (stock npm "
- f"{stock_npm}), but engines.npm is {npm_range!r}. A fresh "
- "Hermes-managed install cannot run npm ci."
- )
+ # pm-era install: node is pinned in pm/lock.json; the npm that
+ # rides with it is the pm-managed npm (also pinned there).
+ lock = json.loads((REPO_ROOT / "pm" / "lock.json").read_text(encoding="utf-8"))
+ managed_major = int(lock["packages"]["node"]["version"].split(".")[0])
+ managed_npm = lock["packages"].get("npm", {}).get("version", "")
+ if managed_npm:
+ # The pinned npm's own version — clear the floor directly.
+ assert _satisfies_range(managed_npm, npm_range), (
+ f"pm/lock.json pins npm {managed_npm}, but engines.npm is "
+ f"{npm_range!r}. A fresh Hermes-managed install cannot run npm ci."
+ )
+ else:
+ stock_npm = _STOCK_NPM_BY_NODE_MAJOR.get(managed_major)
+ assert stock_npm is not None, (
+ f"pm/lock.json pins Node {managed_major} but it is not in the "
+ f"known stock map {_STOCK_NPM_BY_NODE_MAJOR}"
+ )
+ assert _satisfies_range(stock_npm, npm_range), (
+ f"pm/lock.json pins Node {managed_major}.x (stock npm "
+ f"{stock_npm}), but engines.npm is {npm_range!r}. A fresh "
+ "Hermes-managed install cannot run npm ci."
+ )
def test_desktop_node_floor_is_not_stricter_than_its_toolchain(self):
"""apps/desktop must not demand more Node than its own build tools do.
@@ -203,95 +211,3 @@ class TestManifestMirrors:
manifest = _root_manifest()["engines"]
lock = json.loads((REPO_ROOT / "package-lock.json").read_text())
assert lock["packages"][""]["engines"] == manifest
-
-
-def _normalize_range(spec: str) -> str:
- """Normalize the wilder styles real deps publish so our tiny evaluator
- can read them: collapse space after operators (``">= 10"``), drop ``v``
- prefixes (``">=v12.22.7"``), and rewrite ``x``/``*`` wildcards to floors.
- """
- import re
-
- spec = re.sub(r"(>=|<=|>|<|\^|~|=)\s+", r"\1", spec)
- spec = re.sub(r"(>=|<=|>|<|\^|~|=)v", r"\1", spec)
- # "6.x" / "10.*" -> "^6.0.0"-ish floor within the major; ">= 10.*" -> ">=10.0.0"
- spec = re.sub(r"(\d+)\.[x*](?:\.[x*])?", r"\1.0.0", spec)
- return spec
-
-
-class TestDeclaredFloorsClearTheLockedTree:
- """Every Node version our own gates accept must survive `npm ci`.
-
- The class of outage this pins: the installers' version gates
- (node_satisfies_build in install.sh, Test-NodeVersionOk in install.ps1)
- and `engines.node` are hand-maintained, while the *real* floor is
- whatever the strictest locked dependency demands. When they drift, a
- user's system Node clears every gate we own and then dies at
- `npm install` with EBADENGINE under engine-strict=true.
-
- Aug 2026 instance: @babel/* 8.x requires `^22.18.0 || >=24.11.0`; our
- engines arm said `^24.0.0`, so Node 24.4 passed the installer and the
- manifest and failed on 28 babel packages.
- """
-
- def _arm_floors(self, node_range: str) -> list[str]:
- floors = []
- for arm in node_range.split("||"):
- arm = arm.strip()
- for op in ("^", ">=", "="):
- if arm.startswith(op):
- floors.append(arm[len(op):].strip())
- break
- else:
- floors.append(arm)
- return floors
-
- def _locked_node_ranges(self) -> dict[str, str]:
- lock = json.loads((REPO_ROOT / "package-lock.json").read_text())
- ranges: dict[str, str] = {}
- for path, meta in lock["packages"].items():
- engines = meta.get("engines")
- if not isinstance(engines, dict):
- continue
- node_range = engines.get("node")
- if isinstance(node_range, str) and node_range.strip() not in ("", "*"):
- ranges.setdefault(node_range, path)
- return ranges
-
- def test_every_engines_arm_floor_clears_every_locked_dependency(self):
- node_range = _root_manifest()["engines"]["node"]
- violations = []
- for floor in self._arm_floors(node_range):
- for dep_range, example in self._locked_node_ranges().items():
- if not _satisfies_range(floor, _normalize_range(dep_range)):
- violations.append((floor, dep_range, example))
- assert not violations, (
- "engines.node arms admit Node versions the locked dependency "
- "tree rejects — those users pass every install gate and then "
- "die at `npm install` with EBADENGINE (engine-strict=true). "
- "Raise the arm floor (and the installer gates: "
- "node_satisfies_build in scripts/install.sh, Test-NodeVersionOk "
- f"in scripts/install.ps1) or relax the dep. Violations: {violations}"
- )
-
- def test_installer_gates_match_the_manifest_arms(self):
- """install.sh's node_satisfies_build must encode the same floors as
- engines.node — a laxer gate accepts a Node that npm then rejects."""
- node_range = _root_manifest()["engines"]["node"]
- install_sh = (REPO_ROOT / "scripts" / "install.sh").read_text()
- install_ps1 = (REPO_ROOT / "scripts" / "install.ps1").read_text()
- for arm in node_range.split("||"):
- arm = arm.strip()
- major, minor = _parse_major_minor_patch(arm.lstrip("^>="))[:2]
- if arm.startswith("^") and minor > 0:
- sh_gate = f'[ "$major" -eq {major} ] && [ "$minor" -ge {minor} ]'
- ps1_gate = f"if ($v.Major -eq {major}) {{ return ($v.Minor -ge {minor}) }}"
- assert sh_gate in install_sh, (
- f"engines.node arm {arm!r} has no matching gate in "
- f"install.sh node_satisfies_build (expected: {sh_gate})"
- )
- assert ps1_gate in install_ps1, (
- f"engines.node arm {arm!r} has no matching gate in "
- f"install.ps1 Test-NodeVersionOk (expected: {ps1_gate})"
- )
-
diff --git a/tests/test_old_updater_compat_surface.py b/tests/test_old_updater_compat_surface.py
new file mode 100644
index 00000000000..16d279dde12
--- /dev/null
+++ b/tests/test_old_updater_compat_surface.py
@@ -0,0 +1,137 @@
+"""An old `hermes update` must still find every name it loads mid-swap.
+
+`hermes update` replaces the checkout underneath a RUNNING process. The
+old process then lazy-imports from the new tree: whatever it asks for
+must still exist, or the user's update dies half-applied. The names it
+can ask for were collected by auditing the update flow in this tree
+(scripts/audit-old-updater-imports.py) and frozen into
+tests/compat/old_updater_surface.json. The pm rewrite retired the
+lineage the original shipped-history walk froze (installation/*,
+hermes_cli.managed_uv), so the frozen contract here is the CURRENT
+updater's mid-swap loads; releases cut from this branch re-enter the
+surface by regenerating against the tree that shipped them.
+
+`managed_uv._reload_hermes_constants` is the scar proving the failure
+mode is real: a live updater hit ``cannot import name 'venv_python_path'
+from 'hermes_constants'`` while the NEW file on disk plainly held it.
+
+If this test fails you have two honest options:
+* restore the name (a stub with the old signature is fine), or
+* prove no shipped release still loads it, then REGENERATE the frozen
+ file:
+ python scripts/audit-old-updater-imports.py --freeze \
+ tests/compat/old_updater_surface.json
+Hand-trimming the JSON is how someone's install bricks mid-update.
+
+The test resolves names statically (AST over the files) rather than
+importing: importing would execute module side effects and — worse —
+resolve against the test venv, not the tree under test.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+SURFACE_FILE = REPO_ROOT / "tests" / "compat" / "old_updater_surface.json"
+
+# One authority for resolution: the audit script itself. The test must
+# agree with --check byte-for-byte or the two drift apart.
+import importlib.util as _ilu
+import sys as _sys
+
+_spec = _ilu.spec_from_file_location(
+ "audit_old_updater_imports",
+ REPO_ROOT / "scripts" / "audit-old-updater-imports.py",
+)
+assert _spec is not None and _spec.loader is not None
+_audit = _ilu.module_from_spec(_spec)
+# dataclass decorators resolve their defining module through sys.modules
+# at class-creation time; exec without registration dies on it.
+_sys.modules["audit_old_updater_imports"] = _audit
+_spec.loader.exec_module(_audit)
+
+
+def _load_surface() -> dict:
+ return json.loads(SURFACE_FILE.read_text())
+
+
+def _pairs(entries: list[str]) -> list[tuple[str, str | None]]:
+ out: list[tuple[str, str | None]] = []
+ for entry in entries:
+ module, _, symbol = entry.partition("::")
+ out.append((module, symbol or None))
+ return out
+
+
+class TestTheFrozenSurfaceStillResolves:
+ """Every bare name a shipped updater loads must exist in THIS tree."""
+
+ @pytest.mark.parametrize(
+ "module,symbol",
+ _pairs(_load_surface()["bare"]),
+ ids=lambda v: v or "<module>",
+ )
+ def test_bare_name_exists(self, module: str, symbol: str | None):
+ ok, why = _audit.resolve_in_tree(module, symbol, REPO_ROOT)
+ assert ok, (
+ f"{why} — but a shipped `hermes update` imports it AFTER the "
+ f"checkout swap. Restore the name (a compat stub is fine) or "
+ f"regenerate the frozen surface on a full clone; see this "
+ f"file's docstring."
+ )
+
+
+class TestTheFrozenFileIsSane:
+ """Catch a corrupted or hand-trimmed freeze before it lies to us."""
+
+ def test_has_the_load_bearing_names(self):
+ # Spot-check names that are KNOWN load-bearing today. If any of
+ # these fall out of the frozen file, the freeze itself went wrong
+ # (shallow clone, wrong branch) — the resolver test above would
+ # pass vacuously.
+ bare = set(_load_surface()["bare"])
+ for anchor in (
+ "hermes_constants::with_hermes_node_path",
+ "pm.ensure::sync_venv",
+ "hermes_cli.gitlock::clear_stale_git_locks",
+ ):
+ assert anchor in bare, (
+ f"{anchor} missing from the frozen surface — the freeze "
+ f"went wrong (wrong branch, or the audit lost its "
+ f"entrypoints); regenerate and eyeball the diff."
+ )
+
+ def test_audit_saw_the_whole_update_flow(self):
+ stats = _load_surface()["stats"]
+ assert stats.get("mode") == "tree", (
+ "frozen surface is not a tree-mode freeze — regenerate with "
+ "scripts/audit-old-updater-imports.py --freeze (no --history)."
+ )
+ analyzed = set(stats.get("files_analyzed", []))
+ for must_see in ("hermes_cli/update_cmd.py", "pm/ensure.py"):
+ assert must_see in analyzed, (
+ f"{must_see} was not analyzed for the freeze — the audit "
+ f"lost part of the update flow; a vacuously small surface "
+ f"cannot guard anything."
+ )
+
+ def test_frozen_matches_a_fresh_audit(self):
+ # A new lazy import in the update flow must not slip in unrecorded:
+ # the frozen file and a fresh audit of this tree must agree.
+ fresh = _audit.audit_tree()
+ fresh_bare = sorted(
+ f"{m}::{s}"
+ for (m, s) in fresh.required
+ if (m, s) not in fresh.guarded_only
+ )
+ frozen_bare = _load_surface()["bare"]
+ assert fresh_bare == frozen_bare, (
+ "the update flow's bare mid-swap loads changed but the frozen "
+ "surface was not regenerated — run scripts/"
+ "audit-old-updater-imports.py --freeze "
+ "tests/compat/old_updater_surface.json and review the diff."
+ )
diff --git a/tests/test_packaging_build_guard.py b/tests/test_packaging_build_guard.py
index 0b169f76ed8..b21db872321 100644
--- a/tests/test_packaging_build_guard.py
+++ b/tests/test_packaging_build_guard.py
@@ -94,3 +94,25 @@ def test_artifact_build_allows_explicit_nix_package_build_marker(kind, artifact_
missing = sorted(expected - shipped)
assert not missing, f"{kind} omits bundled plugin manifests: {missing}"
+
+
+def test_wheel_ships_pm_package_and_lock_json(tmp_path):
+ """The pm/ package manager must survive a sealed wheel build.
+
+ pm is a flat package listed in [tool.setuptools.packages.find] include,
+ and pm/lock.json is its runtime pin table (uv/python/tool versions +
+ sha256s) declared via [tool.setuptools.package-data]. If either drops
+ out of the wheel, installed Hermes has no package manager at all --
+ exercise the real PEP 517 build path rather than reading TOML source.
+ """
+ result = _build_artifact("wheel", tmp_path, nix_build=True)
+
+ assert result.returncode == 0, result.stderr
+ artifacts = list(tmp_path.glob("hermes_agent-*.whl"))
+ assert artifacts
+
+ with zipfile.ZipFile(artifacts[0]) as wheel:
+ shipped = set(wheel.namelist())
+
+ missing = sorted({"pm/__init__.py", "pm/lock.json"} - shipped)
+ assert not missing, f"wheel omits pm package files: {missing}"
diff --git a/tests/test_wal_reset_repair_hint.py b/tests/test_wal_reset_repair_hint.py
new file mode 100644
index 00000000000..c96b6498435
--- /dev/null
+++ b/tests/test_wal_reset_repair_hint.py
@@ -0,0 +1,44 @@
+"""Behavior tests for hermes_state._wal_reset_repair_hint.
+
+The WAL-reset corruption warning's repair hint must match what the user's
+install can actually do: source checkouts get the venv-setup step, packaged
+installs get their steward's update command (#75153).
+"""
+
+from unittest.mock import patch
+
+import hermes_state
+
+
+def _hint_for(method):
+ with patch("hermes_cli.config.detect_install_method", return_value=method), \
+ patch("hermes_cli.config.recommended_update_command_for_method",
+ return_value=f"CMD-{method}"):
+ return hermes_state._wal_reset_repair_hint()
+
+
+def test_source_checkout_gets_venv_setup_hint():
+ assert _hint_for("source") == (
+ "source checkouts can repair the runtime by re-running their venv setup"
+ )
+
+
+def test_git_install_gets_hermes_managed_hint():
+ assert _hint_for("git") == (
+ "Hermes-managed installs can repair the embedded runtime with `CMD-git`"
+ )
+
+
+def test_docker_gets_container_image_hint():
+ assert _hint_for("docker") == "update the container image with `CMD-docker`"
+
+
+def test_nix_passes_through_recommended_command():
+ assert _hint_for("nix") == "CMD-nix"
+
+
+def test_hint_falls_back_when_detection_fails():
+ with patch("hermes_cli.config.detect_install_method",
+ side_effect=RuntimeError("boom")):
+ hint = hermes_state._wal_reset_repair_hint()
+ assert "SQLite 3.51.3+" in hint
diff --git a/tools/environments/base.py b/tools/environments/base.py
index 1ab32f8a808..9b36719087f 100644
--- a/tools/environments/base.py
+++ b/tools/environments/base.py
@@ -441,7 +441,7 @@ def _load_json_store(path: Path) -> dict:
"""Load a JSON file as a dict, returning ``{}`` on any error."""
if path.exists():
try:
- return json.loads(path.read_text(encoding="utf-8"))
+ return json.loads(path.read_text(encoding="utf-8-sig"))
except Exception:
pass
return {}
@@ -506,7 +506,7 @@ class _ThreadedProcessHandle:
# Pipe for stdout — drain thread in _wait_for_process reads the read end.
read_fd, write_fd = os.pipe()
- self._stdout = os.fdopen(read_fd, "r", encoding="utf-8", errors="replace")
+ self._stdout = os.fdopen(read_fd, "r", encoding="utf-8", errors="replace") # windows-footgun: ok (pipe is BOM-free)
self._write_fd = write_fd
def _worker():
@@ -677,8 +677,8 @@ class BaseEnvironment(ABC):
"""Return the backend temp directory used for session artifacts.
Most sandboxed backends use ``/tmp`` inside the target environment.
- LocalEnvironment overrides this on platforms like Termux where ``/tmp``
- may be missing and ``TMPDIR`` is the portable writable location.
+ LocalEnvironment overrides this on hosts where ``/tmp`` may be missing
+ and ``TMPDIR`` is the portable writable location.
"""
return "/tmp"
diff --git a/tools/environments/local.py b/tools/environments/local.py
index a70897e1941..33380189a16 100644
--- a/tools/environments/local.py
+++ b/tools/environments/local.py
@@ -453,7 +453,7 @@ _HERMES_PROVIDER_ENV_BLOCKLIST = _build_provider_env_blocklist()
# system/venv Pythons — to the Hermes venv's stdlib, which crashes with
# version-mismatch errors before a child script even imports a package
# (#75018). Hermes itself treats PYTHONHOME as contamination in its own
-# child processes (managed_uv.py, sqlite_runtime.py), so stripping it from
+# child processes (sqlite_runtime.py), so stripping it from
# subprocess envs is consistent. Users who need PYTHONHOME for a specific
# child can set it explicitly in the command.
#
@@ -717,7 +717,9 @@ _ALWAYS_STRIP_KEYS: frozenset[str] = frozenset({
})
-def hermes_subprocess_env(*, inherit_credentials: bool = False) -> dict[str, str]:
+def hermes_subprocess_env(
+ *, inherit_credentials: bool = False, base_env: dict[str, str] | None = None
+) -> dict[str, str]:
"""Build a sanitized environment dict for a spawned subprocess.
Centralized helper for the **non-terminal** spawn surface (browser,
@@ -748,8 +750,12 @@ def hermes_subprocess_env(*, inherit_credentials: bool = False) -> dict[str, str
needs ``BROWSERBASE_API_KEY`` / ``FIRECRAWL_API_KEY``) should call with
``inherit_credentials=False`` and copy just those keys back from
``os.environ`` into the returned dict.
+
+ ``base_env`` swaps the starting environment (default ``os.environ``) —
+ for callers that already hold a curated env (pm's sanitized uv env) and
+ want the strip policy applied on top of it.
"""
- env = os.environ.copy()
+ env = dict(base_env) if base_env is not None else os.environ.copy()
# Tier 1 — always strip.
for key in _ALWAYS_STRIP_KEYS:
@@ -866,215 +872,20 @@ def build_subprocess_env(
def _find_bash() -> str:
- """Find bash for command execution."""
- if not _IS_WINDOWS:
- return (
- shutil.which("bash")
- or ("/usr/bin/bash" if os.path.isfile("/usr/bin/bash") else None)
- or ("/bin/bash" if os.path.isfile("/bin/bash") else None)
- or os.environ.get("SHELL")
- or "/bin/sh"
- )
-
- candidates: list[str] = []
-
- custom = os.environ.get("HERMES_GIT_BASH_PATH")
- if custom and os.path.isfile(custom):
- candidates.append(custom)
-
- # Prefer our own portable Git install — a broken or partially-uninstalled
- # system Git (or a stale HERMES_GIT_BASH_PATH pointing at one) must not
- # brick the terminal. install.ps1 drops PortableGit here when needed.
- #
- # Layouts (both checked so upgrades between MinGit and PortableGit
- # installs work transparently):
- # PortableGit: %LOCALAPPDATA%\hermes\git\bin\bash.exe (primary)
- # MinGit: %LOCALAPPDATA%\hermes\git\usr\bin\bash.exe (legacy/32-bit fallback)
- _local_appdata = os.environ.get("LOCALAPPDATA", "")
- _hermes_portable_git = os.path.join(_local_appdata, "hermes", "git") if _local_appdata else ""
- if _hermes_portable_git:
- for candidate in (
- os.path.join(_hermes_portable_git, "bin", "bash.exe"), # PortableGit (primary)
- os.path.join(_hermes_portable_git, "usr", "bin", "bash.exe"), # MinGit fallback
- ):
- if os.path.isfile(candidate) and candidate not in candidates:
- candidates.append(candidate)
-
- # Check known Git for Windows install locations before PATH lookup.
- # On machines with both WSL and Git for Windows, shutil.which("bash")
- # may return WSL's bash (which doesn't understand Windows paths and
- # will fail silently). Explicit Git-for-Windows paths avoid that.
- for candidate in (
- os.path.join(os.environ.get("ProgramFiles", r"C:\Program Files"), "Git", "bin", "bash.exe"),
- os.path.join(os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)"), "Git", "bin", "bash.exe"),
- os.path.join(_local_appdata, "Programs", "Git", "bin", "bash.exe") if _local_appdata else "",
- ):
- if candidate and os.path.isfile(candidate) and candidate not in candidates:
- candidates.append(candidate)
-
- found = shutil.which("bash")
- if found and found not in candidates:
- candidates.append(found)
-
- # Prefer the first candidate that can actually start. A stale
- # HERMES_GIT_BASH_PATH pointing at a broken Git-for-Windows install
- # (``Directory \\drivers\\etc does not exist``) must not win over a
- # healthy portable Git under %LOCALAPPDATA%\\hermes\\git.
- for candidate in candidates:
- if _bash_starts(candidate):
- if candidate != custom and custom and os.path.isfile(custom):
- logger.warning(
- "HERMES_GIT_BASH_PATH=%s fails to start; using %s instead",
- custom,
- candidate,
- )
- return candidate
-
- if candidates:
- probe_details = "\n".join(
- detail
- for candidate in candidates
- if (detail := _bash_probe_details_cache.get(candidate))
- )
- if _mandatory_aslr_enabled() is True or _looks_like_msys_spawn_failure(
- probe_details
- ):
- raise RuntimeError(_git_bash_aslr_help(candidates[0], probe_details))
-
- # Last resort for failures unrelated to the known MSYS/ASLR class:
- # return the first path so the caller still sees the real bash error
- # instead of the less useful "not found" message.
- return candidates[0]
-
+ """Resolve the shell Hermes runs commands with. Owned by pm (the store
+ is the authority on bundled bash); this is a thin wrapper over
+ pm.shell() for callers that need a bash binary."""
+ import pm.shell
+
+ bash = pm.shell.bash()
+ if bash:
+ return bash
raise RuntimeError(
- "Git Bash not found. Hermes Agent requires Git for Windows on Windows.\n"
- "Install it from: https://git-scm.com/download/win\n"
- "Or set HERMES_GIT_BASH_PATH to your bash.exe location."
- )
-
-
-_bash_starts_cache: dict[str, bool] = {}
-_bash_probe_details_cache: dict[str, str] = {}
-_mandatory_aslr_enabled_cache: "bool | None" = None
-
-_BASH_EXTERNAL_PROGRAM_PROBE = "/usr/bin/true; /usr/bin/cat --version >/dev/null"
-
-
-def _looks_like_msys_spawn_failure(details: str) -> bool:
- """Match Git-for-Windows child-launch failures associated with ASLR."""
- lowered = details.lower()
- return any(
- marker in lowered
- for marker in (
- "dofork:",
- "child_copy:",
- "0xc0000142",
- "0xc0000005",
- )
+ "No shell found. Hermes needs bash (Git for Windows on Windows). "
+ "Run `hermes pm install` or reinstall the bundle."
)
-def _mandatory_aslr_enabled() -> "bool | None":
- """Return Windows' system-wide ForceRelocateImages state when available."""
- global _mandatory_aslr_enabled_cache
- if _mandatory_aslr_enabled_cache is not None:
- return _mandatory_aslr_enabled_cache
-
- try:
- powershell = shutil.which("powershell.exe") or "powershell.exe"
- result = subprocess.run(
- [
- powershell,
- "-NoProfile",
- "-NonInteractive",
- "-Command",
- "(Get-ProcessMitigation -System).Aslr.ForceRelocateImages.ToString()",
- ],
- capture_output=True,
- text=True, encoding="utf-8", errors="replace",
- timeout=10,
- creationflags=windows_hide_flags(),
- )
- if result.returncode != 0:
- return None
- value = (result.stdout or "").strip().upper()
- if value == "ON":
- _mandatory_aslr_enabled_cache = True
- return True
- if value in {"OFF", "NOTSET"}:
- _mandatory_aslr_enabled_cache = False
- return False
- except Exception as exc:
- logger.debug("Could not query Windows Mandatory ASLR state: %s", exc)
- return None
-
-
-def _git_root_from_bash(bash: str) -> str:
- """Resolve Git's root from either <root>/bin or <root>/usr/bin bash."""
- bin_dir = ntpath.dirname(ntpath.normpath(bash))
- if ntpath.basename(bin_dir).lower() != "bin":
- return ntpath.dirname(bin_dir)
- parent = ntpath.dirname(bin_dir)
- if ntpath.basename(parent).lower() == "usr":
- return ntpath.dirname(parent)
- return parent
-
-
-def _git_bash_aslr_help(bash: str, details: str = "") -> str:
- """Build the targeted per-program Mandatory-ASLR remediation."""
- git_root = _git_root_from_bash(bash)
- escaped_root = git_root.replace("'", "''")
- detail_line = f"\nGit Bash probe output: {details[:500]}" if details else ""
- return (
- f"Git Bash at {bash} cannot launch required MSYS child processes while "
- "Windows Mandatory ASLR (ForceRelocateImages) is enabled, or its output "
- f"matches that Git-for-Windows failure class.{detail_line}\n"
- "Reinstalling Git will not change the Windows mitigation policy. Open "
- "PowerShell as Administrator and run:\n"
- f"$gitRoot = '{escaped_root}'\n"
- 'Get-Item "$gitRoot\\bin\\bash.exe", "$gitRoot\\usr\\bin\\*.exe" '
- "-ErrorAction SilentlyContinue | ForEach-Object { "
- "Set-ProcessMitigation -Name $_.FullName -Disable ForceRelocateImages }\n"
- "Then restart Hermes. If the override is blocked or later re-applied, "
- "ask your Windows administrator to allow this per-program exception."
- )
-
-
-def _bash_starts(bash: str) -> bool:
- """True if *bash* can launch external MSYS programs.
-
- Uses ``--noprofile --norc`` so a broken login post-install
- (``Directory \\drivers\\etc``) does not falsely condemn an otherwise
- usable bash. The external ``true`` and ``cat`` calls are intentional:
- a builtin-only ``exit 0`` probe misses Git-for-Windows fork/spawn failures
- under system-wide Mandatory ASLR. Cached per path for the process lifetime.
- """
- cached = _bash_starts_cache.get(bash)
- if cached is not None:
- return cached
-
- try:
- result = subprocess.run(
- [bash, "--noprofile", "--norc", "-c", _BASH_EXTERNAL_PROGRAM_PROBE],
- capture_output=True,
- text=True, encoding="utf-8", errors="replace",
- timeout=15,
- creationflags=windows_hide_flags() if _IS_WINDOWS else 0,
- )
- ok = result.returncode == 0
- if not ok:
- combined = f"{result.stdout or ''}{result.stderr or ''}"
- _bash_probe_details_cache[bash] = combined.strip()[:2000]
- logger.debug("bash probe failed for %s: %s", bash, combined.strip()[:200])
- except Exception as exc:
- _bash_probe_details_cache[bash] = str(exc)[:2000]
- logger.debug("bash probe error for %s: %s", bash, exc)
- ok = False
-
- _bash_starts_cache[bash] = ok
- return ok
-
-
_git_bash_bin_dirs_cache: "list[str] | None" = None
@@ -1294,7 +1105,7 @@ def _managed_runtime_path_entries() -> list[str]:
itself, so on a machine where Hermes provisioned its own toolchain a
command the agent runs resolves a system copy instead — or nothing at all:
- - ``$HERMES_HOME/node`` (+ ``/bin``) — installed to satisfy the desktop and
+ - the pm store's node/npm entries — installed to satisfy the desktop and
browser toolchain. ``tools/browser_tool.py`` already does this for its own
subprocesses; the agent's shell deserves the same.
- ``$HERMES_HOME/bin`` — the managed ``uv``. ``install.sh`` writes it there
@@ -1302,13 +1113,16 @@ def _managed_runtime_path_entries() -> list[str]:
uv is the managed one looks uv-less to both the agent and the model.
Resolved per call rather than cached in a module constant because
- ``get_hermes_home()`` is profile-scoped and a managed tree can appear
- mid-process (``heal_hermes_managed_node``, a first browser install).
+ ``get_hermes_home()`` is profile-scoped and a managed runtime can appear
+ mid-process (a lazy pm install, a first browser install).
"""
try:
- from hermes_constants import get_hermes_home, iter_hermes_node_dirs
+ import pm
+ from hermes_constants import get_hermes_home
- candidates = [*iter_hermes_node_dirs(), get_hermes_home() / "bin"]
+ env = pm.env_for("npm", base_env={"PATH": ""})
+ managed = [Path(d) for d in env.get("PATH", "").split(os.pathsep) if d]
+ candidates = [*managed, get_hermes_home() / "bin"]
return [str(d) for d in candidates if d.is_dir()]
except Exception:
return []
@@ -1895,7 +1709,7 @@ class LocalEnvironment(BaseEnvironment):
def get_temp_dir(self) -> str:
"""Return a shell-safe writable temp dir for local execution.
- Termux does not provide /tmp by default, but exposes a POSIX TMPDIR.
+ Some Unix hosts do not provide /tmp but do export a POSIX TMPDIR.
Prefer POSIX-style env vars when available, keep using /tmp on regular
Unix systems, and only fall back to tempfile.gettempdir() when it also
resolves to a POSIX path.
diff --git a/tools/lazy_deps.py b/tools/lazy_deps.py
deleted file mode 100644
index 64d4f2ec312..00000000000
--- a/tools/lazy_deps.py
+++ /dev/null
@@ -1,1249 +0,0 @@
-"""
-Lazy dependency installer for opt-in Hermes Agent backends.
-
-Many Hermes features (Mistral TTS, ElevenLabs TTS, Honcho memory, Bedrock,
-Slack, Matrix, etc.) require Python packages that not every user needs. The
-historical approach was to bundle them all under ``pyproject.toml`` extras
-(``hermes-agent[all]``) and install them eagerly at setup time. That has
-two problems:
-
-1. **Fragility.** When one extra's transitive dependency becomes
- unavailable on PyPI (quarantined for malware, yanked, broken upload),
- the *entire* ``[all]`` resolve fails and fresh installs silently fall
- back to a stripped tier — losing 10+ unrelated extras at once.
-
-2. **Bloat.** A user who only ever talks to one provider pulls hundreds
- of packages they will never import.
-
-The lazy-install pattern fixes both. Backends call :func:`ensure` at the
-top of their first-import path. If the deps are missing, ``ensure`` checks
-the ``security.allow_lazy_installs`` config flag (default true) and runs
-a venv-scoped pip install. If the user has explicitly disabled lazy
-installs, ``ensure`` raises :class:`FeatureUnavailable` with a clear
-remediation hint pointing at ``hermes tools`` or the manual pip command.
-
-Security model:
-
-* **Venv-scoped by default.** Installs target ``sys.executable`` in the
- active venv. We never touch the system Python.
-* **Durable-target mode (immutable images).** When the deployment seals the
- agent's own venv (the Docker image sets ``HERMES_DISABLE_LAZY_INSTALLS=1``
- and makes ``/opt/hermes`` read-only), setting
- ``HERMES_LAZY_INSTALL_TARGET`` redirects lazy installs to a writable
- directory on the durable data volume (e.g. ``/opt/data/lazy-packages``).
- That directory is **appended to the end of ``sys.path``** — never
- prepended, never exported via ``PYTHONPATH`` — so the agent's own
- site-packages wins every name collision. A package installed this way can
- only ADD new importable modules; it can never shadow, downgrade, or break
- a module the core already ships. The worst a bad/incompatible backend
- package can do is fail to import and report itself unavailable — the agent
- core stays healthy. This is the structural guarantee that a lazily
- installed package cannot brick Hermes, which is what made it safe to seal
- the venv in the first place. Compiled-wheel safety across image rebuilds
- is handled by an ABI/Python-version stamp on the target subdir (see
- :func:`_ensure_target_ready`).
-* **PyPI by package name only.** Specs may be ``"package>=1.0,<2"`` etc.
- We do NOT support ``--index-url`` overrides, ``git+https://``, file:
- paths, or any other input that could be hijacked by a malicious config.
-* **Allowlist.** Only specs that appear in :data:`LAZY_DEPS` can be
- installed via this path. A typo in feature name doesn't get the user
- install-anything semantics.
-* **Opt-out.** Setting ``security.allow_lazy_installs: false`` in
- ``config.yaml`` disables runtime installs in BOTH modes. Users in
- restricted networks or strict security postures can pin themselves to
- whatever was installed at setup time.
-* **Offline detection.** If the install fails (offline, mirror down,
- PyPI 404 / quarantine), we surface the failure as
- :class:`FeatureUnavailable` with the actual pip stderr — no silent
- retries, no caching of bad state.
-
-Adding a new backend:
-
-1. Add an entry to :data:`LAZY_DEPS` with the package specs.
-2. At the top of the backend module's import path, call
- ``ensure("feature.name")`` inside a try/except that converts
- :class:`FeatureUnavailable` to a useful runtime error.
-"""
-
-from __future__ import annotations
-
-import logging
-import os
-import re
-import shutil
-import site
-import subprocess
-import sys
-import sysconfig
-from dataclasses import dataclass
-from pathlib import Path
-from typing import Any, Callable, Optional
-
-from hermes_cli._subprocess_compat import windows_hide_flags
-
-logger = logging.getLogger(__name__)
-
-
-# =============================================================================
-# Allowlist of lazy-installable backends.
-#
-# Keys are dot-separated feature names ("namespace.backend"). Values are
-# tuples of pip-installable specs that match the corresponding extra in
-# pyproject.toml. The framework enforces that only specs from this map
-# can flow into the pip install command.
-# =============================================================================
-
-
-LAZY_DEPS: dict[str, tuple[str, ...]] = {
- # ─── Inference providers ───────────────────────────────────────────────
- # Native Anthropic SDK — needed when provider=anthropic (not via
- # OpenRouter / aggregators which use the openai SDK).
- "provider.anthropic": ("anthropic==0.87.0",), # CVE-2026-34450, CVE-2026-34452
- # AWS Bedrock provider
- "provider.bedrock": ("boto3==1.42.89",),
- # Google Vertex AI provider — OAuth2 token minting for the Gemini
- # OpenAI-compatible endpoint. Only loaded when provider=vertex is selected;
- # google-auth is NOT in [all] so plain installs don't carry it.
- "provider.vertex": (
- "google-auth==2.55.1",
- "pyasn1==0.6.4",
- ),
- # Microsoft Foundry — Entra ID auth (managed identity, workload identity,
- # service principal, az login, VS Code, azd, PowerShell). Only loaded
- # when model.auth_mode=entra_id is selected; key-based azure-foundry
- # users never pay this import.
- "provider.azure_identity": ("azure-identity==1.25.3",),
-
- # ─── Web search backends ───────────────────────────────────────────────
- "search.exa": ("exa-py==2.10.2",),
- "search.firecrawl": ("firecrawl-py==4.17.0",),
- "search.parallel": ("parallel-web==0.4.2",),
-
- # ─── Monitoring ─────────────────────────────────────────────────────────
- # OTLP gateway monitoring export. Lazily installed on first use of
- # monitoring.gateway_health_export / monitoring.export.otlp. Tracks the
- # `otlp` extra in pyproject.toml — bump both together.
- "export.otlp": (
- "opentelemetry-sdk==1.39.1",
- "opentelemetry-exporter-otlp-proto-http==1.39.1",
- ),
-
- # ─── TTS providers ─────────────────────────────────────────────────────
- # Pinned to exact versions to match pyproject.toml's no-ranges policy
- # (see comment at top of [project.dependencies]). When bumping, update
- # both this map AND the corresponding extra in pyproject.toml.
- #
- # mistralai pin tracks the `mistral` extra in pyproject.toml. PyPI
- # quarantined the project 2026-05-12 (malicious 2.4.6, Mini Shai-Hulud);
- # 2.4.6 was removed and clean releases resumed (2.4.7, 2.4.8). Voxtral
- # STT + TTS share the same SDK.
- "tts.mistral": ("mistralai==2.4.8",),
- "tts.edge": ("edge-tts==7.2.7",),
- "tts.elevenlabs": ("elevenlabs==1.59.0",),
-
- # ─── Speech-to-text providers ──────────────────────────────────────────
- "stt.mistral": ("mistralai==2.4.8",),
- "stt.faster_whisper": (
- "faster-whisper==1.2.1",
- "sounddevice==0.5.5",
- "numpy==2.4.3",
- ),
- # SILK voice-note decoding (WeChat/QQ .silk voice messages). pilk is a
- # small silk-v3 codec binding; installed on first .silk transcription.
- "stt.silk": ("pilk==0.2.4",),
-
- # ─── Wake word ("Hey Hermes") engines ──────────────────────────────────
- # Keep in sync with the `wake` extra in pyproject.toml. openWakeWord is the
- # free, local default (ONNX runtime); Porcupine is the premium engine.
- # openWakeWord's ONNX embedding model returns near-zero scores on macOS
- # ARM64 (dscripka/openWakeWord#336), so the wake word runs on the tflite
- # backend there. Upstream declares tflite-runtime for Linux only;
- # ai-edge-litert is the macOS equivalent, bridged in tools/wake_word.py.
- # It lives in its own feature because lazy-dep specs cannot carry PEP 508
- # environment markers (_spec_is_safe rejects ";"), so the platform gate is
- # applied by the caller instead.
- "wake.openwakeword.tflite": (
- "ai-edge-litert==2.1.6",
- ),
- "wake.openwakeword": (
- "openwakeword==0.6.0",
- "onnxruntime==1.27.0",
- "sounddevice==0.5.5",
- "numpy==2.4.3",
- ),
- # Open-vocabulary keyword spotting: any typed phrase, zero training.
- # sentencepiece is required by sherpa_onnx.text2token (runtime phrase
- # tokenization) even though sherpa-onnx doesn't declare it.
- "wake.sherpa": (
- "sherpa-onnx==1.13.4",
- "sentencepiece==0.2.2",
- "sounddevice==0.5.5",
- "numpy==2.4.3",
- ),
- "wake.porcupine": (
- "pvporcupine==4.0.3",
- "sounddevice==0.5.5",
- "numpy==2.4.3",
- ),
-
- # ─── Image generation backends ─────────────────────────────────────────
- "image.fal": ("fal-client==0.13.1",),
-
- # ─── Memory providers ──────────────────────────────────────────────────
- "memory.honcho": ("honcho-ai==2.2.0",),
- "memory.hindsight": ("hindsight-client==0.6.1",),
- # supermemory + mem0 are opt-in cloud memory providers with their own
- # SDKs. On the published Docker image the agent venv is sealed
- # (HERMES_DISABLE_LAZY_INSTALLS=1) and lazy installs are redirected to the
- # durable target — so, like honcho/hindsight, these MUST go through
- # ensure() to be installable there. Without an allowlist entry + an
- # ensure() call at the import site, the SDK never installs on a hosted
- # instance and the provider silently reports itself unavailable.
- "memory.supermemory": ("supermemory==3.50.0",),
- "memory.mem0": ("mem0ai==2.0.10",),
-
- # ─── Messaging platforms (lazy-installable on demand) ──────────────────
- "platform.telegram": ("python-telegram-bot[webhooks]==22.8",),
- # brotlicffi gives aiohttp a working 2-arg Decompressor.process() for
- # Discord CDN's Brotli-encoded attachments. Without it, aiohttp falls
- # back to google's `Brotli` package (1-arg API), and any .txt/.md/.doc
- # uploaded to the Discord gateway fails to decode at att.read() with
- # "Can not decode content-encoding: br" — see #12511 / #15744.
- "platform.discord": (
- "discord.py[voice]==2.7.1",
- "brotlicffi==1.2.0.1",
- # discord.py pulls aiohttp transitively (>=3.7.4,<4) as its HTTP
- # backbone. Pin the patched floor here too so the lazy Discord path
- # can't keep an already-installed vulnerable aiohttp satisfying that
- # range — mirrors the messaging extra and platform.slack.
- "aiohttp==3.14.3", # prior CVEs + GHSA-cq5v-8q36-5273/GHSA-mfx4-hv73-q22v/GHSA-mq44-7p77-q5h7
- ),
- "platform.slack": (
- "slack-bolt==1.30.0",
- "slack-sdk==3.43.0",
- "aiohttp==3.14.3", # prior CVEs + GHSA-cq5v-8q36-5273/GHSA-mfx4-hv73-q22v/GHSA-mq44-7p77-q5h7
- ),
- "platform.matrix": (
- "mautrix[encryption]==0.21.1",
- "aiosqlite==0.22.1",
- "asyncpg==0.31.0",
- "aiohttp-socks==0.11.0",
- # mautrix (aiohttp>=3,<4) and aiohttp-socks (aiohttp>=3.10.0) only cap
- # aiohttp transitively, so a vulnerable already-installed aiohttp still
- # satisfies both — pin the patched floor here too, like platform.discord.
- "aiohttp==3.14.3", # prior CVEs + GHSA-cq5v-8q36-5273/GHSA-mfx4-hv73-q22v/GHSA-mq44-7p77-q5h7
- ),
- "platform.dingtalk": (
- "dingtalk-stream==0.24.3",
- "alibabacloud-dingtalk==2.2.42",
- "qrcode==7.4.2",
- ),
- "platform.feishu": (
- "lark-oapi==1.6.8",
- "qrcode==7.4.2",
- ),
- # WeCom callback-mode adapter — parses untrusted XML POST bodies. Pulls
- # defusedxml only; aiohttp/httpx are core dependencies of every messaging
- # adapter and ship via `platform.discord` / `platform.slack` / etc.
- "platform.wecom_callback": ("defusedxml==0.7.1",),
- # Microsoft Teams adapter — microsoft-teams-apps pulls a heavy tree
- # (microsoft-teams-api/cards/common, dependency-injector, msal). Lazy-
- # installed on demand like every other messaging platform; also exposed
- # as the `teams` extra in pyproject for packagers / explicit installs.
- "platform.teams": ("microsoft-teams-apps==2.0.13.4", "aiohttp==3.14.3"), # aiohttp 3.14.3: prior CVEs + GHSA-cq5v-8q36-5273/GHSA-mfx4-hv73-q22v/GHSA-mq44-7p77-q5h7
-
- # ─── Terminal backends ─────────────────────────────────────────────────
- "terminal.modal": ("modal==1.3.4",),
- "terminal.daytona": ("daytona==0.155.0",),
- "terminal.vercel": ("vercel==0.7.2",),
-
- # ─── Skills ────────────────────────────────────────────────────────────
- "skill.google_workspace": (
- "google-api-python-client==2.194.0",
- "google-auth==2.55.1",
- "google-auth-oauthlib==1.3.1",
- "google-auth-httplib2==0.3.1",
- # Transitive via google-api-python-client/google-auth-httplib2; keep explicit
- # so lazy installs do not resolve vulnerable transitives: httplib2 0.31.2
- # (GHSA-j5g9-f88f-gfj3 decompression bomb DoS), stale pyasn1/google-auth.
- "httplib2==0.32.0",
- "pyasn1==0.6.4",
- ),
- "skill.youtube": ("youtube-transcript-api==1.2.4",),
-
- # ─── Tools ─────────────────────────────────────────────────────────────
- # ACP adapter (VS Code / Zed / JetBrains integration)
- "tool.acp": ("agent-client-protocol==0.9.0",),
- # Dashboard (`hermes dashboard`)
- "tool.dashboard": (
- "fastapi==0.133.1",
- "uvicorn[standard]==0.41.0",
- "starlette==1.3.1", # CVE-2026-48710 (BadHost) — keep lazy-install in sync with pyproject [web]
- "python-multipart==0.0.32", # FastAPI UploadFile/Form for streaming uploads (NS-501)
- ),
- # Vision image-resize recovery (Pillow). Pillow is now a CORE dependency
- # (pyproject `dependencies`), so this entry is a belt-and-suspenders fallback
- # for stripped/source-build installs that somehow dropped it. The vision
- # call site uses prompt=False so it can never raise a blocking input()
- # prompt mid-session (#40490).
- "tool.vision": ("Pillow==12.3.0",),
- # Document-to-Markdown extraction for read_file (firecrawl-anydoc, Rust
- # core, imports as `anydoc`). Widens read_file's auto-extraction beyond
- # the stdlib .ipynb/.docx/.xlsx to PDF, legacy Office (.doc/.ppt/.xls),
- # OpenDocument, RTF, and EPUB. Installed on first read of such a file;
- # the call site uses prompt=False so read_file never blocks on a prompt.
- # NOTE: bundled in core pyproject dependencies since the hosted-OCR
- # wiring (keep this lazy pin in lockstep with pyproject) — this entry
- # survives as the self-heal path for lean/partial installs.
- "tool.doc_extract": ("firecrawl-anydoc==0.2.4",), # lockstep with pyproject
- # Computer Use (cua-driver) — the MCP client SDK used to spawn and talk
- # to the cua-driver process over stdio. Matches the `mcp` / `computer-use`
- # extras in pyproject.toml. The one-liner installer pulls this in via
- # `[all]`; lazy-installing here covers lean / partial / broken-extra
- # installs so computer_use never dead-ends on `No module named 'mcp'`.
- "tool.computer_use": (
- "mcp==2.0.0",
- "httpx2==2.7.0", # mcp 2.x HTTP stack — keep in sync with pyproject [computer-use]
- "starlette==1.3.1", # CVE-2026-48710 — keep in sync with pyproject [computer-use]
- ),
- # HF Agent Trace Viewer upload (hermes trace upload / /upload-trace).
- #
- # huggingface-hub is a SHARED dependency: transformers (pulled by
- # sentence-transformers for local Hindsight embeddings) requires
- # >=1.5.0,<2, and faster-whisper/tokenizers depend on it transitively.
- # Because active_features() marks a feature active from mere package
- # presence, the `hermes update` lazy-refresh pass re-asserts THIS pin on
- # every install where hub is present — so an exact pin below 1.5.0
- # force-downgrades the shared package and breaks Hindsight startup
- # (#60783). Policy: keep the exact pin (no ranges — security posture),
- # but it MUST stay inside transformers' accepted window and MUST match
- # uv.lock so the whole tree converges on ONE hub version
- # (tests/test_project_metadata.py enforces both). When bumping: update
- # here AND `uv lock --upgrade-package huggingface-hub` in lockstep.
- "tool.trace_upload": ("huggingface-hub==1.24.0",),
-}
-
-
-# Conservative regex for spec validation — package name plus optional
-# version range. Reject anything that looks like a URL, file path, or shell
-# metacharacter.
-_SAFE_SPEC = re.compile(
- r"^[A-Za-z0-9_][A-Za-z0-9_.\-]*" # package name
- r"(?:\[[A-Za-z0-9_,\-]+\])?" # optional [extras]
- r"(?:[<>=!~]=?[A-Za-z0-9_.\-+,*<>=!~]+)?" # optional version specifier
- r"$"
-)
-
-
-class FeatureUnavailable(RuntimeError):
- """A lazily-installable feature is missing and cannot be made available.
-
- Either the deps were never installed and the user has disabled lazy
- installs, or the install attempt failed.
- """
-
- def __init__(self, feature: str, missing: tuple[str, ...], reason: str):
- self.feature = feature
- self.missing = missing
- self.reason = reason
- super().__init__(self._format())
-
- def _format(self) -> str:
- spec_list = " ".join(repr(s) for s in self.missing)
- return (
- f"Feature {self.feature!r} unavailable: {self.reason}. "
- f"To enable manually: uv pip install {spec_list} "
- f"(or: pip install {spec_list})."
- )
-
-
-@dataclass(frozen=True)
-class _InstallResult:
- success: bool
- stdout: str
- stderr: str
-
-
-# =============================================================================
-# Internals
-# =============================================================================
-
-
-# Environment variable that redirects lazy installs away from the (sealed)
-# agent venv and into a writable directory on a durable volume. Set by the
-# Docker image to /opt/data/lazy-packages. This is an internal bridge var,
-# not user-facing config: the user-facing knob remains
-# security.allow_lazy_installs in config.yaml. When unset, lazy installs go
-# into the active venv as before.
-_LAZY_TARGET_ENV = "HERMES_LAZY_INSTALL_TARGET"
-
-# Name of the stamp file written into the target dir recording the Python
-# X.Y + ABI it was populated for. If a container rebuild bumps the
-# interpreter, compiled wheels (.so) in the durable store would be ABI-
-# incompatible; we detect the mismatch and wipe the store so packages get
-# re-resolved against the new interpreter rather than importing a stale .so.
-_TARGET_STAMP_NAME = ".python-abi"
-
-
-def _python_abi_tag() -> str:
- """A stable token identifying the running interpreter's ABI.
-
- Combines the X.Y version with the EXT_SUFFIX (which encodes the ABI
- tag and platform, e.g. ``cpython-313-x86_64-linux-gnu``). Two
- interpreters that can share compiled wheels produce the same token.
- """
- ver = f"{sys.version_info.major}.{sys.version_info.minor}"
- ext = sysconfig.get_config_var("EXT_SUFFIX") or ""
- return f"{ver}:{ext}"
-
-
-def _lazy_install_target() -> Optional[Path]:
- """Return the durable install-target dir, or None for venv-scoped mode.
-
- Returns a path only when :data:`_LAZY_TARGET_ENV` is set to a non-empty
- value. The directory is created on demand by :func:`_ensure_target_ready`.
- """
- raw = os.environ.get(_LAZY_TARGET_ENV, "").strip()
- if not raw:
- return None
- return Path(raw)
-
-
-def _ensure_target_ready(target: Path) -> Optional[str]:
- """Create the target dir and validate its ABI stamp.
-
- If the stamp is missing it is written. If it is present but records a
- different interpreter ABI than the one now running (e.g. the container
- image was rebuilt onto a newer Python), the directory's contents are
- wiped and the stamp rewritten, so stale compiled wheels can't be
- imported against an incompatible interpreter.
-
- Returns ``None`` on success, or an error string if the directory can't
- be created / written (e.g. read-only mount, permission error).
- """
- want = _python_abi_tag()
- stamp = target / _TARGET_STAMP_NAME
- try:
- if target.exists():
- have = ""
- try:
- have = stamp.read_text(encoding="utf-8").strip()
- except (OSError, FileNotFoundError):
- have = ""
- if have and have != want:
- logger.info(
- "Lazy install target %s was built for ABI %r but running "
- "ABI is %r; wiping stale packages.",
- target, have, want,
- )
- for child in target.iterdir():
- if child.is_dir() and not child.is_symlink():
- shutil.rmtree(child, ignore_errors=True)
- else:
- try:
- child.unlink()
- except OSError:
- pass
- target.mkdir(parents=True, exist_ok=True)
- stamp.write_text(want, encoding="utf-8")
- except OSError as e:
- return f"lazy install target {target} is not writable: {e}"
- return None
-
-
-def _activate_target_on_syspath(target: Path) -> None:
- """Append the durable target to ``sys.path`` so its packages import.
-
- Appended to the END (never prepended) so the agent's own venv
- site-packages takes precedence on every name collision. Idempotent.
- Uses :func:`site.addsitedir` so ``.pth`` files (namespace packages,
- editable installs) inside the target are honoured, then enforces the
- append ordering — ``addsitedir`` would otherwise insert near the front.
- """
- target_str = str(target)
- # Snapshot existing entries so we can restore precedence afterwards.
- before = list(sys.path)
- if target_str not in before:
- site.addsitedir(target_str)
- # site.addsitedir may have inserted target (and any .pth-added dirs) at
- # the front. Move every newly-added entry to the end, preserving the
- # core venv's precedence. New entries are those not present `before`.
- new_entries = [p for p in sys.path if p not in before]
- if new_entries:
- sys.path[:] = [p for p in sys.path if p not in new_entries] + new_entries
- # importlib.metadata caches the path-based distribution finder; clear it
- # so a just-activated dir is visible to version() checks this process.
- try:
- import importlib
- importlib.invalidate_caches()
- except Exception:
- pass
-
-
-def activate_durable_lazy_target() -> None:
- """Public: wire the durable lazy-install target onto ``sys.path``.
-
- Safe no-op when :data:`_LAZY_TARGET_ENV` is unset or the directory does
- not yet exist. Called once early in process startup (before backends
- import) so packages installed into the durable store on a previous run
- are importable on this run. Never raises.
- """
- target = _lazy_install_target()
- if target is None:
- return
- try:
- if target.exists():
- _activate_target_on_syspath(target)
- except Exception as e: # pragma: no cover - defensive
- logger.debug("Failed to activate durable lazy target %s: %s", target, e)
-
-
-def _allow_lazy_installs() -> bool:
- """Return whether lazy installs are permitted in this environment.
-
- Resolution order:
-
- 1. ``security.allow_lazy_installs: false`` in config.yaml is an absolute
- opt-out — it disables installs in BOTH venv-scoped and durable-target
- modes. This is the user-facing kill switch.
- 2. ``HERMES_DISABLE_LAZY_INSTALLS=1`` seals the *agent venv* (set by the
- immutable Docker image). It blocks venv-scoped installs — UNLESS a
- durable install target is configured, in which case installs are
- redirected there (a path that structurally cannot break the sealed
- venv) and are therefore allowed.
-
- Defaults to True. If config is unreadable we fail open (allow), because
- refusing to install would lock people out of their own backends; the
- decision to block is an explicit user opt-in.
- """
- # (1) Config kill switch wins in every mode.
- try:
- from hermes_cli.config import load_config
- cfg = load_config()
- except Exception:
- cfg = None
- if cfg is not None:
- sec = cfg.get("security") or {}
- if not bool(sec.get("allow_lazy_installs", True)):
- return False
-
- # (2) Sealed-venv env var: blocks ONLY when there is no safe durable
- # target to redirect into. With a target set, the install goes to the
- # data volume (append-only on sys.path), so the seal is preserved.
- if os.environ.get("HERMES_DISABLE_LAZY_INSTALLS") == "1":
- return _lazy_install_target() is not None
-
- return True
-
-
-def _unsupported_feature_reason(feature: str) -> Optional[str]:
- """Return why a lazy feature cannot work on this host, or ``None``.
-
- This is a platform capability gate, not a security policy gate. It keeps
- known-impossible installs out of both first-use lazy installation and the
- ``hermes update`` lazy-refresh pass.
- """
- if sys.platform == "win32" and feature == "platform.matrix":
- return (
- "unsupported on Windows: Matrix E2EE depends on python-olm, "
- "which has no Windows wheel and requires make + libolm to build "
- "from sdist. Run Hermes under WSL to use Matrix on Windows."
- )
- return None
-
-
-def _spec_is_safe(spec: str) -> bool:
- """Reject pip specs that contain URLs, paths, or shell metacharacters."""
- if not spec or len(spec) > 200:
- return False
- if any(ch in spec for ch in (";", "|", "&", "`", "$", "\n", "\r", "\t", "\\")):
- return False
- if spec.startswith(("-", "/", ".")) or "://" in spec or "@" in spec:
- return False
- return bool(_SAFE_SPEC.match(spec))
-
-
-def _pkg_name_from_spec(spec: str) -> str:
- """Extract the bare package name from a pip spec.
-
- ``"slack-bolt>=1.18.0,<2"`` → ``"slack-bolt"``
- ``"mautrix[encryption]>=0.20"`` → ``"mautrix"``
- """
- m = re.match(r"^([A-Za-z0-9_][A-Za-z0-9_.\-]*)", spec)
- return m.group(1) if m else spec
-
-
-def _specifier_from_spec(spec: str) -> str:
- """Extract just the version-specifier portion of a pip spec.
-
- ``"honcho-ai==2.2.0"`` → ``"==2.2.0"``
- ``"mautrix[encryption]>=0.20,<1"`` → ``">=0.20,<1"``
- ``"package"`` → ``""`` (no version constraint)
- """
- # Strip the package name + optional [extras] block.
- m = re.match(r"^[A-Za-z0-9_][A-Za-z0-9_.\-]*(?:\[[A-Za-z0-9_,\-]+\])?", spec)
- if not m:
- return ""
- return spec[m.end():]
-
-
-def _is_satisfied(spec: str) -> bool:
- """Is ``spec`` already satisfied in the current env?
-
- Checks both presence AND version. If the package is installed at a
- version outside the spec's range, returns False so the caller will
- upgrade/downgrade to the pinned version. This is what makes
- ``hermes update`` propagate pin bumps in :data:`LAZY_DEPS` to already-
- installed backends instead of silently leaving stale versions in place.
-
- If ``packaging`` is unavailable for any reason (it's a transitive of
- pip so this should never happen), we fall back to a presence-only check
- so we err on the side of "don't churn".
- """
- pkg = _pkg_name_from_spec(spec)
- try:
- from importlib.metadata import PackageNotFoundError, version
- except ImportError:
- return False
- try:
- installed = version(pkg)
- except PackageNotFoundError:
- return False
- except Exception:
- return False
-
- spec_tail = _specifier_from_spec(spec)
- if not spec_tail:
- # Bare ``"package"`` — no version constraint, presence is enough.
- return True
-
- try:
- from packaging.specifiers import InvalidSpecifier, SpecifierSet
- from packaging.version import InvalidVersion, Version
- except ImportError:
- # packaging unavailable — fall back to "installed counts as satisfied".
- return True
-
- try:
- return Version(installed) in SpecifierSet(spec_tail)
- except (InvalidSpecifier, InvalidVersion, Exception):
- # Malformed spec or installed version we can't parse — don't churn.
- return True
-
-
-def _is_present(spec: str) -> bool:
- """Cheap presence-only check (package name installed at any version).
-
- Used by :func:`active_features` to detect backends the user has
- previously activated, regardless of whether the version pin moved.
- """
- pkg = _pkg_name_from_spec(spec)
- try:
- from importlib.metadata import PackageNotFoundError, version
- except ImportError:
- return False
- try:
- version(pkg)
- return True
- except PackageNotFoundError:
- return False
- except Exception:
- return False
-
-
-def _core_constraints_file() -> Optional[Path]:
- """Write a pip constraints file pinning every package already importable
- in the core environment to its installed version.
-
- Passed as ``--constraint`` for durable-target installs so the resolver
- pins shared transitive deps (httpx, pydantic, aiohttp, …) to the exact
- versions the core venv already ships, instead of pulling newer copies
- into the durable store. Two payoffs:
-
- * The durable store stays minimal — only genuinely-new packages land
- there; shared deps resolve to "already satisfied" against core.
- * A backend that *requires* a version conflicting with core fails loudly
- at install time (resolver conflict) rather than silently installing a
- shadowed copy that can never win on sys.path anyway.
-
- Returns the path to a temp constraints file, or None if enumeration
- failed (in which case the caller installs without constraints — still
- safe, just less tidy).
- """
- try:
- from importlib.metadata import distributions
- except ImportError:
- return None
- try:
- import tempfile
- lines = []
- seen = set()
- for dist in distributions():
- name = dist.metadata["Name"] if dist.metadata else None
- ver = dist.version
- if not name or not ver:
- continue
- key = name.lower()
- if key in seen:
- continue
- seen.add(key)
- lines.append(f"{name}=={ver}")
- if not lines:
- return None
- fd, path = tempfile.mkstemp(prefix="hermes-core-constraints-", suffix=".txt")
- with os.fdopen(fd, "w", encoding="utf-8") as f:
- f.write("\n".join(sorted(lines)) + "\n")
- return Path(path)
- except Exception as e:
- logger.debug("Could not build core constraints file: %s", e)
- return None
-
-
-def _venv_pip_install(specs: tuple[str, ...], *, timeout: int = 300) -> _InstallResult:
- """Install ``specs`` using the uv → pip → ensurepip ladder.
-
- Two modes:
-
- * **Venv-scoped (default).** Installs into the active venv
- (``sys.executable``). Used on normal installs.
- * **Durable-target.** When :data:`_LAZY_TARGET_ENV` is set, installs into
- that directory via ``--target`` and constrains shared deps to the
- core venv's versions (see :func:`_core_constraints_file`). The target
- is append-only on ``sys.path`` so it can never shadow core. Used by
- the immutable Docker image to keep lazy installs off the sealed venv.
-
- Mirrors the strategy in ``hermes_cli.tools_config._pip_install`` but
- kept independent here so this module has no CLI dependency.
- """
- if not specs:
- return _InstallResult(True, "", "")
-
- target = _lazy_install_target()
- constraints: Optional[Path] = None
-
- if target is not None:
- err = _ensure_target_ready(target)
- if err:
- return _InstallResult(False, "", err)
- constraints = _core_constraints_file()
-
- target_args: list[str] = []
- if target is not None:
- # --target tells both uv and pip to install into an arbitrary dir.
- target_args = ["--target", str(target)]
- constraint_args: list[str] = []
- if constraints is not None:
- constraint_args = ["--constraint", str(constraints)]
-
- try:
- venv_root = Path(sys.executable).parent.parent
- from tools.environments.local import hermes_subprocess_env
- uv_env = hermes_subprocess_env(inherit_credentials=False)
- uv_env["VIRTUAL_ENV"] = str(venv_root)
-
- # Tier 1: uv (preferred — fast, doesn't need pip in the venv)
- # Managed uv first: $HERMES_HOME/bin is never on PATH, so a bare
- # which() misses the uv Hermes installed and falls through to the
- # slower pip tier. Deliberately a lookup and not ensure_uv(): this runs
- # mid-turn to install an optional dependency, and downloading uv +
- # migrating the Python runtime as a side effect of that is a far bigger
- # action than the caller asked for. Tier 2 pip covers the no-uv case.
- try:
- from hermes_cli.managed_uv import resolve_uv
-
- uv_bin = resolve_uv() or shutil.which("uv")
- except Exception:
- uv_bin = shutil.which("uv")
- if uv_bin:
- try:
- r = subprocess.run(
- [uv_bin, "pip", "install", *target_args, *constraint_args, *specs],
- capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=timeout, env=uv_env,
- stdin=subprocess.DEVNULL,
- creationflags=windows_hide_flags(),
- )
- if r.returncode == 0:
- if target is not None:
- _activate_target_on_syspath(target)
- return _InstallResult(True, r.stdout or "", r.stderr or "")
- logger.debug("uv pip install failed: %s", r.stderr)
- # A resolver failure is authoritative. Falling through to pip
- # here would silently discard uv policy such as exclude-newer
- # and could install a release that the project quarantined.
- return _InstallResult(False, r.stdout or "", r.stderr or "")
- except subprocess.TimeoutExpired as e:
- logger.debug("uv invocation failed: %s", e)
- return _InstallResult(False, "", f"uv pip install timed out: {e}")
- except FileNotFoundError as e:
- # The resolved uv path disappeared between lookup and spawn.
- # In that narrow availability failure, the pip tier remains a
- # valid fallback because uv never evaluated the requirements.
- logger.debug("uv invocation failed: %s", e)
-
- # Tier 2: python -m pip (with ensurepip bootstrap if needed)
- pip_cmd = [sys.executable, "-m", "pip"]
- try:
- probe = subprocess.run(
- pip_cmd + ["--version"],
- capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=15,
- stdin=subprocess.DEVNULL,
- creationflags=windows_hide_flags(),
- )
- if probe.returncode != 0:
- raise FileNotFoundError("pip not in venv")
- except (subprocess.TimeoutExpired, FileNotFoundError):
- try:
- subprocess.run(
- [sys.executable, "-m", "ensurepip", "--upgrade", "--default-pip"],
- capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=120, check=True,
- stdin=subprocess.DEVNULL,
- creationflags=windows_hide_flags(),
- )
- except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e:
- return _InstallResult(False, "",
- f"pip not available and ensurepip failed: {e}")
-
- try:
- r = subprocess.run(
- pip_cmd + ["install", *target_args, *constraint_args, *specs],
- capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=timeout,
- stdin=subprocess.DEVNULL,
- creationflags=windows_hide_flags(),
- )
- if r.returncode == 0 and target is not None:
- _activate_target_on_syspath(target)
- return _InstallResult(r.returncode == 0, r.stdout or "", r.stderr or "")
- except subprocess.TimeoutExpired as e:
- return _InstallResult(False, "", f"pip install timed out: {e}")
- except Exception as e:
- return _InstallResult(False, "", f"pip install failed: {e}")
- finally:
- if constraints is not None:
- try:
- constraints.unlink()
- except OSError:
- pass
-
-
-# =============================================================================
-# Public API
-# =============================================================================
-
-
-def feature_specs(feature: str) -> tuple[str, ...]:
- """Return the registered specs for a feature, or raise KeyError."""
- if feature not in LAZY_DEPS:
- raise KeyError(f"Unknown lazy feature: {feature!r}")
- return LAZY_DEPS[feature]
-
-
-def feature_missing(feature: str) -> tuple[str, ...]:
- """Return the subset of specs for ``feature`` not currently installed."""
- return tuple(s for s in feature_specs(feature) if not _is_satisfied(s))
-
-
-def ensure(feature: str, *, prompt: bool = True) -> None:
- """Make sure all packages for ``feature`` are importable.
-
- If they're missing, attempts to install them in the active venv. Raises
- :class:`FeatureUnavailable` if the user has disabled lazy installs or
- if the install attempt fails.
-
- ``prompt``: when True (default) and stdin is a TTY, asks the user to
- confirm before installing. Non-interactive callers (gateway, cron,
- batch) get prompt=False and skip the confirmation — config flag is
- the gate in that case.
- """
- if feature not in LAZY_DEPS:
- raise FeatureUnavailable(
- feature, (), f"feature {feature!r} not in LAZY_DEPS allowlist"
- )
-
- missing = feature_missing(feature)
- if not missing:
- return
-
- unsupported = _unsupported_feature_reason(feature)
- if unsupported:
- raise FeatureUnavailable(feature, missing, unsupported)
-
- # Package-manager installs (NixOS, and any other distro that ships Hermes
- # from a read-only store) cannot receive lazy pip installs: the venv's
- # site-packages lives in the store, so the uv -> pip -> ensurepip ladder
- # below burns ~15s bootstrapping ensurepip only to fail on a read-only
- # target. Fail fast with an actionable message instead.
- #
- # Skipped when a durable install target is configured: the container
- # deployment sets HERMES_MANAGED=true *and* HERMES_LAZY_INSTALL_TARGET
- # (a writable volume), where lazy installs legitimately work.
- #
- # The reason string starts with "unsupported " on purpose:
- # refresh_active_features classifies FeatureUnavailable by that prefix and
- # reports anything else as a hard failure rather than a skip.
- if _lazy_install_target() is None:
- try:
- from hermes_cli.config import get_managed_system
-
- managed_by = get_managed_system()
- except Exception:
- managed_by = "" # config unreadable — proceed with the install
- if managed_by:
- raise FeatureUnavailable(
- feature, missing,
- f"unsupported on {managed_by}-managed installs: this build's "
- f"packages come from {managed_by}, so Hermes cannot install "
- f"them at runtime. Add the dependencies for {feature!r} via "
- f"{managed_by} (or run a pip/uv install of Hermes instead)."
- )
-
- # Validate every spec against the allowlist + safety regex. Belt and
- # braces — the keys-in-LAZY_DEPS check above already constrains this.
- for spec in missing:
- if not _spec_is_safe(spec):
- raise FeatureUnavailable(
- feature, missing,
- f"refusing to install unsafe spec {spec!r}"
- )
-
- if not _allow_lazy_installs():
- raise FeatureUnavailable(
- feature, missing,
- "lazy installs disabled (security.allow_lazy_installs=false)"
- )
-
- # Only show the interactive confirmation when we own a TTY and
- # prompt_toolkit isn't running. A bare input() deadlocks when a
- # prompt_toolkit app owns the terminal because keystrokes route to
- # its event loop rather than stdin, so the prompt blocks forever.
- # Under the TUI we skip the prompt and proceed — lazy installs are
- # gated by security.allow_lazy_installs, so reaching here is
- # already user opt-in.
- _pt_active = False
- if "prompt_toolkit.application.current" in sys.modules:
- try:
- from prompt_toolkit.application.current import get_app_or_none
- _app = get_app_or_none()
- _pt_active = _app is not None and getattr(_app, "is_running", False)
- except Exception:
- _pt_active = False
-
- if prompt and not _pt_active and sys.stdin.isatty() and sys.stdout.isatty():
- spec_list = ", ".join(missing)
- try:
- answer = input(
- f"\nFeature {feature!r} requires: {spec_list}\n"
- f"Install into the active venv now? [Y/n] "
- ).strip().lower()
- except (EOFError, KeyboardInterrupt):
- answer = "n"
- if answer and answer not in {"y", "yes"}:
- raise FeatureUnavailable(
- feature, missing, "user declined install at prompt"
- )
-
- logger.info("Lazy-installing %s for feature %r", " ".join(missing), feature)
- result = _venv_pip_install(missing)
- if not result.success:
- # Surface the actual pip error so the user can debug PyPI-side
- # issues (404 quarantine, network down, etc.).
- snippet = (result.stderr or result.stdout or "").strip()
- if snippet:
- # Clip to a readable size — pip can dump pages of resolution traces.
- snippet = snippet[-2000:]
- raise FeatureUnavailable(
- feature, missing,
- f"pip install failed: {snippet or 'no error output'}"
- )
-
- # Verify post-install. importlib.metadata caches per-process, so if we
- # just installed something the cache may not see it without a refresh.
- try:
- import importlib.metadata as _md
- if hasattr(_md, "_cache_clear"):
- _md._cache_clear() # type: ignore[attr-defined]
- except Exception:
- pass
-
- still_missing = feature_missing(feature)
- if still_missing:
- raise FeatureUnavailable(
- feature, still_missing,
- "install reported success but packages still not importable "
- "(may require Python restart)"
- )
-
- logger.info("Lazy install complete for feature %r", feature)
-
-
-def is_available(feature: str) -> bool:
- """Return True if the feature's deps are already satisfied."""
- if feature not in LAZY_DEPS:
- return False
- return not feature_missing(feature)
-
-
-def feature_install_command(feature: str, *, venv_pip: bool = False) -> Optional[str]:
- """Return the ``pip install`` command a user could run manually, or None.
-
- ``venv_pip=True`` targets the running interpreter's pip
- (``{sys.executable} -m pip install …``) — correct in every layout
- (default install, ``HERMES_HOME`` overrides, profile installs) and
- immune to Ubuntu 24.04's PEP 668 ``externally-managed-environment``
- failure that a bare/system ``pip install`` hint invites. The default
- ``uv pip install`` form is kept for contexts that document uv usage.
- """
- if feature not in LAZY_DEPS:
- return None
- specs = LAZY_DEPS[feature]
- joined = " ".join(repr(s) for s in specs)
- if venv_pip:
- return f"{sys.executable} -m pip install {joined}"
- return "uv pip install " + joined
-
-
-@dataclass
-class InstallSpecsResult:
- """Outcome of :func:`install_specs` for one batch of pip specs.
-
- ``ok`` — install succeeded (or nothing was missing).
- ``blocked`` — installs are gated off (config kill switch, sealed venv
- without a durable target) or a spec failed validation;
- nothing was executed. ``reason`` explains why.
- ``command`` — human-readable description of what ran (for UIs/logs).
- """
- ok: bool
- blocked: bool = False
- reason: str = ""
- command: str = ""
- stdout: str = ""
- stderr: str = ""
-
-
-def install_specs(specs: list[str] | tuple[str, ...], *, timeout: int = 300) -> InstallSpecsResult:
- """Install arbitrary (validated) pip specs through the lazy-install pipeline.
-
- This is the environment-aware install path for callers whose package
- lists come from data (e.g. memory-provider plugin manifests declaring
- ``pip_dependencies``) rather than the static :data:`LAZY_DEPS` allowlist.
- It applies the exact same environment routing as :func:`ensure`:
-
- * **Venv-scoped by default** — installs into ``sys.executable``'s venv.
- * **Durable-target on immutable images** — when the deployment seals the
- agent venv (``HERMES_DISABLE_LAZY_INSTALLS=1``) and sets
- ``HERMES_LAZY_INSTALL_TARGET``, installs are redirected to the writable
- data-volume dir (``--target`` + core-venv constraints), then activated
- on ``sys.path`` so the packages import in this process immediately.
- * **Gated** — honors ``security.allow_lazy_installs`` and refuses to run
- when the venv is sealed with no durable target (never attempts a write
- to a read-only tree; reports *why* instead of surfacing EROFS/EACCES).
-
- Every spec must pass :func:`_spec_is_safe` (no URLs, paths, or shell
- metacharacters). Unlike :func:`ensure`, unknown packages are permitted —
- the caller owns manifest trust; this function owns spec hygiene and
- environment routing.
-
- Never raises; inspect the returned :class:`InstallSpecsResult`.
- """
- cleaned = tuple(str(s).strip() for s in specs if str(s).strip())
- if not cleaned:
- return InstallSpecsResult(ok=True, command="")
-
- for spec in cleaned:
- if not _spec_is_safe(spec):
- return InstallSpecsResult(
- ok=False, blocked=True,
- reason=f"refusing to install unsafe spec {spec!r}",
- )
-
- if not _allow_lazy_installs():
- target = _lazy_install_target()
- if os.environ.get("HERMES_DISABLE_LAZY_INSTALLS") == "1" and target is None:
- reason = (
- "runtime installs are disabled on this deployment: the agent "
- "environment is immutable and no writable install target is "
- "configured (HERMES_LAZY_INSTALL_TARGET)"
- )
- else:
- reason = "runtime installs disabled (security.allow_lazy_installs=false)"
- return InstallSpecsResult(ok=False, blocked=True, reason=reason)
-
- target = _lazy_install_target()
- display = "uv pip install " + (
- f"--target {target} " if target is not None else ""
- ) + " ".join(cleaned)
-
- logger.info("Installing pip specs %s (target=%s)", " ".join(cleaned), target or "venv")
- try:
- result = _venv_pip_install(cleaned, timeout=timeout)
- except Exception as exc:
- logger.warning("install_specs failed unexpectedly: %s", exc)
- return InstallSpecsResult(
- ok=False, command=display, stderr=f"install failed: {exc}"
- )
-
- # Freshly-installed dists must be visible to importers and metadata
- # checks in this same process (dashboard rechecks availability inline).
- try:
- import importlib
- importlib.invalidate_caches()
- import importlib.metadata as _md
- if hasattr(_md, "_cache_clear"):
- _md._cache_clear() # type: ignore[attr-defined]
- except Exception:
- pass
-
- return InstallSpecsResult(
- ok=result.success,
- command=display,
- stdout=result.stdout,
- stderr=result.stderr,
- )
-
-
-def active_features() -> list[str]:
- """Return the list of features the user has ever lazy-installed.
-
- A feature counts as "active" if its anchor package (the first declared
- spec) is currently installed in the venv (presence check, ignoring
- version). We intentionally do NOT treat shared helper packages as proof
- that a backend was enabled: for example ``platform.matrix`` depends on
- generic packages like ``asyncpg``/``aiosqlite`` that can be installed for
- unrelated reasons, while the actual Matrix adapter anchor is ``mautrix``.
- Features the user has never enabled stay quiet.
-
- Used by ``hermes update`` to figure out which lazy backends need a
- refresh pass when pins move in :data:`LAZY_DEPS`.
- """
- active = []
- for feature, specs in LAZY_DEPS.items():
- if specs and _is_present(specs[0]):
- active.append(feature)
- return active
-
-
-def refresh_active_features(*, prompt: bool = False) -> dict[str, str]:
- """Re-run ``ensure`` for every feature the user has previously activated.
-
- Returns a ``{feature: status}`` map where status is one of:
- ``"current"`` — pins already satisfied, no install run
- ``"refreshed"`` — pins were stale, reinstall succeeded
- ``"failed: <reason>"`` — install attempt failed; caller decides
- whether to surface it (we don't raise)
- ``"skipped: <reason>"`` — gated off (config flag, user decline)
-
- Intended for ``hermes update``. Never raises; lazy-install failures
- here must not block the rest of the update flow.
- """
- return _refresh_features(active_features(), prompt=prompt, restoring=False)
-
-
-def restore_features(features: list[str]) -> dict[str, str]:
- """Restore features captured before an explicit managed-runtime rebuild.
-
- Feature names are checked against :data:`LAZY_DEPS`, and installs remain
- subject to ``security.allow_lazy_installs``. An explicit opt-out therefore
- leaves the captured feature absent and reports it as skipped.
- """
- return _refresh_features(features, prompt=False, restoring=True)
-
-
-def _refresh_features(
- features: list[str], *, prompt: bool, restoring: bool
-) -> dict[str, str]:
- """Refresh or restore a known set of allowlisted lazy features."""
- results: dict[str, str] = {}
- for feature in features:
- if feature not in LAZY_DEPS:
- continue
- missing = feature_missing(feature)
- if not missing:
- results[feature] = "current"
- continue
-
- unsupported = _unsupported_feature_reason(feature)
- if unsupported:
- results[feature] = f"skipped: {unsupported}"
- continue
-
- try:
- if restoring:
- ensure(feature, prompt=False)
- results[feature] = "restored"
- else:
- ensure(feature, prompt=prompt)
- results[feature] = "refreshed"
- except FeatureUnavailable as e:
- # Distinguish "user opted out" or platform-incompatible features
- # from install failures so the update command can render the
- # right non-error message.
- if (
- "lazy installs disabled" in str(e)
- or "declined" in str(e)
- or e.reason.startswith("unsupported ")
- ):
- results[feature] = f"skipped: {e.reason}"
- else:
- results[feature] = f"failed: {e.reason}"
- except Exception as e:
- results[feature] = f"failed: {e}"
- return results
-
-
-def ensure_and_bind(
- feature: str,
- importer: Callable[[], dict[str, Any]],
- target_globals: dict,
- *,
- prompt: bool = False,
-) -> bool:
- """Ensure a feature is installed, then rebind names into the caller's globals.
-
- Combines :func:`ensure` with a post-install import step that rebinds
- module-level names. This eliminates the error-prone pattern of manually
- listing every global that needs updating after lazy-install.
-
- ``importer`` is a zero-arg callable that returns a dict of
- ``{name: value}`` for all symbols the caller needs rebound. It is called
- only after :func:`ensure` succeeds (or if the packages are already
- installed).
-
- Returns True on success, False if deps couldn't be installed or imported.
-
- Example usage in a platform adapter::
-
- def check_slack_requirements() -> bool:
- if SLACK_AVAILABLE:
- return True
- def _import():
- from slack_bolt.async_app import AsyncApp
- from slack_bolt.adapter.socket_mode.async_handler import AsyncSocketModeHandler
- from slack_sdk.web.async_client import AsyncWebClient
- import aiohttp
- return {
- "AsyncApp": AsyncApp,
- "AsyncSocketModeHandler": AsyncSocketModeHandler,
- "AsyncWebClient": AsyncWebClient,
- "aiohttp": aiohttp,
- "SLACK_AVAILABLE": True,
- }
- return ensure_and_bind("platform.slack", _import, globals(), prompt=False)
- """
- try:
- ensure(feature, prompt=prompt)
- except FeatureUnavailable as exc:
- logger.warning("%s", exc)
- return False
- except Exception as exc:
- logger.warning("Failed to ensure feature %r: %s", feature, exc)
- return False
-
- try:
- bindings = importer()
- except ImportError as exc:
- logger.warning(
- "Failed to import feature %r after install: %s", feature, exc
- )
- return False
-
- target_globals.update(bindings)
- return True
diff --git a/tools/voice_mode.py b/tools/voice_mode.py
index 80652bdb0fc..62d2fa4aa9a 100644
--- a/tools/voice_mode.py
+++ b/tools/voice_mode.py
@@ -118,12 +118,7 @@ def _default_input_samplerate(sd) -> int:
return SAMPLE_RATE
-from hermes_constants import is_termux as _is_termux_environment
-
-
def _voice_capture_install_hint() -> str:
- if _is_termux_environment():
- return "pkg install python-numpy portaudio && python -m pip install sounddevice"
# If we're running inside a venv (e.g. the bundled Hermes venv at
# ~/.hermes/profiles/<name>/hermes-agent/venv/), `pip install` on the
# user's PATH won't reach the right site-packages — the bare hint sends
@@ -140,87 +135,6 @@ def _voice_capture_install_hint() -> str:
return "pip install sounddevice numpy"
-def _termux_microphone_command() -> Optional[str]:
- if not _is_termux_environment():
- return None
- return shutil.which("termux-microphone-record")
-
-
-
-# Probes used to detect whether the Termux:API Android app is installed.
-# `pm list packages` is the canonical Android lookup but is unreliable on
-# some devices: on certain ROMs / Android API levels `pm` itself isn't on
-# Termux's PATH while `cmd package` is, on others `pm` returns nothing for
-# the calling user even when the app is present. We try both before
-# concluding that the app is genuinely missing (issue #31015).
-_TERMUX_API_PACKAGE_PROBES = (
- ("pm", "list", "packages", "com.termux.api"),
- ("cmd", "package", "list", "packages", "com.termux.api"),
-)
-
-
-def _termux_api_app_installed() -> bool:
- """Return True iff the Termux:API Android app is installed.
-
- Strategy (issue #31015):
-
- 1. Try each probe in ``_TERMUX_API_PACKAGE_PROBES`` and look for
- ``package:com.termux.api`` in stdout. Any positive hit is
- authoritative — return True.
- 2. If every probe is *inconclusive* (binary missing, permission
- denied, timeout, non-zero exit) we cannot honestly say the app
- is missing; fall back to trusting the ``termux-microphone-record``
- binary on PATH. The binary ships with the ``termux-api`` package
- and is only useful when the Android app is installed; users who
- installed the package deliberately almost always have the app
- too. A false negative on this gate blocks ``/voice on``
- outright (the symptom reported in #31015), while a false
- positive only surfaces a precise runtime error from the binary
- itself — strictly more actionable.
- 3. If at least one probe ran cleanly and definitively did not
- mention the package, treat the app as missing and return False
- — that's the genuine "Termux:API CLI installed without the app"
- case the existing warning was written for.
- """
- if not _is_termux_environment():
- return False
-
- inconclusive = False
- for cmd in _TERMUX_API_PACKAGE_PROBES:
- try:
- result = subprocess.run(
- list(cmd),
- capture_output=True,
- text=True, encoding='utf-8', errors='replace',
- timeout=5,
- check=False,
- stdin=subprocess.DEVNULL,
- )
- except (FileNotFoundError, PermissionError, OSError):
- inconclusive = True
- continue
- except subprocess.TimeoutExpired:
- inconclusive = True
- continue
- if result.returncode != 0:
- inconclusive = True
- continue
- if "package:com.termux.api" in (result.stdout or "").lower():
- return True
-
- if inconclusive and shutil.which("termux-microphone-record") is not None:
- logger.debug(
- "Termux package-manager probes inconclusive; trusting "
- "termux-microphone-record binary on PATH (issue #31015)."
- )
- return True
- return False
-
-
-def _termux_voice_capture_available() -> bool:
- return _termux_microphone_command() is not None and _termux_api_app_installed()
-
-
def _pulse_socket_reachable() -> bool:
"""Return True if a PulseAudio/PipeWire socket is reachable on disk.
@@ -283,9 +197,6 @@ def detect_audio_environment() -> dict:
"""
warnings = [] # hard-fail: these block voice mode
notices = [] # informational: logged but don't block
- termux_mic_cmd = _termux_microphone_command()
- termux_app_installed = _termux_api_app_installed()
- termux_capture = bool(termux_mic_cmd and termux_app_installed)
has_forwarded_audio = bool(
os.environ.get('PULSE_SERVER')
or os.environ.get('PIPEWIRE_REMOTE')
@@ -336,7 +247,7 @@ def detect_audio_environment() -> dict:
# downgrade to a notice (keeps the same recording guidance visible,
# but doesn't block /voice on for TTS-only usage).
try:
- with open('/proc/version', 'r', encoding="utf-8") as f:
+ with open('/proc/version', 'r', encoding="utf-8") as f: # windows-footgun: ok (/proc is BOM-free)
if 'microsoft' in f.read().lower():
if has_forwarded_audio:
notices.append("Running in WSL with a reachable PulseAudio/PipeWire sound server")
@@ -369,8 +280,6 @@ def detect_audio_environment() -> dict:
notices.append(
"No PortAudio devices detected but host audio forwarding is configured -- continuing"
)
- elif termux_capture:
- notices.append("No PortAudio devices detected, but Termux:API microphone capture is available")
else:
warnings.append("No audio input/output devices detected")
except Exception:
@@ -381,39 +290,17 @@ def detect_audio_environment() -> dict:
notices.append(
"Audio device query failed but host audio forwarding is configured -- continuing"
)
- elif termux_capture:
- notices.append("PortAudio device query failed, but Termux:API microphone capture is available")
else:
warnings.append("Audio subsystem error (PortAudio cannot query devices)")
except ImportError:
- if termux_capture:
- notices.append("Termux:API microphone recording available (sounddevice not required)")
- elif termux_mic_cmd and not termux_app_installed:
- warnings.append(
- "Termux:API Android app is not installed. Install/update the Termux:API app to use termux-microphone-record."
- )
- else:
- warnings.append(f"Audio libraries not installed ({_voice_capture_install_hint()})")
+ warnings.append(f"Audio libraries not installed ({_voice_capture_install_hint()})")
except OSError:
- if termux_capture:
- notices.append("Termux:API microphone recording available (PortAudio not required)")
- elif termux_mic_cmd and not termux_app_installed:
- warnings.append(
- "Termux:API Android app is not installed. Install/update the Termux:API app to use termux-microphone-record."
- )
- elif _is_termux_environment():
- warnings.append(
- "PortAudio system library not found -- install it first:\n"
- " Termux: pkg install portaudio\n"
- "Then retry /voice on."
- )
- else:
- warnings.append(
- "PortAudio system library not found -- install it first:\n"
- " Linux: sudo apt-get install libportaudio2\n"
- " macOS: brew install portaudio\n"
- "Then retry /voice on."
- )
+ warnings.append(
+ "PortAudio system library not found -- install it first:\n"
+ " Linux: sudo apt-get install libportaudio2\n"
+ " macOS: brew install portaudio\n"
+ "Then retry /voice on."
+ )
return {
"available": not warnings,
@@ -678,134 +565,6 @@ def stop_thinking_sound() -> None:
stop.set()
-# ============================================================================
-# Termux Audio Recorder
-# ============================================================================
-class TermuxAudioRecorder:
- """Recorder backend that uses Termux:API microphone capture commands."""
-
- supports_silence_autostop = False
-
- def __init__(self) -> None:
- self._lock = threading.Lock()
- self._recording = False
- self._start_time = 0.0
- self._recording_path: Optional[str] = None
- self._current_rms = 0
-
- @property
- def is_recording(self) -> bool:
- return self._recording
-
- @property
- def elapsed_seconds(self) -> float:
- if not self._recording:
- return 0.0
- return time.monotonic() - self._start_time
-
- @property
- def current_rms(self) -> int:
- return self._current_rms
-
- def start(self, on_silence_stop=None) -> None:
- del on_silence_stop # Termux:API does not expose live silence callbacks.
- mic_cmd = _termux_microphone_command()
- if not mic_cmd:
- raise RuntimeError(
- "Termux voice capture requires the termux-api package and app.\n"
- "Install with: pkg install termux-api\n"
- "Then install/update the Termux:API Android app."
- )
- if not _termux_api_app_installed():
- raise RuntimeError(
- "Termux voice capture requires the Termux:API Android app.\n"
- "Install/update the Termux:API app, then retry /voice on."
- )
-
- with self._lock:
- if self._recording:
- return
- os.makedirs(_TEMP_DIR, exist_ok=True)
- timestamp = time.strftime("%Y%m%d_%H%M%S")
- self._recording_path = os.path.join(_TEMP_DIR, f"recording_{timestamp}.aac")
-
- command = [
- mic_cmd,
- "-f", self._recording_path,
- "-l", "0",
- "-e", "aac",
- "-r", str(SAMPLE_RATE),
- "-c", str(CHANNELS),
- ]
- try:
- subprocess.run(command, capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=15, check=True, stdin=subprocess.DEVNULL)
- except subprocess.CalledProcessError as e:
- details = (e.stderr or e.stdout or str(e)).strip()
- raise RuntimeError(f"Termux microphone start failed: {details}") from e
- except Exception as e:
- raise RuntimeError(f"Termux microphone start failed: {e}") from e
-
- with self._lock:
- self._start_time = time.monotonic()
- self._recording = True
- self._current_rms = 0
- logger.info("Termux voice recording started")
-
- def _stop_termux_recording(self) -> None:
- mic_cmd = _termux_microphone_command()
- if not mic_cmd:
- return
- subprocess.run([mic_cmd, "-q"], capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=15, check=False, stdin=subprocess.DEVNULL)
-
- def stop(self) -> Optional[str]:
- with self._lock:
- if not self._recording:
- return None
- self._recording = False
- path = self._recording_path
- self._recording_path = None
- started_at = self._start_time
- self._current_rms = 0
-
- self._stop_termux_recording()
- if not path or not os.path.isfile(path):
- return None
- if time.monotonic() - started_at < 0.3:
- try:
- os.unlink(path)
- except OSError:
- pass
- return None
- if os.path.getsize(path) <= 0:
- try:
- os.unlink(path)
- except OSError:
- pass
- return None
- logger.info("Termux voice recording stopped: %s", path)
- return path
-
- def cancel(self) -> None:
- with self._lock:
- path = self._recording_path
- self._recording = False
- self._recording_path = None
- self._current_rms = 0
- try:
- self._stop_termux_recording()
- except Exception:
- pass
- if path and os.path.isfile(path):
- try:
- os.unlink(path)
- except OSError:
- pass
- logger.info("Termux voice recording cancelled")
-
- def shutdown(self) -> None:
- self.cancel()
-
-
# ============================================================================
# AudioRecorder
# ============================================================================
@@ -1045,13 +804,10 @@ class AudioRecorder:
# sounddevice imports but PortAudio's shared library is missing —
# a pip install can't fix that; point at the system package
# instead of misreporting missing Python packages (#18432).
- if _is_termux_environment():
- portaudio_hint = " Termux: pkg install portaudio"
- else:
- portaudio_hint = (
- " Linux: sudo apt-get install libportaudio2\n"
- " macOS: brew install portaudio"
- )
+ portaudio_hint = (
+ " Linux: sudo apt-get install libportaudio2\n"
+ " macOS: brew install portaudio"
+ )
raise RuntimeError(
"PortAudio system library not found -- install it first:\n"
f"{portaudio_hint}\n"
@@ -1198,10 +954,8 @@ class AudioRecorder:
return wav_path
-def create_audio_recorder() -> AudioRecorder | TermuxAudioRecorder:
+def create_audio_recorder() -> AudioRecorder:
"""Return the best recorder backend for the current environment."""
- if _termux_voice_capture_available():
- return TermuxAudioRecorder()
return AudioRecorder()
@@ -1584,7 +1338,7 @@ def stop_playback() -> None:
def _is_wsl() -> bool:
"""True when running inside Windows Subsystem for Linux."""
try:
- with open("/proc/version", "r", encoding="utf-8", errors="replace") as f:
+ with open("/proc/version", "r", encoding="utf-8", errors="replace") as f: # windows-footgun: ok (/proc is BOM-free)
return "microsoft" in f.read().lower()
except Exception:
return False
@@ -1599,7 +1353,7 @@ def _is_wsl2_env() -> bool:
without fighting builtins.open patching complexity.
"""
try:
- with open("/proc/version", encoding="utf-8", errors="replace") as _fv:
+ with open("/proc/version", encoding="utf-8", errors="replace") as _fv: # windows-footgun: ok (/proc is BOM-free)
return "microsoft" in _fv.read().lower()
except OSError:
return False
@@ -2285,8 +2039,7 @@ def check_voice_requirements() -> Dict[str, Any]:
)
missing: List[str] = []
- termux_capture = _termux_voice_capture_available()
- has_audio = _audio_available() or termux_capture
+ has_audio = _audio_available()
if not has_audio:
missing.extend(["sounddevice", "numpy"])
@@ -2297,9 +2050,7 @@ def check_voice_requirements() -> Dict[str, Any]:
available = has_audio and stt_available and env_check["available"]
details_parts = []
- if termux_capture:
- details_parts.append("Audio capture: OK (Termux:API microphone)")
- elif has_audio:
+ if has_audio:
details_parts.append("Audio capture: OK")
else:
details_parts.append(f"Audio capture: MISSING ({_voice_capture_install_hint()})")
diff --git a/ui-tui/src/__tests__/virtualHistoryOffsetCache.test.ts b/ui-tui/src/__tests__/virtualHistoryOffsetCache.test.ts
index e5bed9d966f..1ad3a971d94 100644
--- a/ui-tui/src/__tests__/virtualHistoryOffsetCache.test.ts
+++ b/ui-tui/src/__tests__/virtualHistoryOffsetCache.test.ts
@@ -528,18 +528,21 @@ describe('useVirtualHistory offset cache reuse', () => {
})
try {
- await delay(20)
+ // Generous settle windows: the unmount-measurement callback must fire
+ // before the assertion, and under CI load a 20-40ms sleep is not
+ // enough (flaked as "adjustScrollTop called 0 times").
+ await delay(50)
const scroll = expose.current!.scroll!
scroll.scrollTo(0)
- await delay(20)
+ await delay(50)
scroll.scrollTo(5)
const adjustScrollTop = vi.spyOn(scroll, 'adjustScrollTop')
const staleHeights = new Map(initialHeights)
staleHeights.set(items[0]!.key, 1)
instance.rerender(React.createElement(Harness, { expose, initialHeights: staleHeights, items }))
- await delay(40)
+ await delay(400)
expect(adjustScrollTop).toHaveBeenCalledOnce()
expect(adjustScrollTop).toHaveBeenCalledWith(1)