Skip to content

The agent that grows with you

fix(runtime): restore startup imports and isolate updater tests

ethernet9d7921cd6e56
diff --git a/hermes_cli/banner.py b/hermes_cli/banner.py
index 64f633d0382..78560590529 100644
--- a/hermes_cli/banner.py
+++ b/hermes_cli/banner.py
@@ -405,8 +405,8 @@ def get_git_banner_state(repo_dir: Optional[Path] = None) -> Optional[dict]:
def _baked_banner_state() -> Optional[dict]:
"""Banner state from the baked build SHA (Docker image path), or None."""
def _baked():
- from hermes_cli.build_info import get_build_sha
- return get_build_sha(short=8)
+ from hermes_cli.version_info import get_code_identity
+ return get_code_identity().get("short_sha")
baked = _quiet(_baked)
return {"upstream": baked, "local": baked, "ahead": 0} if baked else None
diff --git a/hermes_cli/dump.py b/hermes_cli/dump.py
index e6233fa2046..82121e32913 100644
--- a/hermes_cli/dump.py
+++ b/hermes_cli/dump.py
@@ -57,8 +57,8 @@ def _get_git_commit(project_root: Path) -> str:
if value:
return value
try:
- from hermes_cli.build_info import get_build_sha # deferred: keeps dump cheap on non-dump paths
- return get_build_sha(short=8) or "(unknown)"
+ from hermes_cli.version_info import get_code_identity
+ return get_code_identity().get("short_sha") or "(unknown)"
except Exception:
return "(unknown)"
diff --git a/hermes_cli/main.py b/hermes_cli/main.py
index 016d7cd8ce5..70a2356ef41 100644
--- a/hermes_cli/main.py
+++ b/hermes_cli/main.py
@@ -2184,7 +2184,10 @@ def _finalize_update_receipt(code: int, reason: str) -> None:
def _update_preflight_handled(args) -> bool:
"""Managed-install refusal, --plan, admission gate, --check. True = nothing more to do."""
from hermes_cli.config import is_managed, managed_error
+ from hermes_cli.update_channel import handle_metadata_args
+ if handle_metadata_args(args, PROJECT_ROOT):
+ sys.exit(0)
if is_managed():
managed_error("update Hermes Agent")
return True
diff --git a/hermes_cli/update_channel.py b/hermes_cli/update_channel.py
index 7167904d65a..afb82253877 100644
--- a/hermes_cli/update_channel.py
+++ b/hermes_cli/update_channel.py
@@ -229,6 +229,33 @@ def set_install_channel(
return sha16
+def handle_metadata_args(args, project_root: Path) -> bool:
+ """Handle metadata-only update commands before any update side effect."""
+ if getattr(args, "install_id", False):
+ print(install_id(project_root))
+ return True
+ channel = getattr(args, "set_channel", None)
+ if channel is None:
+ return False
+ try:
+ key = set_install_channel(channel, project_root)
+ except ValueError as exc:
+ print(str(exc))
+ raise SystemExit(2) from exc
+ print(f"Update channel for {key}: {channel}")
+ if channel == CHANNEL_CANARY:
+ print("Canary builds can write forward-incompatible state. Back up your data before switching.")
+ elif channel == CHANNEL_STABLE:
+ from hermes_cli.steward import read_install_stamp
+
+ current = read_install_stamp(project_root).get("displayVersion", "")
+ if "-canary." in current:
+ stable = current.partition("-canary.")[0]
+ print(f"You are on {current}. Wait for v{stable} or a newer stable release.")
+ print("For a manual reinstall, see https://hermes-agent.nousresearch.com.")
+ return True
+
+
def _write_channel_record(sha16: str, path: str, channel: str) -> None:
"""Write ``update.installs.<sha16>`` into config.yaml, preserving the rest."""
import yaml
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py
index 579cc8e2697..567a1d2cbfb 100644
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@ -4367,7 +4367,7 @@ def _update_node_dependencies() -> list[str]:
# cache (~0.4s once warm) — print first so that doesn't look like a hang.
print("→ Warming npx cache for agent-browser...")
try:
- from tools.browser_tool import warm_agent_browser_npx_cache
+ from tools.browser_tool_install import warm_agent_browser_npx_cache
warm_agent_browser_npx_cache()
except Exception:
pass
diff --git a/hermes_cli/update_cmd_fleet.py b/hermes_cli/update_cmd_fleet.py
index f81bf0b4d8c..e42e3c71cbe 100644
--- a/hermes_cli/update_cmd_fleet.py
+++ b/hermes_cli/update_cmd_fleet.py
@@ -70,7 +70,7 @@ def _current_checkout_sha() -> str | None:
"""Current on-disk checkout HEAD, or None if it cannot be resolved."""
from hermes_cli.update_cmd import _capture_head_sha, _m
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:
diff --git a/hermes_cli/update_inventory.py b/hermes_cli/update_inventory.py
index 912d66dcc3c..d20eaaa6c84 100644
--- a/hermes_cli/update_inventory.py
+++ b/hermes_cli/update_inventory.py
@@ -237,7 +237,7 @@ def collect_runtime_inventory() -> UpdatePlan:
plan = UpdatePlan()
_collect_install_shape(plan)
with _probe("Code-identity probe"):
- 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 da1ad20afa5..c4a93a6fd23 100644
--- a/hermes_cli/update_receipt.py
+++ b/hermes_cli/update_receipt.py
@@ -54,7 +54,7 @@ def _utc_now_iso() -> str:
def _code_identity(refresh: bool = False) -> dict[str, Any]:
"""Running-code identity, or ``{}`` when the probe fails."""
with suppress(Exception):
- from hermes_cli.build_info import get_code_identity
+ from hermes_cli.version_info import get_code_identity
return get_code_identity(refresh=refresh) or {}
return {}
diff --git a/tests/hermes_cli/test_cmd_update.py b/tests/hermes_cli/test_cmd_update.py
index c2297447525..2a29467de42 100644
--- a/tests/hermes_cli/test_cmd_update.py
+++ b/tests/hermes_cli/test_cmd_update.py
@@ -1,5 +1,6 @@
"""Tests for cmd_update — branch fallback when remote branch doesn't exist."""
+import contextlib
import hashlib
import os
import subprocess
@@ -49,6 +50,42 @@ def _make_run_side_effect(branch="main", verify_ok=True, commit_count="0"):
return side_effect
+class _NoSpawnProcess:
+ """Stand-in for a spawned child: context manager, empty stderr tee, exit 0.
+
+ Used by the autouse machine-boundary fixture so no real process can ever
+ launch from the end-to-end cmd_update tests (the npm install path streams
+ via subprocess.Popen, which per-test `subprocess.run` patches miss).
+ """
+
+ def __init__(self, cmd, **kwargs):
+ self.cmd = cmd
+ self.stdout = iter(())
+ self.stderr = iter(())
+ self.returncode = 0
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc_info):
+ return False
+
+ def wait(self, timeout=None):
+ return self.returncode
+
+ def communicate(self, timeout=None):
+ return ("", "")
+
+ def terminate(self):
+ return None
+
+ kill = terminate
+
+
+def _no_spawn_popen(cmd, *args, **kwargs):
+ return _NoSpawnProcess(cmd, **kwargs)
+
+
@pytest.fixture
def mock_args():
return SimpleNamespace()
@@ -80,29 +117,62 @@ def _patch_gateway_discovery():
Discovery returning nothing makes the phase a clean no-op for every test
in this module (none of them assert on gateway restarts).
"""
- 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.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"):
+ # ExitStack rather than one parenthesized `with`: the patch list exceeds
+ # CPython's 20 statically-nested-block limit.
+ _patches = [
+ 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.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"),
+ # ── Machine boundary: the update pipeline must not touch this host ──
+ # The npx warm-up spawns a real npx (network + node resolution) — stub
+ # it at its defining module (same seam the dedicated warm-up test
+ # asserts against).
+ patch("tools.browser_tool_install.warm_agent_browser_npx_cache", return_value=False),
+ # Post-pull steps walk and mutate the REAL checkout (delete stale
+ # __pycache__ dirs, rewrite the bytecode fingerprint, regenerate the
+ # bootstrap cache scripts). None of this module's assertions cover
+ # them; keep them off the working tree.
+ patch("hermes_cli.main._clear_bytecode_cache", return_value=0),
+ patch("hermes_cli.main._record_bytecode_fingerprint"),
+ patch("hermes_cli.main._refresh_bootstrap_cache_scripts"),
+ # Same for the web/desktop rebuild phases: they resolve the real
+ # machine's npm and run real `npm run build` / electron-builder against
+ # PROJECT_ROOT. Stub at the hm facade, exactly as the Windows
+ # ZIP-fallback test in this file already does.
+ patch("hermes_cli.main._build_web_ui", return_value=True),
+ patch("hermes_cli.main._desktop_build_needed", return_value=False),
+ # _update_node_dependencies' npm install streams via subprocess.Popen
+ # (capture_output=False), which the per-test `subprocess.run` patches
+ # do not cover — on Windows the real machine's bundled npm.cmd is
+ # resolved (hermes_constants.find_node_executable managed-tree scan)
+ # and CreateProcess on it raises PermissionError [WinError 5]. Stub
+ # Popen so no real process can ever launch from these end-to-end
+ # tests; dedicated npm-flow tests patch Popen themselves.
+ patch("subprocess.Popen", side_effect=_no_spawn_popen),
+ ]
+ with contextlib.ExitStack() as stack:
+ for cm in _patches:
+ stack.enter_context(cm)
yield
@@ -1415,9 +1485,16 @@ class TestUpdateNodeDependencies:
def test_returns_silently_when_npm_not_found(self, _which, mock_run, tmp_path, monkeypatch):
"""No npm on PATH → return without calling subprocess."""
from hermes_cli import main as hm
+ import hermes_constants
(tmp_path / "package.json").write_text("{}")
monkeypatch.setattr(hm, "PROJECT_ROOT", tmp_path)
+ # Production resolves npm via hermes_constants.find_node_executable
+ # (managed-tree scan first, then a PATH walk that on Windows never
+ # calls shutil.which), so patching shutil.which alone cannot make the
+ # resolver return None — it would find the real machine's bundled npm
+ # and spawn it. Patch the defining resolver seam.
+ monkeypatch.setattr(hermes_constants, "find_node_executable", lambda _name: None)
update_cmd._update_node_dependencies()
diff --git a/tests/hermes_cli/test_update_channel.py b/tests/hermes_cli/test_update_channel.py
index fce5696a85b..6f8ef135d16 100644
--- a/tests/hermes_cli/test_update_channel.py
+++ b/tests/hermes_cli/test_update_channel.py
@@ -228,6 +228,16 @@ class TestSetChannelCLI:
base.update(kw)
return SimpleNamespace(**base)
+ @pytest.fixture(autouse=True)
+ def _no_real_updater(self, monkeypatch, tmp_path):
+ """Metadata commands must not enter the code-update pipeline."""
+ from hermes_cli import main, update_cmd
+
+ monkeypatch.setattr(main, "PROJECT_ROOT", tmp_path)
+ def unexpected_update(*args, **kwargs):
+ pytest.fail("metadata command entered the real updater")
+ monkeypatch.setattr(update_cmd, "_cmd_update_impl", unexpected_update)
+
def test_stable_switch_from_canary_is_an_honest_wait(self, capsys):
from unittest.mock import patch
diff --git a/tools/environments/base.py b/tools/environments/base.py
index bee8567926d..c4ae12d1f7b 100644
--- a/tools/environments/base.py
+++ b/tools/environments/base.py
@@ -10,13 +10,18 @@ or a temp file (local). Cohesive pieces live in sibling modules (``base_output``
import json
import logging
import os
+import re
import shlex
+import subprocess
import threading
import time
import uuid
+import codecs
+import select
from abc import ABC, abstractmethod
+from collections import deque
from pathlib import Path
-from typing import Callable, Iterable
+from typing import Callable, IO, Iterable, Protocol
from hermes_constants import get_hermes_home
from tools.interrupt import is_interrupted, is_thread_interrupted
diff --git a/ui-tui/src/__tests__/terminalParity.test.ts b/ui-tui/src/__tests__/terminalParity.test.ts
index d1f36f49d97..b2933733e76 100644
--- a/ui-tui/src/__tests__/terminalParity.test.ts
+++ b/ui-tui/src/__tests__/terminalParity.test.ts
@@ -19,7 +19,8 @@ describe('terminalParityHints', () => {
const hints = await terminalParityHints({ TERM_PROGRAM: 'vscode' } as NodeJS.ProcessEnv, {
fileOps: { readFile },
- homeDir: '/tmp/fake-home'
+ homeDir: '/tmp/fake-home',
+ platform: 'darwin'
})
expect(hints.some(h => h.key === 'ide-setup')).toBe(true)
@@ -69,7 +70,8 @@ describe('terminalParityHints', () => {
const hints = await terminalParityHints({ TERM_PROGRAM: 'vscode' } as NodeJS.ProcessEnv, {
fileOps: { readFile },
- homeDir: '/tmp/fake-home'
+ homeDir: '/tmp/fake-home',
+ platform: 'darwin'
})
expect(hints.some(h => h.key === 'ide-setup')).toBe(false)
@@ -119,7 +121,8 @@ describe('terminalParityHints', () => {
const hints = await terminalParityHints({ TERM_PROGRAM: 'vscode' } as NodeJS.ProcessEnv, {
fileOps: { readFile },
- homeDir: '/tmp/fake-home'
+ homeDir: '/tmp/fake-home',
+ platform: 'darwin'
})
// Legacy bindings don't match current CSI u targets, so setup is still needed
diff --git a/ui-tui/src/__tests__/terminalSetup.test.ts b/ui-tui/src/__tests__/terminalSetup.test.ts
index 84e5a553dc2..f2f0907f439 100644
--- a/ui-tui/src/__tests__/terminalSetup.test.ts
+++ b/ui-tui/src/__tests__/terminalSetup.test.ts
@@ -1,3 +1,5 @@
+import { join } from 'node:path'
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
@@ -31,11 +33,14 @@ describe('terminalSetup helpers', () => {
})
it('computes VS Code style config dirs cross-platform', () => {
+ // Expected paths are built with the same join() the helper uses, so the
+ // assertion checks platform-specific layout logic (which root, APPDATA vs
+ // home) rather than freezing host separators.
expect(getVSCodeStyleConfigDir('Code', 'darwin', {} as NodeJS.ProcessEnv, '/home/me')).toBe(
- '/home/me/Library/Application Support/Code/User'
+ join('/home/me', 'Library', 'Application Support', 'Code', 'User')
)
expect(getVSCodeStyleConfigDir('Code', 'linux', {} as NodeJS.ProcessEnv, '/home/me')).toBe(
- '/home/me/.config/Code/User'
+ join('/home/me', '.config', 'Code', 'User')
)
expect(
getVSCodeStyleConfigDir(
@@ -44,7 +49,7 @@ describe('terminalSetup helpers', () => {
{ APPDATA: 'C:/Users/me/AppData/Roaming' } as NodeJS.ProcessEnv,
'/home/me'
)
- ).toBe('C:/Users/me/AppData/Roaming/Code/User')
+ ).toBe(join('C:/Users/me/AppData/Roaming', 'Code', 'User'))
})
it('strips line comments from keybindings JSON', () => {
@@ -340,7 +345,9 @@ describe('configureTerminalKeybindings', () => {
await expect(
shouldPromptForTerminalSetup({
env: { TERM_PROGRAM: 'vscode' } as NodeJS.ProcessEnv,
- fileOps: { readFile: readMissing }
+ fileOps: { readFile: readMissing },
+ homeDir: '/tmp/fake-home',
+ platform: 'darwin'
})
).resolves.toBe(true)
@@ -388,7 +395,9 @@ describe('configureTerminalKeybindings', () => {
await expect(
shouldPromptForTerminalSetup({
env: { TERM_PROGRAM: 'vscode' } as NodeJS.ProcessEnv,
- fileOps: { readFile: readComplete }
+ fileOps: { readFile: readComplete },
+ homeDir: '/tmp/fake-home',
+ platform: 'darwin'
})
).resolves.toBe(false)
})
@@ -448,7 +457,9 @@ describe('configureTerminalKeybindings', () => {
await expect(
shouldPromptForTerminalSetup({
env: { TERM_PROGRAM: 'vscode' } as NodeJS.ProcessEnv,
- fileOps: { readFile: readLegacy }
+ fileOps: { readFile: readLegacy },
+ homeDir: '/tmp/fake-home',
+ platform: 'darwin'
})
).resolves.toBe(true)
})
diff --git a/ui-tui/src/lib/editor.test.ts b/ui-tui/src/lib/editor.test.ts
index dc18be716ad..bd870def86a 100644
--- a/ui-tui/src/lib/editor.test.ts
+++ b/ui-tui/src/lib/editor.test.ts
@@ -38,7 +38,7 @@ describe('resolveEditor', () => {
it('ignores whitespace-only env vars', () => {
const expected = exe(dir, 'editor')
- expect(resolveEditor({ EDITOR: ' ', PATH: dir, VISUAL: '' })).toEqual([expected])
+ expect(resolveEditor({ EDITOR: ' ', PATH: dir, VISUAL: '' }, 'linux')).toEqual([expected])
})
it('prefers `editor` over nano over vi on $PATH', () => {
@@ -46,18 +46,18 @@ describe('resolveEditor', () => {
exe(dir, 'vi')
const expected = exe(dir, 'editor')
- expect(resolveEditor({ PATH: dir })).toEqual([expected])
+ expect(resolveEditor({ PATH: dir }, 'linux')).toEqual([expected])
})
it('falls back to nano before vi when both exist', () => {
exe(dir, 'vi')
const expected = exe(dir, 'nano')
- expect(resolveEditor({ PATH: dir })).toEqual([expected])
+ expect(resolveEditor({ PATH: dir }, 'linux')).toEqual([expected])
})
it('returns ["vi"] when $PATH is empty', () => {
- expect(resolveEditor({ PATH: '' })).toEqual(['vi'])
+ expect(resolveEditor({ PATH: '' }, 'linux')).toEqual(['vi'])
})
it('walks multi-entry $PATH', () => {
@@ -65,7 +65,7 @@ describe('resolveEditor', () => {
const b = mkdtempSync(join(tmpdir(), 'editor-b-'))
const expected = exe(b, 'editor')
- expect(resolveEditor({ PATH: [a, b].join(delimiter) })).toEqual([expected])
+ expect(resolveEditor({ PATH: [a, b].join(delimiter) }, 'linux')).toEqual([expected])
})
it('uses notepad.exe on Windows when no env override', () => {
diff --git a/ui-tui/src/lib/terminalParity.ts b/ui-tui/src/lib/terminalParity.ts
index 9010dedfc77..56ca5294845 100644
--- a/ui-tui/src/lib/terminalParity.ts
+++ b/ui-tui/src/lib/terminalParity.ts
@@ -31,14 +31,19 @@ export function detectMacTerminalContext(env: NodeJS.ProcessEnv = process.env):
export async function terminalParityHints(
env: NodeJS.ProcessEnv = process.env,
- options?: { fileOps?: Partial<FileOps>; homeDir?: string }
+ options?: { fileOps?: Partial<FileOps>; homeDir?: string; platform?: NodeJS.Platform }
): Promise<MacTerminalHint[]> {
const ctx = detectMacTerminalContext(env)
const hints: MacTerminalHint[] = []
if (
ctx.vscodeLike &&
- (await shouldPromptForTerminalSetup({ env, fileOps: options?.fileOps, homeDir: options?.homeDir }))
+ (await shouldPromptForTerminalSetup({
+ env,
+ fileOps: options?.fileOps,
+ homeDir: options?.homeDir,
+ platform: options?.platform
+ }))
) {
hints.push({
key: 'ide-setup',