From a45a4b13f0ab24d07e3e5357678ef9d6108206bf Mon Sep 17 00:00:00 2001 From: Rod Boev Date: Thu, 4 Jun 2026 19:28:55 -0400 Subject: [PATCH 1/3] perf(cli): skip npm install during update when lockfile is unchanged (#17268) (cherry picked from commit 8fb6d5e910b6fd89bdc698c477cc5f039a0deabd) (cherry picked from commit 27474007b9463d7ce19d981a24aeeac552e79f48) --- hermes_cli/main.py | 41 +++++++++++++ tests/hermes_cli/test_cmd_update.py | 92 ++++++++++++++++++++++++++++- 2 files changed, 132 insertions(+), 1 deletion(-) diff --git a/hermes_cli/main.py b/hermes_cli/main.py index f450a76666f3..ab9146360cf2 100644 --- a/hermes_cli/main.py +++ b/hermes_cli/main.py @@ -8068,6 +8068,39 @@ def _ensure_uv_for_termux(pip_cmd: list[str]) -> str | None: return resolve_uv() or shutil.which("uv") +def _npm_lockfile_changed(hermes_root: Path) -> bool: + lockfile = PROJECT_ROOT / "package-lock.json" + if not lockfile.exists(): + return True + # Also check that node_modules exists; a matching hash with missing + # node_modules means the cache was recorded by another checkout. + if not (PROJECT_ROOT / "node_modules").is_dir(): + return True + try: + current = hashlib.sha256(lockfile.read_bytes()).hexdigest() + # Key the cache by PROJECT_ROOT so parallel worktrees don't collide. + cache_key = hashlib.sha256(str(PROJECT_ROOT).encode()).hexdigest()[:12] + 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 + except OSError: + return True + + +def _record_npm_lockfile_hash(hermes_root: Path) -> None: + lockfile = PROJECT_ROOT / "package-lock.json" + if not lockfile.exists(): + return + try: + digest = hashlib.sha256(lockfile.read_bytes()).hexdigest() + cache_key = hashlib.sha256(str(PROJECT_ROOT).encode()).hexdigest()[:12] + cache_file = hermes_root / f".npm_lock_hash_{cache_key}" + cache_file.write_text(digest, encoding="utf-8") + except OSError: + logger.debug("Could not write npm lockfile hash cache") + + def _update_node_dependencies() -> None: from hermes_constants import find_node_executable, with_hermes_node_path @@ -8078,6 +8111,13 @@ def _update_node_dependencies() -> None: if not (PROJECT_ROOT / "package.json").exists(): return + from hermes_constants import get_default_hermes_root + + hermes_root = get_default_hermes_root() + if not _npm_lockfile_changed(hermes_root): + logger.info("npm lockfile unchanged, skipping npm install") + return + # With a single workspace lockfile the root install would cover ALL # workspaces — but apps/desktop pulls in Electron as a devDependency, # and its postinstall downloads a ~200MB binary. Most users don't @@ -8122,6 +8162,7 @@ def _update_node_dependencies() -> None: env=nixos_env, ) if ws_result.returncode == 0: + _record_npm_lockfile_hash(hermes_root) print(" ✓ repo root + ui-tui, web workspaces (desktop skipped)") else: print(" ⚠ npm workspace install failed") diff --git a/tests/hermes_cli/test_cmd_update.py b/tests/hermes_cli/test_cmd_update.py index 56671aa7ecc5..d8643fb43b62 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 hashlib import subprocess from types import SimpleNamespace from unittest.mock import patch @@ -70,6 +71,92 @@ def _fake_update_managed_uv(): yield +class TestCmdUpdateNpmLockfileCache: + @staticmethod + def _cache_file(hermes_root, project_root): + cache_key = hashlib.sha256(str(project_root).encode()).hexdigest()[:12] + return hermes_root / f".npm_lock_hash_{cache_key}" + + def test_npm_lockfile_changed_no_cache(self, tmp_path, monkeypatch): + from hermes_cli import main as hm + + monkeypatch.setattr(hm, "PROJECT_ROOT", tmp_path) + (tmp_path / "package-lock.json").write_text('{"lockfileVersion": 3}') + (tmp_path / "node_modules").mkdir() + + assert hm._npm_lockfile_changed(tmp_path) is True + + def test_npm_lockfile_changed_matching(self, tmp_path, monkeypatch): + from hermes_cli import main as hm + + content = b'{"lockfileVersion": 3}' + monkeypatch.setattr(hm, "PROJECT_ROOT", tmp_path) + (tmp_path / "package-lock.json").write_bytes(content) + (tmp_path / "node_modules").mkdir() + digest = hashlib.sha256(content).hexdigest() + self._cache_file(tmp_path, tmp_path).write_text(digest) + + assert hm._npm_lockfile_changed(tmp_path) is False + + def test_npm_lockfile_changed_mismatch(self, tmp_path, monkeypatch): + from hermes_cli import main as hm + + monkeypatch.setattr(hm, "PROJECT_ROOT", tmp_path) + (tmp_path / "package-lock.json").write_text('{"lockfileVersion": 3}') + (tmp_path / "node_modules").mkdir() + self._cache_file(tmp_path, tmp_path).write_text("old-digest") + + assert hm._npm_lockfile_changed(tmp_path) is True + + def test_npm_lockfile_changed_missing_node_modules(self, tmp_path, monkeypatch): + from hermes_cli import main as hm + + content = b'{"lockfileVersion": 3}' + monkeypatch.setattr(hm, "PROJECT_ROOT", tmp_path) + (tmp_path / "package-lock.json").write_bytes(content) + digest = hashlib.sha256(content).hexdigest() + self._cache_file(tmp_path, tmp_path).write_text(digest) + # node_modules missing: should report changed even though hash matches + + assert hm._npm_lockfile_changed(tmp_path) is True + + def test_record_npm_lockfile_hash(self, tmp_path, monkeypatch): + from hermes_cli import main as hm + + content = b'{"lockfileVersion": 3}' + monkeypatch.setattr(hm, "PROJECT_ROOT", tmp_path) + (tmp_path / "package-lock.json").write_bytes(content) + + hm._record_npm_lockfile_hash(tmp_path) + + expected = hashlib.sha256(content).hexdigest() + assert self._cache_file(tmp_path, tmp_path).read_text() == expected + + def test_npm_lockfile_changed_cache_read_error(self, tmp_path, monkeypatch): + from hermes_cli import main as hm + + monkeypatch.setattr(hm, "PROJECT_ROOT", tmp_path) + (tmp_path / "package-lock.json").write_text('{"lockfileVersion": 3}') + (tmp_path / "node_modules").mkdir() + # Make cache file a directory to cause OSError on read + self._cache_file(tmp_path, tmp_path).mkdir(parents=True) + + assert hm._npm_lockfile_changed(tmp_path) is True + + def test_update_skips_npm_when_lockfile_unchanged(self, tmp_path, monkeypatch): + from hermes_cli import main as hm + + monkeypatch.setattr(hm, "PROJECT_ROOT", tmp_path) + (tmp_path / "package.json").write_text("{}") + + with patch("shutil.which", return_value="/usr/bin/npm"), \ + patch.object(hm, "_npm_lockfile_changed", return_value=False), \ + patch("subprocess.run") as mock_run: + hm._update_node_dependencies() + + mock_run.assert_not_called() + + class TestCmdUpdatePip: """Regression tests for pip-install update flows.""" @@ -246,7 +333,10 @@ def test_update_on_fork_checks_upstream_when_origin_up_to_date( ), patch.object(hm, "_sync_with_upstream_if_needed") as sync_mock: cmd_update(mock_args) - sync_mock.assert_called_once_with(["git"], PROJECT_ROOT) + expected_git_cmd = ( + ["git", "-c", "windows.appendAtomically=false"] if hm._is_windows() else ["git"] + ) + sync_mock.assert_called_once_with(expected_git_cmd, PROJECT_ROOT) captured = capsys.readouterr() assert "Already up to date!" in captured.out From 16516654287156b422d8f8685cbcb037907a20b4 Mon Sep 17 00:00:00 2001 From: kshitijk4poor <82637225+kshitijk4poor@users.noreply.github.com> Date: Fri, 10 Jul 2026 00:21:24 +0530 Subject: [PATCH 2/3] fix: derive skip-key manifests from npm workspaces config MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review round 2 from @ethernet8023 on #61580: 1. The manifest list was a hardcoded root/ui-tui/web trio — desktop and any future workspace escaped the skip key even though step 1's root install hoists deps for every workspace. The list is now expanded from the root package.json 'workspaces' globs (npm's own source of truth): on the real repo that yields all 8 manifests incl. apps/desktop, apps/bootstrap-installer, apps/shared, and the nested ui-tui/packages/hermes-ink. Unreadable package.json falls back to root manifests only (never skips more than main would install). 2. --prefer-offline dropped entirely (this branch no longer carries #39399): local 3-run benchmarks on the repo's real manifests show the flag is noise on npm ci with a warm cache (root: 0.90s vs 0.84s avg; ws: 4.02s vs 4.00s avg) — npm ci does no resolution and the content-addressed cache already serves tarballs locally. It also carried the stale-resolution risk on the npm install fallback the reviewer flagged. All the real win is the skip itself (0s vs ~5s+). Tests: workspace-glob edit (desktop), literal-listed edit, and new-workspace-under-glob all defeat the skip; verified against the real repo's workspace config (8 manifests picked up). --- hermes_cli/main.py | 63 ++++++++++++++++++++--- tests/hermes_cli/test_cmd_update.py | 80 ++++++++++++++++++++++++++--- 2 files changed, 129 insertions(+), 14 deletions(-) diff --git a/hermes_cli/main.py b/hermes_cli/main.py index ab9146360cf2..758119699a23 100644 --- a/hermes_cli/main.py +++ b/hermes_cli/main.py @@ -8068,16 +8068,68 @@ def _ensure_uv_for_termux(pip_cmd: list[str]) -> str | None: return resolve_uv() or shutil.which("uv") +def _npm_manifest_paths() -> tuple[Path, ...]: + """Manifests whose changes must defeat the update-skip. + + The lockfile alone is NOT a sufficient key: on a local checkout a dev + can edit package.json (root or a workspace) without running npm — the + lockfile is then unchanged but `hermes update` is exactly the step + expected to sync node_modules (via the `npm install` fallback in + _run_npm_install_deterministic). + + The workspace list is pulled from the root package.json's `workspaces` + globs (npm's own source of truth) rather than hardcoded, so adding a + workspace can never silently escape the skip key. The root install + (step 1, --workspaces=false) still hoists shared deps for EVERY + workspace — desktop included — so all of them belong in the key, not + just the ones step 2 installs. Falls back to hashing just root + manifests if package.json is unreadable (never skips more than main + would have installed). + """ + root_pkg = PROJECT_ROOT / "package.json" + paths = [PROJECT_ROOT / "package-lock.json", root_pkg] + try: + workspaces = json.loads(root_pkg.read_text(encoding="utf-8")).get( + "workspaces", [] + ) + if isinstance(workspaces, dict): # legacy {"packages": [...]} form + workspaces = workspaces.get("packages", []) + for pattern in workspaces: + for match in sorted(PROJECT_ROOT.glob(str(pattern))): + manifest = match / "package.json" + if manifest.is_file(): + paths.append(manifest) + except (OSError, json.JSONDecodeError, TypeError): + pass + return tuple(paths) + + +def _npm_manifests_digest() -> str | None: + """Combined sha256 over the lockfile + all workspace package.json files. + + Returns None when the lockfile is missing (never skip then). + """ + if not (PROJECT_ROOT / "package-lock.json").exists(): + return None + h = hashlib.sha256() + for p in _npm_manifest_paths(): + h.update(str(p.relative_to(PROJECT_ROOT)).encode()) + try: + h.update(p.read_bytes()) + except OSError: + h.update(b"") + return h.hexdigest() + + def _npm_lockfile_changed(hermes_root: Path) -> bool: - lockfile = PROJECT_ROOT / "package-lock.json" - if not lockfile.exists(): + current = _npm_manifests_digest() + if current is None: return True # Also check that node_modules exists; a matching hash with missing # node_modules means the cache was recorded by another checkout. if not (PROJECT_ROOT / "node_modules").is_dir(): return True try: - current = hashlib.sha256(lockfile.read_bytes()).hexdigest() # Key the cache by PROJECT_ROOT so parallel worktrees don't collide. cache_key = hashlib.sha256(str(PROJECT_ROOT).encode()).hexdigest()[:12] cache_file = hermes_root / f".npm_lock_hash_{cache_key}" @@ -8089,11 +8141,10 @@ def _npm_lockfile_changed(hermes_root: Path) -> bool: def _record_npm_lockfile_hash(hermes_root: Path) -> None: - lockfile = PROJECT_ROOT / "package-lock.json" - if not lockfile.exists(): + digest = _npm_manifests_digest() + if digest is None: return try: - digest = hashlib.sha256(lockfile.read_bytes()).hexdigest() cache_key = hashlib.sha256(str(PROJECT_ROOT).encode()).hexdigest()[:12] cache_file = hermes_root / f".npm_lock_hash_{cache_key}" cache_file.write_text(digest, encoding="utf-8") diff --git a/tests/hermes_cli/test_cmd_update.py b/tests/hermes_cli/test_cmd_update.py index d8643fb43b62..3be32ab8cf04 100644 --- a/tests/hermes_cli/test_cmd_update.py +++ b/tests/hermes_cli/test_cmd_update.py @@ -89,12 +89,10 @@ def test_npm_lockfile_changed_no_cache(self, tmp_path, monkeypatch): def test_npm_lockfile_changed_matching(self, tmp_path, monkeypatch): from hermes_cli import main as hm - content = b'{"lockfileVersion": 3}' monkeypatch.setattr(hm, "PROJECT_ROOT", tmp_path) - (tmp_path / "package-lock.json").write_bytes(content) + (tmp_path / "package-lock.json").write_text('{"lockfileVersion": 3}') (tmp_path / "node_modules").mkdir() - digest = hashlib.sha256(content).hexdigest() - self._cache_file(tmp_path, tmp_path).write_text(digest) + self._cache_file(tmp_path, tmp_path).write_text(hm._npm_manifests_digest()) assert hm._npm_lockfile_changed(tmp_path) is False @@ -123,14 +121,80 @@ def test_npm_lockfile_changed_missing_node_modules(self, tmp_path, monkeypatch): def test_record_npm_lockfile_hash(self, tmp_path, monkeypatch): from hermes_cli import main as hm - content = b'{"lockfileVersion": 3}' monkeypatch.setattr(hm, "PROJECT_ROOT", tmp_path) - (tmp_path / "package-lock.json").write_bytes(content) + (tmp_path / "package-lock.json").write_text('{"lockfileVersion": 3}') + + hm._record_npm_lockfile_hash(tmp_path) + + assert ( + self._cache_file(tmp_path, tmp_path).read_text() + == hm._npm_manifests_digest() + ) + + def test_package_json_only_edit_defeats_skip(self, tmp_path, monkeypatch): + """Reviewer scenario (#61580): dev edits package.json WITHOUT running + npm — lockfile unchanged. `hermes update` must still install (the + npm-install fallback is what syncs node_modules in that state).""" + from hermes_cli import main as hm + + monkeypatch.setattr(hm, "PROJECT_ROOT", tmp_path) + (tmp_path / "package-lock.json").write_text('{"lockfileVersion": 3}') + (tmp_path / "package.json").write_text('{"dependencies": {}}') + (tmp_path / "node_modules").mkdir() + hm._record_npm_lockfile_hash(tmp_path) + assert hm._npm_lockfile_changed(tmp_path) is False + + (tmp_path / "package.json").write_text( + '{"dependencies": {"left-pad": "^1.0.0"}}' + ) + assert hm._npm_lockfile_changed(tmp_path) is True + def test_workspace_package_json_edit_defeats_skip(self, tmp_path, monkeypatch): + """The manifest list comes from the root package.json `workspaces` + globs (npm's source of truth), so ANY workspace (desktop included) + defeats the skip, not a hardcoded set.""" + from hermes_cli import main as hm + + monkeypatch.setattr(hm, "PROJECT_ROOT", tmp_path) + (tmp_path / "package-lock.json").write_text('{"lockfileVersion": 3}') + (tmp_path / "package.json").write_text( + '{"workspaces": ["apps/*", "ui-tui"]}' + ) + (tmp_path / "ui-tui").mkdir() + (tmp_path / "ui-tui" / "package.json").write_text("{}") + (tmp_path / "apps" / "desktop").mkdir(parents=True) + (tmp_path / "apps" / "desktop" / "package.json").write_text("{}") + (tmp_path / "node_modules").mkdir() hm._record_npm_lockfile_hash(tmp_path) + assert hm._npm_lockfile_changed(tmp_path) is False + + # A glob-matched workspace (desktop) defeats the skip… + (tmp_path / "apps" / "desktop" / "package.json").write_text( + '{"name": "desktop"}' + ) + assert hm._npm_lockfile_changed(tmp_path) is True - expected = hashlib.sha256(content).hexdigest() - assert self._cache_file(tmp_path, tmp_path).read_text() == expected + # …and so does a literal-listed one. + hm._record_npm_lockfile_hash(tmp_path) + assert hm._npm_lockfile_changed(tmp_path) is False + (tmp_path / "ui-tui" / "package.json").write_text('{"name": "x"}') + assert hm._npm_lockfile_changed(tmp_path) is True + + def test_new_workspace_added_defeats_skip(self, tmp_path, monkeypatch): + """Adding a whole new workspace dir under an existing glob changes + the manifest set itself — must also defeat the skip.""" + from hermes_cli import main as hm + + monkeypatch.setattr(hm, "PROJECT_ROOT", tmp_path) + (tmp_path / "package-lock.json").write_text('{"lockfileVersion": 3}') + (tmp_path / "package.json").write_text('{"workspaces": ["apps/*"]}') + (tmp_path / "node_modules").mkdir() + hm._record_npm_lockfile_hash(tmp_path) + assert hm._npm_lockfile_changed(tmp_path) is False + + (tmp_path / "apps" / "newtool").mkdir(parents=True) + (tmp_path / "apps" / "newtool" / "package.json").write_text("{}") + assert hm._npm_lockfile_changed(tmp_path) is True def test_npm_lockfile_changed_cache_read_error(self, tmp_path, monkeypatch): from hermes_cli import main as hm From a8f227ae2a2257bfb6c1fe3c7b410732ce4e46ab Mon Sep 17 00:00:00 2001 From: kshitijk4poor <82637225+kshitijk4poor@users.noreply.github.com> Date: Fri, 10 Jul 2026 10:49:42 +0530 Subject: [PATCH 3/3] test(update): document shared npm cache scope --- hermes_cli/main.py | 9 +++++--- tests/hermes_cli/test_cmd_update.py | 34 +++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/hermes_cli/main.py b/hermes_cli/main.py index 758119699a23..8867b2b4c0a0 100644 --- a/hermes_cli/main.py +++ b/hermes_cli/main.py @@ -8164,8 +8164,11 @@ def _update_node_dependencies() -> None: from hermes_constants import get_default_hermes_root - hermes_root = get_default_hermes_root() - if not _npm_lockfile_changed(hermes_root): + # This cache describes PROJECT_ROOT/node_modules, which is shared by every + # Hermes profile using this checkout. Keep one per-checkout cache under the + # shared Hermes root rather than rerunning npm once per named profile. + shared_hermes_root = get_default_hermes_root() + if not _npm_lockfile_changed(shared_hermes_root): logger.info("npm lockfile unchanged, skipping npm install") return @@ -8213,7 +8216,7 @@ def _update_node_dependencies() -> None: env=nixos_env, ) if ws_result.returncode == 0: - _record_npm_lockfile_hash(hermes_root) + _record_npm_lockfile_hash(shared_hermes_root) print(" ✓ repo root + ui-tui, web workspaces (desktop skipped)") else: print(" ⚠ npm workspace install failed") diff --git a/tests/hermes_cli/test_cmd_update.py b/tests/hermes_cli/test_cmd_update.py index 3be32ab8cf04..b1458cbd3c2f 100644 --- a/tests/hermes_cli/test_cmd_update.py +++ b/tests/hermes_cli/test_cmd_update.py @@ -220,6 +220,40 @@ def test_update_skips_npm_when_lockfile_unchanged(self, tmp_path, monkeypatch): mock_run.assert_not_called() + def test_update_uses_one_shared_npm_cache_across_profiles( + self, tmp_path, monkeypatch + ): + """The npm cache describes checkout-global node_modules, not a profile.""" + from hermes_cli import main as hm + import hermes_constants + + checkout = tmp_path / "checkout" + checkout.mkdir() + (checkout / "package.json").write_text("{}") + shared_root = tmp_path / ".hermes" + named_profile = shared_root / "profiles" / "work" + named_profile.mkdir(parents=True) + + monkeypatch.setattr(hm, "PROJECT_ROOT", checkout) + monkeypatch.setattr(hermes_constants.Path, "home", lambda: tmp_path) + monkeypatch.setattr( + hermes_constants, "find_node_executable", lambda _name: "/usr/bin/npm" + ) + + cache_roots = [] + with patch.object( + hm, + "_npm_lockfile_changed", + side_effect=lambda root: cache_roots.append(root) or False, + ): + monkeypatch.setenv("HERMES_HOME", str(shared_root)) + hm._update_node_dependencies() + + monkeypatch.setenv("HERMES_HOME", str(named_profile)) + hm._update_node_dependencies() + + assert cache_roots == [shared_root, shared_root] + class TestCmdUpdatePip: """Regression tests for pip-install update flows."""