The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Disable updates for single-commit desktop builds
ethernete69706943145
diff --git a/apps/desktop/electron/app-version.test.ts b/apps/desktop/electron/app-version.test.tsnew file mode 100644index 00000000000..489772e67d7--- /dev/null+++ b/apps/desktop/electron/app-version.test.ts@@ -0,0 +1,27 @@+import { describe, expect, it } from 'vitest'++import { appVersionInfo, assertSourceUpdateChannel } from './app-version'+import type { InstallStamp } from './install-stamp'++describe('artifact version identity', (): void => {+ it.each([+ ['v1.2.3', 'stable'],+ ['v1.2.4-canary.20260911010101', 'canary'],+ [null, null]+ ] as const)('reports the client version and fixed channel for %s, not a remote runtime', (tag: string | null, channel: 'stable' | 'canary' | null): void => {+ const stamp: InstallStamp = {+ payload: 'bundled', tag, displayVersion: '1.2.3+gabcdef12',+ source: tag ? 'ci' : 'commit-build', updateMechanism: 'external'+ } as InstallStamp++ expect(appVersionInfo(stamp, '9.9.9-remote', '1.2.3')).toMatchObject({+ appVersion: stamp.displayVersion, channel, source: stamp.source+ })+ expect((): void => assertSourceUpdateChannel(stamp)).toThrow()+ })++ it('keeps source installs on their runtime version without a fixed package channel', (): void => {+ expect(appVersionInfo(null, '9.9.9-runtime', '1.2.3')).toMatchObject({ appVersion: '9.9.9-runtime' })+ expect((): void => assertSourceUpdateChannel(null)).not.toThrow()+ })+})diff --git a/apps/desktop/electron/app-version.ts b/apps/desktop/electron/app-version.tsnew file mode 100644index 00000000000..611ecbff9cb--- /dev/null+++ b/apps/desktop/electron/app-version.ts@@ -0,0 +1,49 @@+import { isCanaryTag } from './feature-flags'+import type { InstallStamp } from './install-stamp'+import { COMMIT_BUILD_UPDATE_MESSAGE } from './updater/external'++export interface AppVersionInfo {+ appVersion: string+ baseVersion?: string+ channel?: 'stable' | 'canary' | null+ distance?: number+ commit?: string | null+ branch?: string | null+ source?: InstallStamp['source']+ distribution?: string+ updateMechanism?: InstallStamp['updateMechanism']+ dirty?: boolean+}++/** A release channel is an artifact identity, not a user preference. */+export function packagedReleaseChannel(stamp: Readonly<InstallStamp> | null): 'stable' | 'canary' | null {+ if (!stamp?.tag || stamp.source === 'commit-build') { return null }++ return isCanaryTag(stamp.tag) ? 'canary' : 'stable'+}++/** The backend may live on another machine and run a different release. */+export function appVersionInfo(stamp: Readonly<InstallStamp> | null, runtimeVersion: string, packageVersion: string): AppVersionInfo {+ if (!stamp) { return { appVersion: runtimeVersion, baseVersion: packageVersion } }++ return {+ appVersion: stamp.payload === 'bootstrap' ? runtimeVersion : stamp.displayVersion || packageVersion,+ baseVersion: stamp.baseVersion ?? undefined,+ channel: packagedReleaseChannel(stamp),+ distance: stamp.distance ?? undefined,+ commit: stamp.commit,+ branch: stamp.branch,+ source: stamp.source ?? undefined,+ distribution: stamp.distribution ?? undefined,+ updateMechanism: stamp.updateMechanism,+ dirty: stamp.dirty+ }+}++export function assertSourceUpdateChannel(stamp: Readonly<InstallStamp> | null): void {+ if (stamp?.source === 'commit-build') { throw new Error(COMMIT_BUILD_UPDATE_MESSAGE) }++ if (stamp && stamp.payload !== 'bootstrap') {+ throw new Error('This package has a fixed update channel. Install the other package to change channels.')+ }+}diff --git a/apps/desktop/electron/install-stamp.ts b/apps/desktop/electron/install-stamp.tsindex 9c9f4c93427..7ab7ffe7f72 100644--- a/apps/desktop/electron/install-stamp.ts+++ b/apps/desktop/electron/install-stamp.ts@@ -38,7 +38,7 @@ export interface InstallStamp {builtAt: string | nulldirty: boolean/** Build provenance: where the stamp's facts came from. */- source: 'build' | 'ci' | 'docker' | 'fallback' | 'git' | 'local' | 'nix' | 'unknown' | null+ source: 'build' | 'commit-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. */diff --git a/apps/desktop/electron/updater/commit-build.test.ts b/apps/desktop/electron/updater/commit-build.test.tsnew file mode 100644index 00000000000..a3c1445868e--- /dev/null+++ b/apps/desktop/electron/updater/commit-build.test.ts@@ -0,0 +1,29 @@+import { describe, expect, it } from 'vitest'++import type { InstallStamp } from '../install-stamp'++import { ExternalStrategy } from './external'++import { resolveUpdaterMechanism, type UpdaterStrategy } from './index'++const message: string = "This build doesn't get updates. Ask the developer who gave it to you for a new build."++describe('one-commit artifacts', (): void => {+ it.each(['win32', 'darwin', 'linux'] as const)('cannot select an active updater on %s', (platform: NodeJS.Platform): void => {+ for (const updateMechanism of ['self', 'app-installer', 'electron-updater', 'microsoft-store', 'external'] as const) {+ expect(resolveUpdaterMechanism({ platform, updateMechanism, source: 'commit-build' })).toBe('external')+ }+ })++ it('refuses both checks and apply with no manual-update escape', async (): Promise<void> => {+ const stamp: InstallStamp = { source: 'commit-build' } as InstallStamp+ const strategy: UpdaterStrategy = new ExternalStrategy(stamp)+ expect(await strategy.check({ force: true })).toMatchObject({+ supported: false, mechanism: 'external', reason: 'commit-build', message+ })+ expect(await strategy.apply({ stopSafeBlockers: true })).toMatchObject({+ ok: false, mechanism: 'external', error: 'commit-build', message+ })+ expect(await strategy.apply({})).not.toHaveProperty('command')+ })+})diff --git a/apps/desktop/electron/updater/external.ts b/apps/desktop/electron/updater/external.tsindex 14cedf3fc6a..04d4842cb77 100644--- a/apps/desktop/electron/updater/external.ts+++ b/apps/desktop/electron/updater/external.ts@@ -3,12 +3,18 @@// The stamp declares 'external' when the package owner handles updates// without an in-app check or apply action.+import type { InstallStamp } from '../install-stamp'+import type { UpdaterApplyResultWire, UpdaterStatusWire } from './index'export const EXTERNAL_UNSUPPORTED_MESSAGE ='Updates are managed by the package owner outside this app.'+export const COMMIT_BUILD_UPDATE_MESSAGE: string =+ "This build doesn't get updates. Ask the developer who gave it to you for a new build."+export class ExternalStrategy {+ constructor(private readonly stamp: Pick<InstallStamp, 'source'> | null = null) {}readonly mechanism = 'external' as constreadonly supported = false@@ -16,13 +22,17 @@ export class ExternalStrategy {return {supported: false,mechanism: 'external',- reason: 'bundled-not-appinstaller',- message: EXTERNAL_UNSUPPORTED_MESSAGE,+ reason: this.stamp?.source === 'commit-build' ? 'commit-build' : 'bundled-not-appinstaller',+ message: this.stamp?.source === 'commit-build' ? COMMIT_BUILD_UPDATE_MESSAGE : EXTERNAL_UNSUPPORTED_MESSAGE,fetchedAt: Date.now()}}async apply(): Promise<UpdaterApplyResultWire> {+ if (this.stamp?.source === 'commit-build') {+ return { ok: false, mechanism: 'external', error: 'commit-build', message: COMMIT_BUILD_UPDATE_MESSAGE }+ }+return { ok: true, manual: true, bundled: true, mechanism: 'external' }}}diff --git a/apps/desktop/electron/updater/index.ts b/apps/desktop/electron/updater/index.tsindex 09140096b1d..21a234401b9 100644--- a/apps/desktop/electron/updater/index.ts+++ b/apps/desktop/electron/updater/index.ts@@ -29,6 +29,7 @@ export type UpdaterMechanism =/** The facts the mechanism dispatch keys on. Pure data — injectable for tests. */export interface MechanismFacts {platform: NodeJS.Platform+ source?: InstallStamp['source']updateMechanism: InstallStamp['updateMechanism'] | undefined}@@ -37,6 +38,8 @@ export interface MechanismFacts {* packaged app into a checkout, and Light needs no payload to update itself.*/export function resolveUpdaterMechanism(facts: MechanismFacts): UpdaterMechanism {+ if (facts.source === 'commit-build') { return 'external' }+if (facts.updateMechanism && facts.updateMechanism !== 'self') {return facts.updateMechanism}diff --git a/apps/desktop/src/app/settings/about-settings.test.tsx b/apps/desktop/src/app/settings/about-settings.test.tsxindex 697542dd363..11c809b9279 100644--- a/apps/desktop/src/app/settings/about-settings.test.tsx+++ b/apps/desktop/src/app/settings/about-settings.test.tsx@@ -11,6 +11,7 @@ import {checkBackendUpdates,checkUpdates,refreshDesktopVersion,+ startActiveUpdate,type UpdateApplyState} from '@/store/updates'@@ -109,6 +110,26 @@ describe('AboutSettings', (): void => {expect(checkBackendUpdates).toHaveBeenCalledTimes(2)})+ it('shows the fixed package channel with no selector', (): void => {+ $desktopVersion.set({ ...$desktopVersion.get()!, channel: 'canary' })+ render(<AboutSettings />)+ expect(screen.getByText(`${en.updates.version('1.2.3')} · canary`)).toBeTruthy()+ expect(screen.queryByRole('combobox')).toBeNull()+ })++ it('a commit client refuses updates without hiding an unrelated backend update', (): void => {+ const message: string = "This build doesn't get updates. Ask the developer who gave it to you for a new build."+ $connection.set(connection('remote'))+ $desktopVersion.set({ ...$desktopVersion.get()!, source: 'commit-build' })+ $updateStatus.set({ supported: false, mechanism: 'external', reason: 'commit-build', message })+ $backendUpdateStatus.set({ supported: true, behind: 3 })+ render(<AboutSettings />)+ expect(screen.getByText(message)).toBeTruthy()+ expect(screen.getAllByRole('button', { name: en.updates.checkNow })).toHaveLength(1)+ fireEvent.click(screen.getByRole('button', { name: en.updates.updateNow }))+ expect(startActiveUpdate).toHaveBeenCalledWith('backend')+ })+it('forces a fresh check only for the card the user checks', async (): Promise<void> => {$connection.set(connection('remote'))render(<AboutSettings />)diff --git a/apps/desktop/src/components/update-status.tsx b/apps/desktop/src/components/update-status.tsxindex caf563050d9..6c7a85dd8ae 100644--- a/apps/desktop/src/components/update-status.tsx+++ b/apps/desktop/src/components/update-status.tsx@@ -137,7 +137,7 @@ export function VersionHero({}: {renderHeading?: (heading: string) => ReactNodeversion: DesktopVersionInfo | null-}) {+}): ReactElement {const { t } = useI18n()const u = t.updates@@ -152,6 +152,7 @@ export function VersionHero({)}<p className="mt-1 text-xs text-muted-foreground">{version?.appVersion ? u.version(version.appVersion) : u.versionUnavailable}+ {version?.channel ? ` · ${version.channel}` : ''}</p></div>{(version?.bundleSwapPending || version?.bundleOutOfSync) && (@@ -268,7 +269,7 @@ export function UpdateStatusCard({{view.updateAvailable && view.supported && !view.applying && (<>- <Button onClick={() => startActiveUpdate()} size="sm">+ <Button onClick={() => startActiveUpdate(target)} size="sm">{u.updateNow}</Button><Button onClick={() => openUpdateOverlayFor(target)} size="sm" variant="textStrong">diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.tsindex 3afbd1b603f..7e5ea3a0a76 100644--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@ -650,8 +650,10 @@ export interface DesktopSyncReceipt {}export interface DesktopVersionInfo {- /** Running gateway version; empty when the gateway cannot report it. */+ /** Packaged client version, or the runtime version for source installs. */appVersion: string+ /** Fixed release identity. Commit builds have no update channel. */+ channel?: 'stable' | 'canary' | nullelectronVersion: stringnodeVersion: stringplatform: string@@ -668,7 +670,7 @@ export interface DesktopVersionInfo {commit?: string | nulldistance?: numberdirty?: boolean- source?: 'build' | 'ci' | 'docker' | 'fallback' | 'git' | 'local' | 'nix' | 'unknown'+ source?: 'build' | 'commit-build' | 'ci' | 'docker' | 'fallback' | 'git' | 'local' | 'nix' | 'unknown'distribution?: 'desktop-app' | 'docker' | 'nix'/** Who applies the next update (from the stamp). Names the Store on a* Store-identity build — the Settings label keys off this, neverdiff --git a/hermes_cli/banner.py b/hermes_cli/banner.pyindex 19d12da3111..78ba422c30d 100644--- a/hermes_cli/banner.py+++ b/hermes_cli/banner.py@@ -374,6 +374,13 @@ def check_for_updates(*, passive: bool = False) -> Optional[int]:If ``HERMES_REVISION`` is set (nix builds embed it), compare it to upstream main; otherwisecompare the local checkout's HEAD. Both go through the GitHub API, never ``git fetch``."""+ from hermes_cli.config import get_project_root+ from hermes_cli.update_contract import is_commit_build+ from hermes_cli.steward import is_bundled_payload++ if is_commit_build(get_project_root()) or is_bundled_payload(get_project_root()):+ return None+def _read_config_opt_out():from hermes_cli.config import load_configreturn load_config().get("updates", {}).get("check", True) is False@@ -392,6 +399,10 @@ def check_for_updates(*, passive: bool = False) -> Optional[int]:if _quiet(_install_method) in {"docker", "apt"}:return None+ from hermes_cli.config import load_config+ from hermes_cli.update_channel import resolve_update_channel++ channel = resolve_update_channel(_quiet(load_config), get_project_root())# Cache is invalidated when the embedded rev OR installed version changed since the last check.# For a git checkout the local HEAD is part of the key too: `hermes update` moves HEAD, and a# stale "3 behind" must not survive the update it just prompted.@@ -400,18 +411,30 @@ def check_for_updates(*, passive: bool = False) -> Optional[int]:head_rev = _git_stdout(["rev-parse", "HEAD"], cwd=repo_dir) if repo_dir is not None else Nonecached = _read_json(cache_file)if cached is not None and cached.get("rev") == embedded_rev and cached.get("ver") == VERSION \- and cached.get("head") == head_rev:+ and cached.get("head") == head_rev and cached.get("channel", "main") == channel:ttl = _UPDATE_CHECK_CACHE_SECONDS if cached.get("behind") is not None else _UPDATE_CHECK_FAILURE_CACHE_SECONDSif now - cached.get("ts", 0) < ttl:return cached.get("behind")- if embedded_rev:+ if channel in {"stable", "canary"}:+ from hermes_cli.source_releases import resolve_source_release, source_repository++ global _last_target_rev+ repository = source_repository(["git"] if repo_dir else None, repo_dir)+ _, _last_target_rev = resolve_source_release(channel, repository=repository)+ current = head_rev or embedded_rev+ # A selected release can be an ancestor after a channel switch.+ # Equality, not ancestry, means this install runs that release.+ behind = None if not current or not _last_target_rev else (+ 0 if current == _last_target_rev else UPDATE_AVAILABLE_NO_COUNT+ )+ elif embedded_rev:behind = _check_via_rev(embedded_rev)else:# No checkout and no embedded revision — status can't be determined.behind = _check_via_local_git(repo_dir) if repo_dir is not None else None_quiet(lambda: cache_file.write_text(json.dumps({"ts": now, "behind": behind, "rev": embedded_rev, "ver": VERSION,- "head": head_rev or embedded_rev, "target": _last_target_rev}),+ "head": head_rev or embedded_rev, "target": _last_target_rev, "channel": channel}),encoding="utf-8"))return behind@@ -477,7 +500,29 @@ def get_latest_release_tag(repo_dir: Optional[Path] = None) -> Optional[tuple]:def format_banner_version_label() -> str:"""Return the version label shown in the startup banner title."""+ from hermes_cli.config import get_project_root+ from hermes_cli.steward import read_install_stamp+ from hermes_cli.update_channel import is_canary_tag++ stamp = read_install_stamp(get_project_root())+ if stamp.get("distribution") == "desktop-app":+ version = stamp.get("displayVersion") or stamp.get("baseVersion") or VERSION+ label = f"Hermes Agent v{version}"+ if stamp.get("source") == "commit-build":+ return f"{label} · commit-build · {str(stamp.get('commit') or '')[:12]}"+ if stamp.get("tag"):+ channel = "canary" if is_canary_tag(stamp["tag"]) else "stable"+ return f"{label} · {channel}"+ return label+base = f"Hermes Agent v{VERSION} ({RELEASE_DATE})"+ from hermes_cli.config import load_config+ from hermes_cli.update_channel import resolve_update_channel++ channel = resolve_update_channel(_quiet(load_config), get_project_root())+ if channel in {"stable", "canary"}:+ head = _git_stdout(["rev-parse", "HEAD"], cwd=get_project_root())+ return f"{base} · {channel}" + (f" · local {head[:12]}" if head else "")state = get_git_banner_state()if not state:return basediff --git a/hermes_cli/update_contract.py b/hermes_cli/update_contract.pyindex b74a2bd7f0c..419037e4fcb 100644--- a/hermes_cli/update_contract.py+++ b/hermes_cli/update_contract.py@@ -14,6 +14,17 @@ from typing import Callable, Optionallogger = logging.getLogger(__name__)+COMMIT_BUILD_UPDATE_MESSAGE = (+ "This build doesn't get updates. Ask the developer who gave it to you for a new build."+)+++def is_commit_build(project_root: Path) -> bool:+ from hermes_cli.steward import read_install_stamp++ return read_install_stamp(project_root).get("source") == "commit-build"++@dataclass(frozen=True)class UpdateRefusal:@@ -42,6 +53,9 @@ def evaluate_update_admission(project_root: Path) -> Optional[UpdateRefusal]:``None`` means the install is eligible for in-place update (git checkout or unknown-but-mutable). Never raises; on any internal error it falls back to the heuristic layer only."""+ if is_commit_build(project_root):+ return UpdateRefusal("commit-build", COMMIT_BUILD_UPDATE_MESSAGE, "")+# Layer 1: baked provenance marker — authoritative when present.try:from hermes_cli.image_provenance import read_image_provenance@@ -143,7 +157,9 @@ def record_refusal_receipt(refusal: UpdateRefusal) -> None:from hermes_cli.update_receipt import begin_update_receipt, finalize_update_receipt, record_stepbegin_update_receipt()- record_step("admission", False, f"not updatable in place ({refusal.code}); use: {refusal.update_command}")+ detail = f"not updatable in place ({refusal.code})"+ detail += f"; use: {refusal.update_command}" if refusal.update_command else f"; {refusal.message}"+ record_step("admission", False, detail)finalize_update_receipt("refused", stop_reason=refusal.code)except Exception as exc:logger.debug("Could not record refusal receipt: %s", exc)diff --git a/hermes_cli/version_info.py b/hermes_cli/version_info.pyindex 7f591f22704..7d029091e27 100644--- a/hermes_cli/version_info.py+++ b/hermes_cli/version_info.py@@ -32,7 +32,7 @@ class VersionInfo:distance: int | Nonecommit: str | Nonebranch: str | None- source: Literal["build", "ci", "docker", "fallback", "git", "local", "nix", "unknown"]+ source: Literal["build", "commit-build", "ci", "docker", "fallback", "git", "local", "nix", "unknown"]dirty: bool = Falsecommit_date: int | None = Nonedistribution: Literal["docker", "nix", "desktop-app"] | None = None@@ -146,8 +146,8 @@ def _stamp_version_info() -> VersionInfo | None:# the package form users installed. Keep both facts intact for support.stamp_source = str(data.get("source") or "")source = (- cast(Literal["build", "ci", "docker", "fallback", "git", "local", "nix", "unknown"], stamp_source)- if stamp_source in {"ci", "docker", "fallback", "local", "nix"}+ cast(Literal["build", "commit-build", "ci", "docker", "fallback", "git", "local", "nix", "unknown"], stamp_source)+ if stamp_source in {"commit-build", "ci", "docker", "fallback", "local", "nix"}else "build")distribution = data.get("distribution")diff --git a/hermes_cli/web_routers/actions.py b/hermes_cli/web_routers/actions.pyindex c135e7219f8..e1760a0e735 100644--- a/hermes_cli/web_routers/actions.py+++ b/hermes_cli/web_routers/actions.py@@ -18,6 +18,7 @@ from fastapi import APIRouter, HTTPException, Requestfrom hermes_cli import __version__from hermes_cli.config import format_docker_update_message, recommended_update_command_for_method+from hermes_cli.update_contract import COMMIT_BUILD_UPDATE_MESSAGE, is_commit_buildfrom hermes_cli.web_deps import LateState, latefrom hermes_cli.web_server_gateway import _ACTION_LOG_FILESfrom hermes_cli.web_routers._common import http_failure@@ -200,6 +201,9 @@ def _update_refused(error: str, message: str, update_command: str) -> Dict[str,@router.post("/api/hermes/update")async def update_hermes():"""Kick off ``hermes update`` in the background."""+ if is_commit_build(_server_path("PROJECT_ROOT")):+ return _update_refused("commit-build", COMMIT_BUILD_UPDATE_MESSAGE, "")+if _dashboard_local_update_managed_externally():message = _MANAGED_EXTERNALLY_MESSAGE + " The built-in local updater is disabled here."return _update_refused("dashboard_update_managed_externally", message, "managed outside dashboard")@@ -247,6 +251,16 @@ async def check_hermes_update(force: bool = False):non-applyable methods) and, for git installs that are behind, commits[{sha, summary, author, at}] (additive; existing consumers ignore it)."""+ if is_commit_build(_server_path("PROJECT_ROOT")):+ from hermes_cli.steward import read_install_stamp++ stamp = read_install_stamp(_server_path("PROJECT_ROOT"))+ return {+ "install_method": "desktop-app", "current_version": stamp.get("displayVersion") or __version__,+ "behind": None, "update_available": False, "can_apply": False,+ "update_command": "", "message": COMMIT_BUILD_UPDATE_MESSAGE,+ }+if _dashboard_local_update_managed_externally():return {"install_method": "managed-runtime", "current_version": __version__, "behind": None,diff --git a/tests/hermes_cli/test_banner_release_channel.py b/tests/hermes_cli/test_banner_release_channel.pynew file mode 100644index 00000000000..306d82df6f1--- /dev/null+++ b/tests/hermes_cli/test_banner_release_channel.py@@ -0,0 +1,53 @@+"""Passive checks use the same release selection as explicit source updates."""++import json+from unittest.mock import Mock++import pytest++from hermes_cli import banner+from hermes_cli.update_channel import install_id++[email protected]("channel", ["stable", "canary"])+def test_release_channel_never_compares_main_or_reuses_main_cache(tmp_path, monkeypatch, channel):+ from hermes_constants import get_hermes_home++ root = tmp_path / "source"+ root.mkdir()+ (root / ".git").mkdir()+ monkeypatch.setenv("HERMES_INSTALL_ROOT", str(root))+ monkeypatch.delenv("HERMES_REVISION", raising=False)+ monkeypatch.setattr("hermes_cli.config.get_project_root", lambda: root)+ monkeypatch.setattr(banner, "_resolve_repo_dir", lambda: root)+ head = "a" * 40+ target = "b" * 40+ monkeypatch.setattr(banner, "_git_stdout", lambda args, **kw: head if args == ["rev-parse", "HEAD"] else "https://github.com/NousResearch/hermes-agent.git")+ (get_hermes_home() / "config.yaml").write_text(json.dumps({+ "update": {"installs": {install_id(root): {"path": str(root), "channel": channel}}}+ }))+ (get_hermes_home() / ".update_check").write_text(json.dumps({+ "rev": None, "ver": banner.VERSION, "head": head, "behind": 99, "ts": 10**12,+ }))+ resolve = Mock(return_value=("v1.2.3" if channel == "stable" else "v1.2.4-canary.20260911", target))+ monkeypatch.setattr("hermes_cli.source_releases.resolve_source_release", resolve)+ repository = Mock(return_value="example/fork")+ monkeypatch.setattr("hermes_cli.source_releases.source_repository", repository)+ main = Mock(return_value="c" * 40)+ monkeypatch.setattr(banner, "_github_branch_tip", main)+ compare = Mock(return_value=2)+ monkeypatch.setattr(banner, "_tips_behind", compare)++ assert banner.check_for_updates(passive=True) == banner.UPDATE_AVAILABLE_NO_COUNT+ repository.assert_called_once_with(["git"], root)+ resolve.assert_called_once_with(channel, repository="example/fork")+ compare.assert_not_called()+ main.assert_not_called()+ cache = json.loads((get_hermes_home() / ".update_check").read_text())+ assert cache["channel"] == channel+ assert cache["target"] == target+ # The selected release may be an ancestor (a requested canary → stable switch).+ # That is still a different release, not "already current" or "behind main".+ label = banner.format_banner_version_label()+ assert channel in label+ assert "upstream" not in labeldiff --git a/tests/hermes_cli/test_commit_build_cli.py b/tests/hermes_cli/test_commit_build_cli.pynew file mode 100644index 00000000000..51b32a2a535--- /dev/null+++ b/tests/hermes_cli/test_commit_build_cli.py@@ -0,0 +1,67 @@+"""Exercise the installed CLI with a sealed code copy and its build stamp."""++import json+import os+from pathlib import Path+import shutil+import subprocess+import sys++import pytest++MESSAGE = "This build doesn't get updates. Ask the developer who gave it to you for a new build."++[email protected](scope="module")+def payload(tmp_path_factory):+ root = tmp_path_factory.mktemp("commit-payload")+ source = Path(__file__).resolve().parents[2]+ shutil.copytree(source / "hermes_cli", root / "hermes_cli", ignore=shutil.ignore_patterns("__pycache__"))+ (root / "install-stamp.json").write_text(json.dumps({+ "source": "commit-build", "distribution": "desktop-app", "payload": "bundled",+ "updateMechanism": "external", "commit": "a" * 40,+ "displayVersion": "1.2.3+gabcdef12", "baseVersion": "1.2.3", "tag": None,+ }))+ return root, source+++# The entrypoint runs only from the temporary sealed copy, under an audit hook.[email protected]_system_guard_bypass[email protected]("args", [+ ["--version"], ["update"], ["update", "--check"],+ ["update", "--force", "--yes"], ["update", "--check", "--branch", "main"],+ ["update", "--channel", "canary"], ["update", "--set-channel", "stable"],+])+def test_sealed_cli_never_checks_or_spawns_updater(payload, tmp_path, args):+ root, source = payload+ home = tmp_path / "home"+ home.mkdir()+ env = {**os.environ, "HERMES_HOME": str(home), "HERMES_INSTALL_ROOT": str(root)}+ # Real imports and parser, no admission mocks. Audit attempts even if a caller swallows the error.+ script = f"""+import json, sys+sys.path[:0] = [{str(root)!r}, {str(source)!r}]+sys.argv = ['hermes', *{args!r}]+attempts = []+def audit(event, args):+ if event in ('socket.connect', 'subprocess.Popen', 'os.system'):+ attempts.append(event)+ raise RuntimeError('forbidden update side effect: ' + event)+sys.addaudithook(audit)+try:+ from hermes_cli.main import main+ main()+finally:+ print('AUDIT=' + json.dumps(attempts))+"""+ result = subprocess.run([sys.executable, "-c", script], env=env, cwd=root, capture_output=True, text=True, timeout=45)+ assert result.returncode == (0 if args == ["--version"] else 2), result.stdout + result.stderr+ assert "AUDIT=[]" in result.stdout, result.stdout + result.stderr+ if args == ["--version"]:+ assert "1.2.3+gabcdef12" in result.stdout+ assert "commit-build" in result.stdout+ else:+ assert MESSAGE in result.stdout+ assert "Manage updates from within the desktop app" not in result.stdout+ assert not (home / "config.yaml").exists()+ assert not (home / ".update_check").exists()diff --git a/tests/hermes_cli/test_commit_build_updates.py b/tests/hermes_cli/test_commit_build_updates.pynew file mode 100644index 00000000000..698e95e6e9b--- /dev/null+++ b/tests/hermes_cli/test_commit_build_updates.py@@ -0,0 +1,98 @@+"""A one-commit artifact cannot enter any self-update path."""++import json+from unittest.mock import Mock++import pytest++from hermes_cli.update_contract import evaluate_update_admission++MESSAGE = "This build doesn't get updates. Ask the developer who gave it to you for a new build."+++def commit_build(tmp_path, monkeypatch):+ root = tmp_path / "app"+ root.mkdir()+ (root / "install-stamp.json").write_text(json.dumps({+ "source": "commit-build", "distribution": "desktop-app", "payload": "bundled",+ "updateMechanism": "external", "commit": "a" * 40,+ "displayVersion": "1.2.3+gabcdef12", "baseVersion": "1.2.3", "channel": "canary",+ }))+ monkeypatch.setattr("hermes_cli.image_provenance.IMAGE_PROVENANCE_PATH", tmp_path / "absent")+ monkeypatch.setattr("hermes_cli.config.get_project_root", lambda: root)+ monkeypatch.setattr("hermes_cli.version_info._CODE_ROOT", root)+ monkeypatch.delenv("HERMES_INSTALL_ROOT", raising=False)+ from hermes_cli.version_info import _reset_version_info_cache+ _reset_version_info_cache()+ yield root+ _reset_version_info_cache()++[email protected]("git_present", [False, True])+def test_commit_build_refuses_without_gui_advice(commit_build, git_present):+ if git_present:+ (commit_build / ".git").mkdir()+ refusal = evaluate_update_admission(commit_build)+ assert refusal is not None+ assert refusal.code == "commit-build"+ assert refusal.message == MESSAGE+ assert refusal.update_command == ""++[email protected]("passive", [False, True])+def test_commit_build_never_checks_upstream_or_reuses_source_cache(commit_build, monkeypatch, passive):+ from hermes_cli import banner++ # Even a shared home's source-checkout cache and an embedded SHA cannot turn this into an update.+ monkeypatch.setenv("HERMES_REVISION", "b" * 40)+ check = Mock(return_value=5)+ monkeypatch.setattr(banner, "_check_via_rev", check)+ cache = Mock(return_value={"behind": 5})+ monkeypatch.setattr(banner, "_read_json", cache)+ assert banner.check_for_updates(passive=passive) is None+ check.assert_not_called()+ cache.assert_not_called()+++def test_commit_version_banner_uses_stamp_not_shared_checkout(commit_build, monkeypatch):+ from hermes_cli import banner+ from hermes_cli.version_info import get_version_info++ git = Mock(side_effect=AssertionError("version must not inspect another checkout"))+ monkeypatch.setattr(banner, "get_git_banner_state", git)+ label = banner.format_banner_version_label()+ assert "1.2.3+gabcdef12" in label+ assert "commit-build" in label+ assert get_version_info().source == "commit-build"+ git.assert_not_called()++[email protected]("managed", [False, True])+def test_commit_backend_update_routes_refuse_before_checks_or_spawns(commit_build, monkeypatch, tmp_path, managed):+ from starlette.testclient import TestClient+ import hermes_cli.web_server as server+ import hermes_cli.web_server_gateway as gateway+ from hermes_cli import banner+ from hermes_constants import get_hermes_home++ monkeypatch.setattr(server, "PROJECT_ROOT", commit_build)+ monkeypatch.setattr(gateway, "_ACTION_LOG_DIR", tmp_path / "logs")+ monkeypatch.setattr("hermes_cli.web_server_files._dashboard_local_update_managed_externally", lambda: managed)+ spawn = Mock(side_effect=AssertionError("no updater process"))+ monkeypatch.setattr(gateway, "_spawn_hermes_action", spawn)+ check = Mock(side_effect=AssertionError("no update check"))+ monkeypatch.setattr(banner, "check_for_updates", check)+ cache = get_hermes_home() / ".update_check"+ cache.write_text("source checkout cache")+ client = TestClient(server.app)+ client.headers[server._SESSION_HEADER_NAME] = server._SESSION_TOKEN+ result = client.get("/api/hermes/update/check?force=true")+ assert result.status_code == 200+ assert result.json()["message"] == MESSAGE+ assert result.json()["can_apply"] is False+ assert result.json()["current_version"] == "1.2.3+gabcdef12"+ assert client.post("/api/hermes/update").json()["message"] == MESSAGE+ assert cache.read_text() == "source checkout cache"+ check.assert_not_called()+ spawn.assert_not_called()