diff --git a/hermes_cli/main.py b/hermes_cli/main.py index f450a76666f3..8867b2b4c0a0 100644 --- a/hermes_cli/main.py +++ b/hermes_cli/main.py @@ -8068,6 +8068,90 @@ 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: + 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: + # 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: + digest = _npm_manifests_digest() + if digest is None: + return + try: + 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 +8162,16 @@ def _update_node_dependencies() -> None: if not (PROJECT_ROOT / "package.json").exists(): return + from hermes_constants import get_default_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 + # 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 +8216,7 @@ def _update_node_dependencies() -> None: env=nixos_env, ) if ws_result.returncode == 0: + _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 56671aa7ecc5..b1458cbd3c2f 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,190 @@ 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 + + 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(hm._npm_manifests_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 + + monkeypatch.setattr(hm, "PROJECT_ROOT", tmp_path) + (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 + + # …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 + + 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() + + 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.""" @@ -246,7 +431,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