The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Keep startup and launcher fixtures on the real preimport protocol
ethernetcae0f715df60
diff --git a/tests/pm/test_startup_recovery.py b/tests/pm/test_startup_recovery.pyindex f1824afd6c3..e46153fc4e9 100644--- a/tests/pm/test_startup_recovery.py+++ b/tests/pm/test_startup_recovery.py@@ -1,4 +1,8 @@-"""Startup restores recorded dependencies before importing application packages."""+"""Bare startup repairs through real PM workers before activating dependencies.++The copied install is not a self-managed git checkout: source-update completion+must defer to recorded-graph recovery, not resolve today's application inputs.+"""from __future__ import annotationsimport importlib@@ -19,8 +23,12 @@ from tests.pm.test_workspace_build_inputs import _wheel@pytest.fixture(autouse=True)def isolated_machine_home(tmp_path, monkeypatch):monkeypatch.setattr(Path, "home", lambda: tmp_path)+ # Path.home's monkeypatch does not cross the subprocess boundary. PM's+ # machine cache and platform-specific home lookup must be isolated there too.+ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setenv("USERPROFILE", str(tmp_path))monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))-+ monkeypatch.delenv("HERMES_INSTALL_ROOT", raising=False)@pytest.mark.parametrize("marker_name", [".update-incomplete", ".lazy-refresh-incomplete", None, "manual", "baseline"])@@ -39,14 +47,19 @@ def test_bootstrap_repairs_before_dependency_activation(tmp_path, monkeypatch, mshutil.copytree(repo / "pm", core / "pm", ignore=shutil.ignore_patterns("__pycache__"))cli = core / "hermes_cli"cli.mkdir()- for name in ("__init__.py", "runtime_paths.py", "runtime_state.py", "_early_recovery.py", "_parser.py"):+ # Include the real preimport protocol, including its ownership check. Do+ # not stub prepare_launch: the same files are also saved in PM's workspace.+ for name in ("__init__.py", "runtime_paths.py", "runtime_state.py", "_early_recovery.py", "_parser.py",+ "venv_sync.py", "steward.py"):shutil.copy2(repo / "hermes_cli" / name, cli / name)wheels = tmp_path / "wheels"wheels.mkdir()_wheel(wheels, "startup_dep", "1.0")(core / "pyproject.toml").write_text('[project]\nname="startup-proof"\nversion="1"\nrequires-python=">=3.11"\n'- 'dependencies=["startup-dep==1.0"]\n[tool.uv]\npackage=false\nno-index=true\n'+ 'dependencies=["startup-dep==1.0"]\n'+ '[project.optional-dependencies]\nstartup-extra=[]\n'+ '[tool.uv]\npackage=false\nno-index=true\noffline=true\n'f'find-links=[{json.dumps(wheels.as_posix())}]\n', encoding="utf-8",)uv = shutil.which("uv")@@ -59,15 +72,35 @@ def test_bootstrap_repairs_before_dependency_activation(tmp_path, monkeypatch, mclean = {**runtime_environment(), "UV_PYTHON": sys.executable, "UV_OFFLINE": "1"}clean.pop("UV_NO_CONFIG", None)subprocess.run([uv, "lock"], cwd=core, env=clean, capture_output=True, check=True, timeout=60)- engine.sync_venv([], explicit=True, plugin_dirs=[])+ extras = ["startup-extra"]+ engine.sync_venv(extras, explicit=True, plugin_dirs=[])old = selected_venv(core)- shutil.rmtree(site_packages(old))+ recorded = Facts(paths.runtime_facts_path(), strict=True).get("venv")+ assert recorded is not None+ saved_lock = Path(recorded["resolved_lock"]).read_bytes()+ saved_project = Path(recorded["resolved_lock"]).with_name("pyproject.toml").read_bytes()+ old_site = site_packages(old)+ activated_old = tmp_path / "activated-damaged-dependencies"+ if marker_name in {".update-incomplete", ".lazy-refresh-incomplete"}:+ # Partial damage leaves executable .pth hooks behind. Merely succeeding+ # eventually is insufficient: startup must never activate this tree.+ shutil.rmtree(old_site / "startup_dep")+ (old_site / "old_dependency.pth").write_text(+ f"import pathlib; pathlib.Path({str(activated_old)!r}).touch()\n", encoding="utf-8",+ )+ else:+ shutil.rmtree(old_site)if marker_name == "baseline":from pm.features import write_features# A shipped baseline has its feature declaration but no mutable selection.paths.runtime_facts_path().unlink()- write_features([], tmp_path)+ write_features(extras, tmp_path)+ else:+ # Recovery must replay the saved workspace and lock, not discover a new+ # graph from broken/changed live inputs or silently lose recorded extras.+ (core / "pyproject.toml").write_text("broken [project\n", encoding="utf-8")+ (core / "uv.lock").write_text("broken lock [\n", encoding="utf-8")marker = core / (".update-incomplete" if marker_name in {"manual", "baseline"} else marker_name) if marker_name else Noneif marker:marker.write_text('{"attempts":3}' if marker_name == "manual" else '{"attempts":0}', encoding="utf-8")@@ -101,12 +134,35 @@ def test_bootstrap_repairs_before_dependency_activation(tmp_path, monkeypatch, mlock.save()launcher = core / "launch.py"launcher.write_text(- 'import hermes_bootstrap\nimport startup_dep\nprint("APP_STARTED", startup_dep.__version__)\n',+ 'import importlib.util, json\n'+ 'assert importlib.util.find_spec("startup_dep") is None\n'+ 'import hermes_bootstrap\nimport startup_dep\n'+ 'print(json.dumps({"version": startup_dep.__version__, "file": startup_dep.__file__}))\n',encoding="utf-8",)- env = {**os.environ, "PYTHONPATH": str(core)}+ env = {**os.environ, "PYTHONPATH": str(core), "HERMES_PYTHON_SRC_ROOT": str(core)}env.pop("PYTEST_CURRENT_TEST", None) # this child owns an isolated copied installation+ control = subprocess.run(+ [sys.executable, "-S", "-c", f"import site; site.addsitedir({str(old_site)!r}); import startup_dep"],+ cwd=tmp_path, env=env, capture_output=True, text=True, timeout=30,+ )+ assert control.returncode != 0 and "No module named 'startup_dep'" in control.stderr+ if old_site.is_dir():+ assert activated_old.is_file(), "positive control did not execute the old activation hook"+ activated_old.unlink()+ receipts = home / "logs" / "update_receipts"+ before_receipts = set(receipts.glob("pm_*.json"))if marker_name == "manual":+ assert marker is not None+ refused = subprocess.run(+ [sys.executable, "-S", str(launcher)], cwd=tmp_path,+ env=env, capture_output=True, text=True, timeout=90,+ )+ assert refused.returncode != 0+ assert "retry limit reached" in refused.stderr+ assert selected_venv(core) == old+ assert marker.exists()+ assert set(receipts.glob("pm_*.json")) == before_receiptsrepaired = subprocess.run([sys.executable, "-S", "-m", "pm.cli", "repair"], cwd=tmp_path,env=env, capture_output=True, text=True, timeout=90)assert repaired.returncode == 0, repaired.stdout + repaired.stderr@@ -117,9 +173,38 @@ def test_bootstrap_repairs_before_dependency_activation(tmp_path, monkeypatch, mencoding="utf-8", timeout=90,)assert result.returncode == 0, result.stdout + result.stderr- assert result.stdout.strip() == "APP_STARTED 1.0"+ output = json.loads(result.stdout)+ assert output["version"] == "1.0"+ selected = selected_venv(core)+ assert Path(output["file"]).is_relative_to(site_packages(selected))+ assert not activated_old.exists(), "damaged dependencies activated before repair"assert marker is None or not marker.exists()- assert selected_venv(core) != old+ assert selected != oldassert old.is_dir()+ repaired_fact = Facts(paths.runtime_facts_path(), strict=True).get("venv")+ assert repaired_fact is not None+ assert repaired_fact["extras"] == extras+ assert Path(repaired_fact["environment"]) == selected+ repaired_lock = Path(repaired_fact["resolved_lock"])+ assert repaired_lock.read_bytes() == saved_lock+ assert repaired_lock.with_name("pyproject.toml").read_bytes() == saved_project+ receipt_path, = set(receipts.glob("pm_*.json")) - before_receipts+ receipt = json.loads(receipt_path.read_text(encoding="utf-8"))+ assert receipt["outcome"] == "ok"+ assert receipt["venv_rebuild"]["ok"] is True+ assert receipt["feature_list"] == extrasif marker_name != "manual":assert "repaired" in result.stderr.lower()++ # A completed repair is durable. The next bare launch must not run PM again+ # or replace the selection (even though the live manifests remain broken).+ facts_bytes = paths.runtime_facts_path().read_bytes()+ completed_receipts = set(receipts.glob("pm_*.json"))+ again = subprocess.run(+ [sys.executable, "-S", str(launcher)], cwd=tmp_path,+ env=env, capture_output=True, text=True, encoding="utf-8", timeout=90,+ )+ assert again.returncode == 0, again.stdout + again.stderr+ assert json.loads(again.stdout) == output+ assert paths.runtime_facts_path().read_bytes() == facts_bytes+ assert set(receipts.glob("pm_*.json")) == completed_receiptsdiff --git a/tests/test_source_launcher_stages.py b/tests/test_source_launcher_stages.pyindex c88b2d34703..19729a59718 100644--- a/tests/test_source_launcher_stages.py+++ b/tests/test_source_launcher_stages.py@@ -2,9 +2,9 @@import jsonimport osfrom pathlib import Path+import shleximport shutilimport subprocess-import sysimport pytest@@ -16,6 +16,46 @@ from tests.hermes_cli.test_source_launcher_publication import fixture_treeROOT = Path(__file__).resolve().parents[1]+def bootstrap_inputs(repo):+ # Both pre-Python readers need the real lock shape, including artifact+ # objects (an empty inline {} does not exercise their brace tracking).+ (repo / 'pm').mkdir()+ for name in ('lock.json', 'artifact-mirror.json'):+ shutil.copy2(ROOT / 'pm' / name, repo / 'pm' / name)+ lock = Lockfile(repo / 'pm/lock.json')+ uv_version, py_version = lock.version('uv'), lock.version('python')+ assert uv_version and py_version+ return uv_version, '.'.join(py_version.split('+')[0].split('.')[:2])+++def shell_bootstrap(repo, home, interpreter):+ uv_version, py_version = bootstrap_inputs(repo)+ entry = home / 'tools' / f'uv-{uv_version}-{current_target()}'+ entry.mkdir()+ calls = home / 'uv-calls'+ uv = entry / ('uv.exe' if os.name == 'nt' else 'uv')+ # Only acquisition is replaced: the real stages still parse the pin, run+ # bootstrap Python, and invoke the unmodified shared launcher writer.+ uv.write_text(+ '#!/usr/bin/env bash\nset -eu\n'+ f'printf \'%s\\n\' "$*" >> {shlex.quote(calls.as_posix())}\n'+ 'case "$*" in\n'+ f' --version) printf \'%s\\n\' "uv {uv_version}" ;;\n'+ f' "python install --no-bin {py_version}") test -x {shlex.quote(interpreter.as_posix())} ;;\n'+ f' "python find --managed-python {py_version}") printf \'%s\\n\' {shlex.quote(interpreter.as_posix())} ;;\n'+ ' *) printf \'unexpected bootstrap uv call: %s\\n\' "$*" >&2; exit 91 ;;\n'+ 'esac\n', encoding='utf-8',+ )+ uv.chmod(0o755)+ # Fail closed if a fixture regression tries the installer's download path.+ curl = entry / 'curl'+ curl.write_text('#!/usr/bin/env bash\necho "unexpected bootstrap download" >&2\nexit 91\n',+ encoding='utf-8')+ curl.chmod(0o755)+ return entry, calls, [f'python install --no-bin {py_version}',+ f'python find --managed-python {py_version}']++def selected_environment(repo, value=11):selected = install_state_dir(repo) / 'environments/ready/venv'site = site_packages(selected)@@ -31,22 +71,20 @@ def test_developer_setup_publishes_without_a_checkout_venv(tmp_path, monkeypatchrepo, home, interpreter = fixture_tree(tmp_path, monkeypatch)shutil.copy2(ROOT / 'setup-hermes.sh', repo / 'setup-hermes.sh')store = home / 'tools'- uv = Path(shutil.which('uv') or pytest.fail('canonical test environment needs uv'))- version = Lockfile(ROOT / 'pm/lock.json').version('uv')- entry = store / f'uv-{version}-{current_target()}'- entry.mkdir()- shutil.copy2(uv, entry / ('uv.exe' if os.name == 'nt' else 'uv'))- (repo / 'pm').mkdir()+ entry, calls, expected_calls = shell_bootstrap(repo, home, interpreter)(repo / 'pm/__init__.py').write_text('', encoding='utf-8')# Stop at PM's install boundary; the launcher writer and boot selection stay real.- (repo / 'pm/cli.py').write_text('', encoding='utf-8')- lock = Lockfile(repo / 'pm/lock.json')- lock.set_pin('uv', version, {})- lock.set_pin('python', '.'.join(map(str, sys.version_info[:2])), {})- lock.save()+ receipt = repo / 'pm-install.json'+ (repo / 'pm/cli.py').write_text(+ 'import json, pathlib, sys\n'+ "assert sys.argv[1:] == ['install'], sys.argv\n"+ f'pathlib.Path({str(receipt)!r}).write_text(json.dumps(sys.argv[1:]), encoding="utf-8")\n',+ encoding='utf-8',+ )selected_environment(repo)env = dict(os.environ, HOME=str(tmp_path / 'shell-home'), HERMES_HOME=str(home),- HERMES_RUNTIME_DIR=str(store), UV_OFFLINE='1', UV_PYTHON_DOWNLOADS='never')+ HERMES_RUNTIME_DIR=str(store), UV_OFFLINE='1', UV_PYTHON_DOWNLOADS='never',+ PATH=os.pathsep.join([str(entry), os.environ['PATH']]))env.pop('UV_PYTHON_INSTALL_DIR', None)env.pop('PYTHONHOME', None)env.pop('PYTHONPATH', None)@@ -57,6 +95,8 @@ def test_developer_setup_publishes_without_a_checkout_venv(tmp_path, monkeypatchprint(result.stdout.decode('utf-8', errors='replace'))print(result.stderr.decode('utf-8', errors='backslashreplace'))assert result.returncode == 0, result.stdout + result.stderr+ assert calls.read_text(encoding='utf-8').splitlines() == ['--version', *expected_calls]+ assert json.loads(receipt.read_text(encoding='utf-8')) == ['install']out = home / 'bin' if os.name == 'nt' else Path(env['HOME']) / '.local/bin'launchers = list(out.glob('hermes*')) if out.exists() else []assert launchers, result.stdout + result.stderr@@ -76,16 +116,14 @@ def test_developer_setup_publishes_without_a_checkout_venv(tmp_path, monkeypatch@pytest.mark.platforms("windows", "posix")def test_shell_installer_path_stage_uses_shared_publication(tmp_path, monkeypatch):repo, home, interpreter = fixture_tree(tmp_path, monkeypatch)- (repo / 'pm').mkdir()- lock = Lockfile(repo / 'pm/lock.json')- lock.set_pin('python', '.'.join(map(str, sys.version_info[:2])), {})- lock.save()+ entry, calls, expected_calls = shell_bootstrap(repo, home, interpreter)selected_environment(repo)shell_home = tmp_path / 'shell-home'shell_home.mkdir()env = dict(os.environ, PROBE_SCRIPT=(ROOT / 'scripts/install.sh').as_posix(),PROBE_REPO=repo.as_posix(), PROBE_HOME=home.as_posix(),- PROBE_SHELL_HOME=shell_home.as_posix(), UV_OFFLINE='1', UV_PYTHON_DOWNLOADS='never')+ PROBE_SHELL_HOME=shell_home.as_posix(), UV_OFFLINE='1', UV_PYTHON_DOWNLOADS='never',+ PATH=os.pathsep.join([str(entry), os.environ['PATH']]))env.pop('UV_PYTHON_INSTALL_DIR', None)script = '''source "$PROBE_SCRIPT" --manifest --dir "$PROBE_REPO" --hermes-home "$PROBE_HOME"HOME="$PROBE_SHELL_HOME"@@ -96,6 +134,7 @@ run_stage pathresult = subprocess.run(['bash', '-c', script], cwd=tmp_path, env=env,capture_output=True, timeout=90)assert result.returncode == 0, result.stdout + result.stderr+ assert calls.read_text(encoding='utf-8').splitlines() == expected_callsframes = [json.loads(line) for line in result.stdout.splitlines() if line.startswith(b'{')]assert frames == [{'ok': True, 'stage': 'path', 'skipped': False}]out = shell_home / '.local/bin'@@ -116,15 +155,30 @@ run_stage path@pytest.mark.platforms("windows")def test_powershell_stage_publishes_without_a_checkout_venv(tmp_path, monkeypatch):repo, home, interpreter = fixture_tree(tmp_path, monkeypatch)- (repo / 'pm').mkdir()- lock = Lockfile(repo / 'pm/lock.json')- lock.set_pin('python', '.'.join(map(str, sys.version_info[:2])), {})- lock.save()+ _, py_version = bootstrap_inputs(repo)selected_environment(repo)+ calls = home / 'uv-calls'wrapper = tmp_path / 'stage.ps1'wrapper.write_text('''$ErrorActionPreference = 'Stop'. $env:PROBE_INSTALLER -InstallDir $env:PROBE_REPO -HermesHome $env:PROBE_HOMEInitialize-ResolvedPaths+# Replace acquisition only; Get-BootstrapPython and Stage-Path stay real.+function Get-Uv { return 'Invoke-FixtureUv' }+function Invoke-FixtureUv {+ $call = $args -join ' '+ Add-Content -LiteralPath $env:PROBE_UV_CALLS -Encoding UTF8 -Value $call+ switch -Exact ($call) {+ "python install --no-bin $env:PROBE_PY_VERSION" {+ if (-not (Test-Path -LiteralPath $env:PROBE_PYTHON -PathType Leaf)) { throw 'missing fixture Python' }+ }+ "python find --managed-python --no-project $env:PROBE_PY_VERSION" {+ Write-Output $env:PROBE_PYTHON+ }+ default { throw "unexpected bootstrap uv call: $call" }+ }+ $global:LASTEXITCODE = 0+}+function Invoke-WebRequest { throw 'unexpected bootstrap download' }# Replace only the registry publication edge, never mutate the actual user PATH.function Set-LauncherUserPath([string]$binDir) {if ($binDir -ne (Join-Path $env:PROBE_HOME 'bin')) { throw 'wrong user PATH target' }@@ -138,15 +192,19 @@ exit 0powershell = Path(os.environ['SystemRoot']) / 'System32/WindowsPowerShell/v1.0/powershell.exe'env = dict(os.environ, PROBE_INSTALLER=str(ROOT / 'scripts/install.ps1'),PROBE_REPO=str(repo), PROBE_HOME=str(home), HERMES_HOME=str(tmp_path / 'other-home'),+ PROBE_PY_VERSION=py_version, PROBE_PYTHON=str(interpreter), PROBE_UV_CALLS=str(calls),UV_OFFLINE='1', UV_PYTHON_DOWNLOADS='never')- uv = Path(shutil.which('uv') or pytest.fail('canonical test environment needs uv'))- env['PATH'] = os.pathsep.join([str(uv.parent), str(powershell.parent), str(Path(os.environ['SystemRoot']) / 'System32')])+ env['PATH'] = os.pathsep.join([str(powershell.parent), str(Path(os.environ['SystemRoot']) / 'System32')])env['PATHEXT'] = '.COM;.EXE;.BAT;.CMD'env.pop('UV_PYTHON_INSTALL_DIR', None)result = subprocess.run([str(powershell), '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', str(wrapper)],cwd=tmp_path, env=env, capture_output=True, timeout=90)assert result.returncode == 0, result.stdout + result.stderrassert b'REACHED_PATH_PUBLICATION' in result.stdout+ assert calls.read_text(encoding='utf-8-sig').splitlines() == [+ f'python install --no-bin {py_version}',+ f'python find --managed-python --no-project {py_version}',+ ]for name in ('hermes', 'hermes-acp'):command = home / 'bin' / (name + ('.exe' if (home / 'bin' / (name + '.exe')).is_file() else '.cmd'))child_env = dict(env)