The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(pm): keep bootstrap and readiness checks behind safe operations
ethernetc7b1f238b517
diff --git a/pm/client.py b/pm/client.pyindex 1900a88a342..208254bebbb 100644--- a/pm/client.py+++ b/pm/client.py@@ -269,10 +269,11 @@ def stage_manager_runtime(*, python: Path, destination: Path, project: Path | None = None,offline: bool = False, wheelhouse: Path | None = None, cache: Path | None = None,) -> Path:- return Path(_python_operation("stage_manager_runtime", {- "python": Path(python), "destination": Path(destination), "project": project,- "offline": offline, "wheelhouse": wheelhouse, "cache": cache,- }))+ # PM cannot dispatch the construction of its own offline runtime through+ # that runtime. The stdlib-only bootstrap shares the private build engine.+ from pm.operations import stage_manager_runtime as stage+ return stage(python=Path(python), destination=Path(destination), project=project,+ offline=offline, wheelhouse=wheelhouse, cache=cache)def ensure_environment(@@ -302,9 +303,16 @@ def ensure_python_tool(def venv_is_current(*, project_root: Path | None = None) -> bool:- from pm.ensure import venv_is_current as direct-- return direct(project_root=project_root)+ """Check through a ready PM, never bootstrap dependencies for a probe."""+ if is_runtime() and (project_root is None or Path(project_root).resolve() == paths.repo_root().resolve()):+ from pm.ensure import venv_is_current as direct+ return direct(project_root=project_root)+ try:+ return bool(_request("venv_is_current", {}, project_root=project_root))+ except InstallError as exc:+ if exc.package == "pm-runtime":+ return False # Without its checker, currency cannot be established.+ raisedef check_project_lock(source: Path, *, python: Path | None = None, cache: Path | None = None,diff --git a/pm/extras.py b/pm/extras.pyindex 5ca2c9ee072..7f09228ab5e 100644--- a/pm/extras.py+++ b/pm/extras.py@@ -55,7 +55,7 @@ ANCHORS: dict[str, str | tuple[str, ...]] = {"modal": "modal","daytona": "daytona","vercel": "vercel",- "google": "googleapiclient",+ "google": ("googleapiclient", "google.auth", "google_auth_oauthlib.flow", "google_auth_httplib2"),"google-chat": "google.cloud.pubsub_v1","youtube": "youtube_transcript_api","acp": "acp",diff --git a/pm/operations.py b/pm/operations.pyindex 50f731a7753..162525ac0e2 100644--- a/pm/operations.py+++ b/pm/operations.py@@ -84,19 +84,29 @@ def stage_manager_runtime(offline: bool = False, wheelhouse: Path | None = None, cache: Path | None = None,) -> Path:"""Stage PM's independent dependency graph using its private toolchain."""- from pm.environment import managed_environment+ from pm._uv import _toolchainfrom pm.runtime_stage import stage_runtimedestination, python = Path(destination).absolute(), Path(python).absolute()if destination.exists() or destination.is_symlink():raise FileExistsError(f"environment destination already exists: {destination}")- environment = managed_environment(destination, python=python,- cache=Path(cache) if cache is not None else None, explicit=True,- offline=offline, output=sys.stderr)- return stage_runtime(environment.uv, python, destination,- project=Path(project) if project is not None else None,- offline=offline, wheelhouse=Path(wheelhouse) if wheelhouse is not None else None,- cache=Path(cache) if cache is not None else None)+ # Tools are staged before this bootstrap: acquiring them here would need+ # the TLS dependencies in the very runtime we are constructing.+ tools = _toolchain(realize=False)+ if tools is None:+ raise InstallError("pm-runtime", "stage pinned tools before building the manager runtime")+ destination.mkdir(parents=True)+ try:+ executable = stage_runtime(tools[0], python, destination,+ project=Path(project) if project is not None else None,+ offline=offline, wheelhouse=Path(wheelhouse) if wheelhouse is not None else None,+ cache=Path(cache) if cache is not None else None)+ from pm.lock import _write+ _write(destination / "pm-runtime.json", {})+ return executable+ except BaseException:+ shutil.rmtree(destination, ignore_errors=True)+ raisedef _environment_root(name: str, root: Path | None) -> Path:diff --git a/tests/pm/test_extras.py b/tests/pm/test_extras.pyindex 37af3f5840a..59fbf5fabe0 100644--- a/tests/pm/test_extras.py+++ b/tests/pm/test_extras.py@@ -134,6 +134,14 @@ def test_available_counts_sys_modules_fakes(monkeypatch, extra, module):assert extras.available(extra) is True+def test_google_readiness_requires_its_oauth_imports(monkeypatch):+ present = {"googleapiclient", "google.auth", "google_auth_httplib2"}+ monkeypatch.setattr(extras, "_importable", lambda name: name in present)+ assert not extras.available("google")+ present.add("google_auth_oauthlib.flow")+ assert extras.available("google")++def test_available_unknown_extra_uses_underscore_guess(monkeypatch):monkeypatch.setitem(sys.modules, "some_new_thing", SimpleNamespace())assert extras.available("some-new-thing") is Truediff --git a/tests/pm/test_update_dependency_legs.py b/tests/pm/test_update_dependency_legs.pyindex cd42cf355ee..378511bbc68 100644--- a/tests/pm/test_update_dependency_legs.py+++ b/tests/pm/test_update_dependency_legs.py@@ -15,7 +15,7 @@ from pm import cli, paths, registryfrom pm.lock import Facts, Lockfilefrom pm.package import Packagefrom pm.packages import Nodejs, Npm, Python, Uv-from pm.store import current_target+from pm.store import current_target, tree_digestclass ManualFixture(Package):@@ -38,6 +38,7 @@ def project(tmp_path, monkeypatch):monkeypatch.setattr(paths, 'repo_root', lambda: repo)monkeypatch.setattr(cli, 'repo_root', lambda: repo)monkeypatch.setattr(paths, 'lockfile_path', lambda: lock.path)+ monkeypatch.setattr(Path, 'home', lambda: tmp_path / 'home')monkeypatch.setenv('HERMES_HOME', str(tmp_path / 'home'))monkeypatch.setenv('HERMES_RUNTIME_DIR', str(tmp_path / 'store'))monkeypatch.chdir(caller)@@ -69,7 +70,7 @@ def test_uv_refresh_uses_real_installed_tool_and_only_the_owned_project(tmp_pathmonkeypatch.setitem(registry._packages, name, package)lock.set_pin(name, 'fixture', {target: {'url': f'https://example.invalid/{name}', 'sha256': '1' * 64}})facts.record(name, 'fixture', str(entry), package.env(entry, target), runtime,- target=target, artifacts=['1' * 64])+ target=target, artifacts=['1' * 64], digest=tree_digest(entry))lock.save()before_lock = lock.path.read_bytes()parent_env = dict(os.environ)@@ -95,12 +96,12 @@ def test_uv_refresh_uses_real_installed_tool_and_only_the_owned_project(tmp_path(repo / 'pyproject.toml').write_text('invalid project [', encoding='utf-8')assert cli.cmd_update(args) == 1assert (repo / 'uv.lock').read_bytes() == original and not syncs- assert 'uv lock --upgrade failed' in capsys.readouterr().out+ assert 'Python lock refresh failed' in capsys.readouterr().outmanaged.unlink()assert cli.cmd_update(args) == 1assert (repo / 'uv.lock').read_bytes() == original and not syncs- assert 'not installed' in capsys.readouterr().out+ assert 'Python lock refresh failed' in capsys.readouterr().out@pytest.mark.platforms('windows', 'posix')@@ -108,6 +109,9 @@ def test_npm_refresh_uses_its_installed_entry_and_owned_project(monkeypatch, capnode_source = Path(shutil.which('node') or pytest.fail('node is required'))npm_source = Path(shutil.which('npm.cmd' if os.name == 'nt' else 'npm') or pytest.fail('npm is required')).resolve()npm_source = npm_source.parent / 'node_modules/npm' if os.name == 'nt' else npm_source.parents[1]+ if not (npm_source / 'bin/npm-cli.js').is_file():+ npm_source = next((path for path in (npm_source / 'lib/npm', npm_source / 'lib/node_modules/npm')+ if (path / 'bin/npm-cli.js').is_file()), npm_source)assert (npm_source / 'bin/npm-cli.js').is_file()# Keep the real tool's argv clear of the harness's hermes-update guard.temp_root = Path(os.environ['LOCALAPPDATA']) / 'Temp' if os.name == 'nt' else Path('/tmp')@@ -127,6 +131,9 @@ def test_npm_refresh_uses_its_installed_entry_and_owned_project(monkeypatch, capshutil.copy2(node_source, node_binary)bundled_npm = node_entry / ('node_modules/npm' if os.name == 'nt' else 'lib/node_modules/npm')shutil.copytree(npm_source, bundled_npm)+ for directory in (bundled_npm, *bundled_npm.rglob('*')):+ if directory.is_dir():+ directory.chmod(directory.stat().st_mode | 0o700)facts = Facts(runtime / 'facts.json')node, npm = Nodejs(), Npm()monkeypatch.setitem(registry._packages, 'node', node)@@ -136,7 +143,7 @@ def test_npm_refresh_uses_its_installed_entry_and_owned_project(monkeypatch, captarget=target, artifacts=['1' * 64])lock.save()archive = root / 'npm.tgz'- with tarfile.open(archive, 'w:gz') as output:+ with tarfile.open(archive, 'w:gz', dereference=True) as output:output.add(npm_source, arcname='package')npm_entry = runtime / 'npm-fixture'npm.unpack(archive, npm_entry, target)diff --git a/tests/pm/test_worker.py b/tests/pm/test_worker.pyindex b6a79895fb6..44d02f15e25 100644--- a/tests/pm/test_worker.py+++ b/tests/pm/test_worker.py@@ -14,6 +14,7 @@ from pm import pathsfrom pm.package import InstallErrorfrom pm.runtime import runtime_pythonfrom tests.pm._range_server import RangeHandler, dl_server, url # noqa: F401+from tests.pm.test_runtime_wheelhouse import locked_wheelhouse # noqa: F401@pytest.fixture(scope="module")@@ -455,6 +456,60 @@ def test_worker_death_reports_transport_failure(client, monkeypatch, isolated_pyclient.ensure("node", explicit=True)+def test_foreign_checkout_sync_uses_its_own_pm_generation(client, tmp_path, monkeypatch, isolated_python):+ from pm import venv_is_current+ from hermes_cli.runtime_paths import selected_venv, runtime_facts_path++ uv = shutil.which("uv")+ assert uv+ worker = Path(client.__file__).with_name("worker.py")+ script = (+ "import runpy, sys; "+ f"sys.path.insert(0, {str(worker.parent.parent)!r}); "+ "import pm._uv; "+ f"pm._uv._toolchain = lambda **kwargs: (__import__('pathlib').Path({uv!r}), "+ f"__import__('pathlib').Path({sys.executable!r})); "+ f"runpy.run_path({str(worker)!r}, run_name='__main__')"+ )+ monkeypatch.setattr(client, "runtime_command", lambda path, **kwargs: [str(isolated_python), "-I", "-B", "-c", script])+ foreign = tmp_path / "other checkout"+ foreign.mkdir()+ (foreign / "pyproject.toml").write_text(+ '[project]\nname="foreign-proof"\nversion="1"\nrequires-python=">=3.11"\n'+ '[tool.uv]\npackage=false\n', encoding="utf-8")+ client.lock_project(foreign, offline=True, explicit=True)+ assert not venv_is_current(project_root=foreign)+ original_root = paths.repo_root()+ client.sync_venv([], project_root=foreign, plugin_dirs=[], explicit=True)+ selected = selected_venv(foreign)+ assert selected != foreign / "venv"+ assert selected.is_relative_to(runtime_facts_path(foreign).parent)+ assert runtime_facts_path(foreign).is_file()+ assert venv_is_current(project_root=foreign)+ assert paths.repo_root() == original_root+ assert not runtime_facts_path(original_root).exists()+++def test_cold_manager_build_does_not_bootstrap_a_worker(client, tmp_path, monkeypatch, locked_wheelhouse):+ import pm++ wheels, _ = locked_wheelhouse++ uv = shutil.which("uv")+ assert uv+ monkeypatch.setattr(client, "runtime_command", lambda *a, **kw: pytest.fail("manager build requested itself"))+ monkeypatch.setattr("pm._uv._toolchain", lambda **kwargs: (Path(uv), Path(sys.executable))+ if kwargs == {"realize": False} else pytest.fail("bootstrap tried to install tools"))+ project = Path(__file__).resolve().parents[2] / "pm"+ python = pm.stage_manager_runtime(python=Path(sys.executable), destination=tmp_path / "manager",+ project=project, wheelhouse=wheels, offline=True)+ result = subprocess.run([str(python), "-I", "-c", "import packaging, tomli_w, truststore; from ruamel.yaml import YAML"],+ capture_output=True, text=True, timeout=30)+ assert result.returncode == 0, result.stderr+ with pytest.raises(FileExistsError):+ pm.stage_manager_runtime(python=Path(sys.executable), destination=python.parent.parent)++def test_worker_side_environment_reuses_and_keeps_selection_on_failed_tool(client, tmp_path, monkeypatch, isolated_python):import zipfilefrom pm import environment_python, python_tool