Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
test(cua-driver): consolidate uninstall ownership fixtures
injaneityebf7f95b7085
diff --git a/libs/cua-driver/scripts/tests/_fake_claude_remove.py b/libs/cua-driver/scripts/tests/_fake_claude_remove.pydeleted file mode 100644index fe5ecc1870..0000000000--- a/libs/cua-driver/scripts/tests/_fake_claude_remove.py+++ /dev/null@@ -1,14 +0,0 @@-"""Stand-in for `claude mcp remove NAME`: deletes the entry by name."""--import json-import sys--config_path, name = sys.argv[1], sys.argv[2]-with open(config_path, encoding="utf-8") as handle:- config = json.load(handle)-servers = config.get("mcpServers") or {}-if name not in servers:- raise SystemExit(1)-del servers[name]-with open(config_path, "w", encoding="utf-8") as handle:- json.dump(config, handle)diff --git a/libs/cua-driver/scripts/tests/conftest.py b/libs/cua-driver/scripts/tests/conftest.pyindex 5862446c7a..b3d6de40b6 100644--- a/libs/cua-driver/scripts/tests/conftest.py+++ b/libs/cua-driver/scripts/tests/conftest.py@@ -1,29 +1,67 @@-"""Isolation helpers for release-uninstaller script tests."""+"""Explicit disposable fixtures for release-uninstaller ownership tests."""-from __future__ import annotations+import json+import os+from pathlib import Path+import shlex+import subprocess+import sysimport pytest[email protected](autouse=True)-def isolate_release_process_inspection(request, monkeypatch):- """Keep MCP tests independent of cua-driver processes on the host machine."""-- module = request.module- if not module.__name__.endswith("test_uninstall_claude_mcp"):- return- run = getattr(module, "_run", None)- executable = getattr(module, "_executable", None)- if run is None or executable is None:- return-- def isolated_run(tmp_path, *args, **kwargs):- fake_bin = tmp_path / "fake-bin"- executable(fake_bin / "pgrep", "exit 1")- executable(- fake_bin / "id",- "if [ \"$1\" = -u ]; then printf '1000\\n'; else /usr/bin/id \"$@\"; fi",+REPO_ROOT = Path(__file__).resolve().parents[4]+UNINSTALL = REPO_ROOT / "libs/cua-driver/scripts/uninstall.sh"+++class ReleaseInstall:+ def __init__(self, root):+ self.home = root / "home"+ self.bin = root / "fake-bin"+ self.release = self.home / ".cua-driver/packages/current/cua-driver"+ self.launcher = self.home / ".local/bin/cua-driver"+ self.config = self.home / ".claude.json"+ self.executable(self.release)+ self.launcher.parent.mkdir(parents=True)+ self.launcher.symlink_to(self.release)+ for name, body in {+ "uname": "printf 'Linux\\n'",+ "pgrep": "exit 1",+ "id": 'if [ "$1" = -u ]; then printf "1000\\n"; else /usr/bin/id "$@"; fi',+ "pkill": "exit 0",+ "systemctl": "exit 0",+ }.items():+ self.executable(self.bin / name, body)+ # Real rm semantics, guarded against any removal outside this fixture.+ guard = self.bin / "safe_rm.py"+ guard.write_text(+ "import os, pathlib, sys\n"+ f"root = pathlib.Path({str(root.resolve())!r})\n"+ "for arg in sys.argv[1:]:\n"+ " if arg.startswith('-'): continue\n"+ " parent = pathlib.Path(arg).parent.resolve()\n"+ " assert root == parent or root in parent.parents, arg\n"+ "os.execv('/bin/rm', ['/bin/rm', *sys.argv[1:]])\n")- return run(tmp_path, *args, **kwargs)+ self.executable(self.bin / "rm", f"exec {shlex.quote(sys.executable)} {shlex.quote(str(guard))} \"$@\"")+ self.env = {k: v for k, v in os.environ.items() if not k.startswith("CUA_DRIVER_")}+ self.env.update(HOME=str(self.home), PATH=f"{self.bin}:/usr/bin:/bin")++ @staticmethod+ def executable(path, body="exit 0"):+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(f"#!/bin/sh\n{body}\n", encoding="utf-8")+ path.chmod(0o755)++ def write_config(self, data):+ self.config.write_text(json.dumps(data), encoding="utf-8")+ return self.config++ def run(self, *args, cwd=REPO_ROOT):+ return subprocess.run(["/bin/bash", str(UNINSTALL), *args], cwd=cwd,+ env=self.env, text=True, capture_output=True, check=False)+- monkeypatch.setattr(module, "_run", isolated_run)+def release_install(tmp_path):+ return ReleaseInstall(tmp_path)diff --git a/libs/cua-driver/scripts/tests/test_installer_bash32_syntax.py b/libs/cua-driver/scripts/tests/test_installer_bash32_syntax.pyindex 992c5c5333..9357b3b60e 100644--- a/libs/cua-driver/scripts/tests/test_installer_bash32_syntax.py+++ b/libs/cua-driver/scripts/tests/test_installer_bash32_syntax.py@@ -1,22 +1,7 @@-"""Guard the installer scripts against the bash 3.2 parser on macOS.+"""Parse every installer script with /bin/bash (Bash 3.2 on macOS CI)."""-macOS ships bash 3.2 as ``/bin/bash``. While scanning for the closing paren of-a command substitution, that parser tracks single quotes even inside a quoted-heredoc body, so a lone apostrophe in an embedded Python comment makes the-whole script fail to parse with ``unexpected EOF while looking for matching-')'``. Newer bash parses the same file cleanly, so ``bash -n`` on a Linux CI-runner does not catch it.--These tests therefore pair a syntax check against the system bash (bash 3.2 on-macOS) with a portable structural check that holds on any host: apostrophes in-a heredoc body must be balanced.-"""--from __future__ import annotations--import re-import subprocessfrom pathlib import Path+import subprocessimport pytest@@ -24,54 +9,8 @@ import pytestREPO_ROOT = Path(__file__).resolve().parents[4]SCRIPTS = sorted((REPO_ROOT / "libs/cua-driver/scripts").glob("*.sh"))-HEREDOC_START = re.compile(- r"<<-?\s*(?:'([A-Za-z_][A-Za-z0-9_]*)'"- r"|\"([A-Za-z_][A-Za-z0-9_]*)\""- r"|([A-Za-z_][A-Za-z0-9_]*))"-)---def _heredoc_bodies(text: str) -> list[tuple[int, str, str]]:- """Yield ``(line number, delimiter, body)`` for each heredoc in ``text``."""- lines = text.splitlines()- found: list[tuple[int, str, str]] = []- index = 0- while index < len(lines):- line = lines[index]- match = None if line.lstrip().startswith("#") else HEREDOC_START.search(line)- if match:- delimiter = match.group(1) or match.group(2) or match.group(3)- body: list[str] = []- cursor = index + 1- while cursor < len(lines) and lines[cursor].strip() != delimiter:- body.append(lines[cursor])- cursor += 1- found.append((index + 1, delimiter, "\n".join(body)))- index = cursor- index += 1- return found-@pytest.mark.parametrize("script", SCRIPTS, ids=lambda path: path.name)def test_installer_scripts_parse_with_the_system_bash(script: Path) -> None:- completed = subprocess.run(- ["/bin/bash", "-n", str(script)],- capture_output=True,- text=True,- check=False,- )+ completed = subprocess.run(["/bin/bash", "-n", str(script)], capture_output=True, text=True)assert completed.returncode == 0, completed.stderr--[email protected]("script", SCRIPTS, ids=lambda path: path.name)-def test_heredoc_apostrophes_are_balanced_for_bash32(script: Path) -> None:- unbalanced = [- (line, delimiter)- for line, delimiter, body in _heredoc_bodies(script.read_text(encoding="utf-8"))- if body.count("'") % 2- ]- assert not unbalanced, (- f"{script.name}: heredoc(s) with an unbalanced apostrophe "- f"{unbalanced}; bash 3.2 cannot parse these inside a command "- "substitution. Reword the text to avoid the apostrophe."- )diff --git a/libs/cua-driver/scripts/tests/test_uninstall_claude_mcp.py b/libs/cua-driver/scripts/tests/test_uninstall_claude_mcp.pyindex 953f13ec5e..7ebc80bfa0 100644--- a/libs/cua-driver/scripts/tests/test_uninstall_claude_mcp.py+++ b/libs/cua-driver/scripts/tests/test_uninstall_claude_mcp.py@@ -1,418 +1,112 @@-"""Ownership-safe Claude MCP cleanup in the release uninstaller."""--from __future__ import annotations+"""Ownership and scope contracts through the real release uninstaller."""import json-import osfrom pathlib import Pathimport shlex-import subprocess-import sys---REPO_ROOT = Path(__file__).resolve().parents[4]-UNINSTALL = REPO_ROOT / "libs/cua-driver/scripts/uninstall.sh"---def _executable(path: Path, body: str = "exit 0") -> None:- path.parent.mkdir(parents=True, exist_ok=True)- path.write_text(f"#!/bin/sh\n{body}\n", encoding="utf-8")- path.chmod(0o755)---def _expand(value, *, home: Path, tmp_path: Path):- if isinstance(value, str):- return value.format(home=home, tmp=tmp_path)- if isinstance(value, list):- return [_expand(item, home=home, tmp_path=tmp_path) for item in value]- if isinstance(value, dict):- return {- key: _expand(item, home=home, tmp_path=tmp_path)- for key, item in value.items()- }- return value---def _run(- tmp_path: Path,- config: dict,- *,- rust_marker: bool,- with_claude_cli: bool = False,- create_canonical_launcher: bool = True,- custom_release_launchers: tuple[str, ...] = (),- cwd: str | None = None,-) -> tuple[dict, str]:- """Run the real release uninstaller against a fake HOME."""-- home = tmp_path / "home"- fake_bin = tmp_path / "fake-bin"- (home / ".local/bin").mkdir(parents=True, exist_ok=True)-- release_binary = home / ".cua-driver/packages/current/cua-driver"- if rust_marker:- _executable(release_binary)- if create_canonical_launcher:- (home / ".local/bin/cua-driver").symlink_to(release_binary)- for raw_path in custom_release_launchers:- launcher = Path(raw_path.format(home=home, tmp=tmp_path))- launcher.parent.mkdir(parents=True, exist_ok=True)- launcher.symlink_to(release_binary)-- claude_json = home / ".claude.json"- _executable(fake_bin / "uname", "printf 'Linux\\n'")- _executable(fake_bin / "pkill")- _executable(fake_bin / "systemctl")-- if with_claude_cli:- _executable(- fake_bin / "claude",- f'echo "$@" >> "{tmp_path / "claude-calls"}"\n'- f'[ "$1" = mcp ] && [ "$2" = remove ] || exit 1\n'- f'exec {shlex.quote(sys.executable)} '- f'{shlex.quote(str(Path(__file__).with_name("_fake_claude_remove.py")))} '- f'"{claude_json}" "$3"',- )-- expanded = _expand(config, home=home, tmp_path=tmp_path)- claude_json.write_text(json.dumps(expanded), encoding="utf-8")-- env = os.environ.copy()- for key in list(env):- if key.startswith("CUA_DRIVER_"):- env.pop(key)- env.update({"HOME": str(home), "PATH": f"{fake_bin}:/usr/bin:/bin"})- result = subprocess.run(- ["/bin/bash", str(UNINSTALL)],- cwd=cwd.format(home=home, tmp=tmp_path) if cwd else REPO_ROOT,- env=env,- text=True,- capture_output=True,- check=False,- )+import shutil++import pytest++[email protected]("scope,name,custom", [+ pytest.param("user", "cua-computer-use", False, id="canonical-user"),+ pytest.param("project", "cua-computer-use", False, id="canonical-project"),+ pytest.param("user", "my-driver", False, id="renamed-key"),+ pytest.param("user", "cua-computer-use", True, id="custom-launcher"),+])+def test_owned_registration_is_removed(release_install, tmp_path, scope, name, custom):+ f = release_install+ command = f.launcher+ if custom:+ command = tmp_path / "custom-bin/cua-driver"+ command.parent.mkdir()+ command.symlink_to(f.release)+ servers = {name: {"command": str(command), "args": ["mcp"]},+ "unrelated": {"command": "/usr/bin/other", "args": ["mcp"]}}+ data = {"mcpServers": servers} if scope == "user" else {+ "mcpServers": {}, "projects": {"/work/repo": {"mcpServers": servers}}}+ f.write_config(data)+ result = f.run()assert result.returncode == 0, result.stdout + result.stderr- return json.loads(claude_json.read_text(encoding="utf-8")), result.stdout---def _user_servers(config: dict) -> set[str]:- return set(config["mcpServers"])---def _project_servers(config: dict, project: str = "/work/repo") -> set[str]:- return set(config["projects"][project]["mcpServers"])---def _claude_removals(tmp_path: Path) -> set[str]:- path = tmp_path / "claude-calls"- calls = path.read_text(encoding="utf-8").splitlines() if path.exists() else []- return {- parts[2]- for parts in (call.split() for call in calls)- if parts[:2] == ["mcp", "remove"]- }---def test_release_registration_is_removed(tmp_path: Path) -> None:- config, stdout = _run(- tmp_path,- {- "mcpServers": {- "cua-computer-use": {- "command": "{home}/.local/bin/cua-driver",- "args": ["mcp"],- },- "unrelated": {"command": "/usr/bin/other", "args": ["mcp"]},- }- },- rust_marker=True,- )-- assert _user_servers(config) == {"unrelated"}- assert "removed Claude MCP registration(s): user:cua-computer-use" in stdout---def test_project_release_registration_is_removed(tmp_path: Path) -> None:- config, _ = _run(- tmp_path,- {- "mcpServers": {},- "projects": {- "/work/repo": {- "mcpServers": {- "cua-computer-use": {- "command": "{home}/.local/bin/cua-driver",- "args": ["mcp"],- },- "unrelated": {"command": "/usr/bin/other"},- }- }- },- },- rust_marker=True,- )-- assert _project_servers(config) == {"unrelated"}---def test_renamed_key_is_removed_when_target_is_release_owned(tmp_path: Path) -> None:- config, _ = _run(- tmp_path,- {- "mcpServers": {- "my-driver": {- "command": "{home}/.local/bin/cua-driver",- "args": ["mcp"],- }- }- },- rust_marker=True,- )-- assert _user_servers(config) == set()---def test_shared_name_without_command_is_preserved(tmp_path: Path) -> None:- config, _ = _run(- tmp_path,- {"mcpServers": {"cua-computer-use": {"args": ["mcp"]}}},- rust_marker=True,- )-- assert _user_servers(config) == {"cua-computer-use"}---def test_legacy_name_without_live_target_is_preserved(tmp_path: Path) -> None:- config, _ = _run(- tmp_path,- {- "mcpServers": {- "cua-driver-rs": {- "command": "/x/cua-driver-rs",- "args": ["mcp"],- }- }- },- rust_marker=False,- )-- # A historical name is not current filesystem ownership evidence.- assert _user_servers(config) == {"cua-driver-rs"}---def test_shared_release_name_is_kept_without_rust_marker(tmp_path: Path) -> None:- config, _ = _run(- tmp_path,- {- "mcpServers": {- "cua-computer-use": {- "command": "{home}/.local/bin/cua-driver",- "args": ["mcp"],- }- }- },- rust_marker=False,- )-- assert _user_servers(config) == {"cua-computer-use"}---def test_reported_cua_driver_local_registration_is_preserved(tmp_path: Path) -> None:- """The release uninstaller must not claim the source-built local product."""-- local_launcher = tmp_path / "home/.local/bin/cua-driver-local"- _executable(local_launcher)- config, stdout = _run(- tmp_path,- {- "mcpServers": {- "cua-computer-use": {- "command": "{home}/.local/bin/cua-driver-local",- "args": ["mcp"],- }- }- },- rust_marker=True,- )-- assert _user_servers(config) == {"cua-computer-use"}- assert "preserved local Claude MCP registration(s): user:cua-computer-use" in stdout- assert "uninstall-local.sh" in stdout---def test_same_filename_at_unrelated_path_is_preserved(tmp_path: Path) -> None:- other_launcher = tmp_path / "other/bin/cua-driver"- _executable(other_launcher)- config, _ = _run(- tmp_path,- {- "mcpServers": {- "cua-computer-use": {- "command": "{tmp}/other/bin/cua-driver",- "args": ["mcp"],- }- }- },- rust_marker=True,- )-- assert _user_servers(config) == {"cua-computer-use"}---def test_custom_bin_launcher_is_removed_when_it_resolves_into_release(tmp_path: Path) -> None:- config, _ = _run(- tmp_path,- {- "mcpServers": {- "cua-computer-use": {- "command": "{tmp}/custom-bin/cua-driver",- "args": ["mcp"],- }- }- },- rust_marker=True,- custom_release_launchers=("{tmp}/custom-bin/cua-driver",),- )-- assert _user_servers(config) == set()---def test_missing_canonical_launcher_is_preserved_as_unproven(tmp_path: Path) -> None:- config, _ = _run(- tmp_path,- {- "mcpServers": {- "cua-computer-use": {- "command": "{home}/.local/bin/cua-driver",- "args": ["mcp"],- }- }- },- rust_marker=True,- create_canonical_launcher=False,- )-- # Deliberately narrower than the contributor fallback: no live target.- assert _user_servers(config) == {"cua-computer-use"}---def test_foreign_dangling_canonical_launcher_is_preserved(tmp_path: Path) -> None:- launcher = tmp_path / "home/.local/bin/cua-driver"- foreign_target = tmp_path / "other-install/bin/cua-driver"- launcher.parent.mkdir(parents=True, exist_ok=True)- launcher.symlink_to(foreign_target)-- config, _ = _run(- tmp_path,- {- "mcpServers": {- "cua-computer-use": {- "command": "{home}/.local/bin/cua-driver",- "args": ["mcp"],- }- }- },- rust_marker=True,- create_canonical_launcher=False,- )-- assert _user_servers(config) == {"cua-computer-use"}- assert launcher.is_symlink()- assert launcher.readlink() == foreign_target---def test_relative_command_is_not_owned_by_the_uninstaller_cwd(tmp_path: Path) -> None:- """A relative command is resolved by Claude, not by the uninstaller.-- Running from inside the release package tree must not turn an unrelated- project's ./cua-driver into release-owned evidence.- """-- config, _ = _run(- tmp_path,- {- "projects": {- "/work/repo": {- "mcpServers": {- "cua-computer-use": {- "command": "./cua-driver",- "args": ["mcp"],- }- }- }- }- },- rust_marker=True,- cwd="{home}/.cua-driver/packages/current",- )-- assert _project_servers(config) == {"cua-computer-use"}---def test_scope_ownership_does_not_leak_to_same_name_in_project(tmp_path: Path) -> None:- other_launcher = tmp_path / "other/bin/cua-driver"- _executable(other_launcher)- config, _ = _run(- tmp_path,- {- "mcpServers": {- "cua-computer-use": {- "command": "{home}/.local/bin/cua-driver",- "args": ["mcp"],- }- },- "projects": {- "/work/repo": {- "mcpServers": {- "cua-computer-use": {- "command": "{tmp}/other/bin/cua-driver",- "args": ["mcp"],- }- }- }- },- },- rust_marker=True,- with_claude_cli=True,- )-- assert _user_servers(config) == set()- assert _project_servers(config) == {"cua-computer-use"}- assert _claude_removals(tmp_path) == set()---def test_no_name_only_cli_fallback(tmp_path: Path) -> None:- _run(- tmp_path,- {"mcpServers": {}},- rust_marker=True,- with_claude_cli=True,- )-- assert _claude_removals(tmp_path) == set()---def test_shared_name_never_enters_cli_fallback_after_json_scrub(tmp_path: Path) -> None:- _run(- tmp_path,- {- "mcpServers": {- "cua-computer-use": {- "command": "{home}/.local/bin/cua-driver",- "args": ["mcp"],- }- }- },- rust_marker=True,- with_claude_cli=True,- )-- assert _claude_removals(tmp_path) == set()---def test_windows_guidance_uses_registered_user_scope() -> None:- script = (REPO_ROOT / "libs/cua-driver/scripts/uninstall.ps1").read_text(- encoding="utf-8-sig"- )-- assert "claude mcp remove cua-computer-use -s user" in script- assert "claude mcp remove cua-driver-rs -s user" in script+ actual = json.loads(f.config.read_text())+ remaining = actual["mcpServers"] if scope == "user" else actual["projects"]["/work/repo"]["mcpServers"]+ assert remaining == {"unrelated": servers["unrelated"]}+ assert not f.release.exists()+ if scope == "user" and name == "cua-computer-use" and not custom:+ assert "removed Claude MCP registration(s): user:cua-computer-use" in result.stdout++[email protected]("case", [+ "missing-command", "legacy-without-marker", "shared-without-marker",+ "local-product", "foreign-filename", "missing-launcher", "foreign-dangling",+])+def test_unproven_registration_is_preserved(release_install, tmp_path, case):+ f = release_install+ command, name = f.launcher, "cua-computer-use"+ if case.endswith("without-marker"):+ f.launcher.unlink()+ shutil.rmtree(f.home / ".cua-driver")+ if case == "legacy-without-marker":+ command, name = Path("/x/cua-driver-rs"), "cua-driver-rs"+ elif case == "local-product":+ command = f.home / ".local/bin/cua-driver-local"+ f.executable(command)+ elif case == "foreign-filename":+ command = tmp_path / "other/bin/cua-driver"+ f.executable(command)+ elif case in ("missing-launcher", "foreign-dangling"):+ f.launcher.unlink()+ if case == "foreign-dangling":+ foreign = tmp_path / "other-install/bin/cua-driver"+ f.launcher.symlink_to(foreign)+ server = {"args": ["mcp"]}+ if case != "missing-command":+ server["command"] = str(command)+ original = {"mcpServers": {name: server}}+ f.write_config(original)+ result = f.run()+ assert result.returncode == 0, result.stdout + result.stderr+ assert json.loads(f.config.read_text()) == original+ if case == "local-product":+ assert "preserved local Claude MCP registration(s): user:cua-computer-use" in result.stdout+ assert "uninstall-local.sh" in result.stdout+ assert command.exists()+ elif case == "foreign-filename":+ assert command.exists()+ elif case == "foreign-dangling":+ assert f.launcher.is_symlink() and f.launcher.readlink() == foreign+++def test_relative_command_is_not_owned_by_the_uninstaller_cwd(release_install):+ f = release_install+ original = {"projects": {"/work/repo": {"mcpServers": {+ "cua-computer-use": {"command": "./cua-driver", "args": ["mcp"]}}}}}+ f.write_config(original)+ result = f.run(cwd=f.release.parent)+ assert result.returncode == 0, result.stdout + result.stderr+ assert json.loads(f.config.read_text()) == original++[email protected]("case", ["empty-config", "owned-user", "foreign-project-same-name"])+def test_no_name_only_cli_fallback(release_install, tmp_path, case):+ f = release_install+ calls = tmp_path / "claude-calls"+ # Any invocation fails the assertion; no fake JSON editor is necessary.+ f.executable(f.bin / "claude", f'printf "%s\\n" "$*" >> {shlex.quote(str(calls))}')+ original = {"mcpServers": {}}+ if case != "empty-config":+ original["mcpServers"]["cua-computer-use"] = {"command": str(f.launcher), "args": ["mcp"]}+ if case == "foreign-project-same-name":+ foreign = tmp_path / "other/bin/cua-driver"+ f.executable(foreign)+ original["projects"] = {"/work/repo": {"mcpServers": {+ "cua-computer-use": {"command": str(foreign), "args": ["mcp"]}}}}+ f.write_config(original)+ result = f.run()+ assert result.returncode == 0, result.stdout + result.stderr+ actual = json.loads(f.config.read_text())+ assert actual["mcpServers"] == {}+ if case == "foreign-project-same-name":+ assert actual["projects"] == original["projects"]+ assert foreign.exists()+ assert not calls.exists(), "uninstaller invoked Claude CLI without per-entry ownership proof"diff --git a/libs/cua-driver/scripts/tests/test_uninstall_claude_mcp_no_python.py b/libs/cua-driver/scripts/tests/test_uninstall_claude_mcp_no_python.pyindex ddacf513fd..7e79daad1d 100644--- a/libs/cua-driver/scripts/tests/test_uninstall_claude_mcp_no_python.py+++ b/libs/cua-driver/scripts/tests/test_uninstall_claude_mcp_no_python.py@@ -1,64 +1,16 @@-"""Regression coverage for safe MCP cleanup when Python is unavailable."""--from __future__ import annotations+"""Missing Python must fail before release or configuration mutation."""import json-import os-from pathlib import Path-import subprocess---REPO_ROOT = Path(__file__).resolve().parents[4]-UNINSTALL = REPO_ROOT / "libs/cua-driver/scripts/uninstall.sh"---def _executable(path: Path, body: str) -> None:- path.parent.mkdir(parents=True, exist_ok=True)- path.write_text(f"#!/bin/sh\n{body}\n", encoding="utf-8")- path.chmod(0o755)---def test_claude_config_requires_python_before_release_is_mutated(tmp_path: Path) -> None:- home = tmp_path / "home"- fake_bin = tmp_path / "fake-bin"- release_binary = home / ".cua-driver/packages/current/cua-driver"- release_binary.parent.mkdir(parents=True, exist_ok=True)- _executable(release_binary, "exit 0")-- launcher = home / ".local/bin/cua-driver"- launcher.parent.mkdir(parents=True, exist_ok=True)- launcher.symlink_to(release_binary)-- claude_json = home / ".claude.json"- original = {- "mcpServers": {- "cua-computer-use": {- "command": str(launcher),- "args": ["mcp"],- }- }- }- claude_json.write_text(json.dumps(original), encoding="utf-8")-- _executable(fake_bin / "uname", "printf 'Linux\\n'")- _executable(- fake_bin / "id",- "if [ \"$1\" = -u ]; then printf '1000\\n'; else exit 1; fi",- )- env = os.environ.copy()- env.update({"HOME": str(home), "PATH": str(fake_bin)})- result = subprocess.run(- ["/bin/bash", str(UNINSTALL)],- cwd=REPO_ROOT,- env=env,- text=True,- capture_output=True,- check=False,- )+def test_claude_config_requires_python_before_release_is_mutated(release_install):+ f = release_install+ original = {"mcpServers": {"cua-computer-use": {"command": str(f.launcher), "args": ["mcp"]}}}+ f.write_config(original)+ f.env["PATH"] = str(f.bin)+ result = f.run()assert result.returncode != 0assert "python3 is required to safely inspect Claude MCP ownership" in result.stderr- assert json.loads(claude_json.read_text(encoding="utf-8")) == original- assert release_binary.exists()- assert launcher.is_symlink()+ assert json.loads(f.config.read_text()) == original+ assert f.release.exists()+ assert f.launcher.is_symlink()diff --git a/libs/cua-driver/scripts/tests/test_uninstall_claude_mcp_safety.py b/libs/cua-driver/scripts/tests/test_uninstall_claude_mcp_safety.pyindex d4b48f4cd8..7dc7a2b6aa 100644--- a/libs/cua-driver/scripts/tests/test_uninstall_claude_mcp_safety.py+++ b/libs/cua-driver/scripts/tests/test_uninstall_claude_mcp_safety.py@@ -1,79 +1,15 @@-"""Regression coverage for release-uninstaller Claude MCP safety gaps."""--from __future__ import annotations+"""Effect-based regressions for release-uninstaller Claude MCP safety."""import json-import osfrom pathlib import Path-import subprocess-import shleximport sysimport pytest-REPO_ROOT = Path(__file__).resolve().parents[4]-UNINSTALL = REPO_ROOT / "libs/cua-driver/scripts/uninstall.sh"---def _executable(path: Path, body: str = "exit 0") -> None:- path.parent.mkdir(parents=True, exist_ok=True)- path.write_text(f"#!/bin/sh\n{body}\n", encoding="utf-8")- path.chmod(0o755)---def _release_fixture(tmp_path: Path, *, pgrep_body: str = "exit 1") -> tuple[Path, Path, Path, dict[str, str]]:- home = tmp_path / "home"- fake_bin = tmp_path / "fake-bin"- release_binary = home / ".cua-driver/packages/current/cua-driver"- _executable(release_binary)-- launcher = home / ".local/bin/cua-driver"- launcher.parent.mkdir(parents=True, exist_ok=True)- launcher.symlink_to(release_binary)-- _executable(fake_bin / "uname", "printf 'Linux\\n'")- _executable(fake_bin / "pgrep", pgrep_body)- _executable(- fake_bin / "id",- "if [ \"$1\" = -u ]; then printf '1000\\n'; else /usr/bin/id \"$@\"; fi",- )- _executable(fake_bin / "pkill")- _executable(fake_bin / "systemctl")-- # Preserve real rm semantics, but never allow a fixture to remove host state.- _executable(fake_bin / "rm", f"exec {shlex.quote(sys.executable)} {shlex.quote(str(fake_bin / 'safe_rm.py'))} \"$@\"")- (fake_bin / "safe_rm.py").write_text(- "import os, pathlib, sys\n"- f"root = pathlib.Path({str(tmp_path.resolve())!r})\n"- "for arg in sys.argv[1:]:\n"- " if arg.startswith('-'): continue\n"- " path = pathlib.Path(arg)\n"- " assert root == path.parent.resolve() or root in path.parent.resolve().parents, arg\n"- "os.execv('/bin/rm', ['/bin/rm', *sys.argv[1:]])\n"- )- env = os.environ.copy()- for key in list(env):- if key.startswith("CUA_DRIVER_"):- env.pop(key)- env.update({"HOME": str(home), "PATH": f"{fake_bin}:/usr/bin:/bin"})- return home, release_binary, launcher, env---def _run(env: dict[str, str], *args: str) -> subprocess.CompletedProcess[str]:- return subprocess.run(- ["/bin/bash", str(UNINSTALL), *args],- cwd=REPO_ROOT,- env=env,- text=True,- capture_output=True,- check=False,- )---def test_legacy_substring_in_unrelated_argument_is_preserved(tmp_path: Path) -> None:- home, _, _, env = _release_fixture(tmp_path)- claude_json = home / ".claude.json"+def test_legacy_substring_in_unrelated_argument_is_preserved(release_install, tmp_path: Path) -> None:+ f = release_install+ claude_json = f.home / ".claude.json"original = {"mcpServers": {"notes-server": {@@ -84,98 +20,90 @@ def test_legacy_substring_in_unrelated_argument_is_preserved(tmp_path: Path) ->}claude_json.write_text(json.dumps(original), encoding="utf-8")- result = _run(env)+ result = f.run()assert result.returncode == 0, result.stdout + result.stderrassert json.loads(claude_json.read_text(encoding="utf-8")) == original-def test_malformed_claude_config_fails_before_release_or_daemon_mutation(tmp_path: Path) -> None:+def test_malformed_claude_config_fails_before_release_or_daemon_mutation(release_install, tmp_path: Path) -> None:pgrep_marker = tmp_path / "pgrep-called"- home, release_binary, launcher, env = _release_fixture(- tmp_path,- pgrep_body=f"printf called > {pgrep_marker}; exit 1",- )- claude_json = home / ".claude.json"+ f = release_install+ f.executable(f.bin / "pgrep", f"printf called > {pgrep_marker}; exit 1")+ claude_json = f.home / ".claude.json"malformed = '{"mcpServers":'claude_json.write_text(malformed, encoding="utf-8")- result = _run(env)+ result = f.run()assert result.returncode != 0assert "could not read Claude config" in result.stderrassert claude_json.read_text(encoding="utf-8") == malformed- assert release_binary.exists()- assert launcher.is_symlink()+ assert f.release.exists()+ assert f.launcher.is_symlink()assert not pgrep_marker.exists(), "daemon inspection ran before Claude config validation"assert "cua-driver uninstalled." not in result.stdout-def _config(home: Path, servers: dict) -> Path:- path = home / ".claude.json"- path.write_text(json.dumps({"mcpServers": servers}))- return path--@pytest.mark.parametrize("owned", [False, True])-def test_original_symlink_dotdot_command_controls_ownership(tmp_path: Path, owned: bool) -> None:- home, release, _, env = _release_fixture(tmp_path)+def test_original_symlink_dotdot_command_controls_ownership(release_install, tmp_path: Path, owned: bool) -> None:+ f = release_installnormal, other = tmp_path / "normal", tmp_path / "other"normal.mkdir()(other / "child").mkdir(parents=True)(normal / "jump").symlink_to(other / "child", target_is_directory=True)foreign = (normal if owned else other) / "cua-driver"- _executable(foreign)- ((other if owned else normal) / "cua-driver").symlink_to(release)+ f.executable(foreign)+ ((other if owned else normal) / "cua-driver").symlink_to(f.release)command = str(normal / "jump") + "/../cua-driver"- assert Path(command).samefile(release if owned else foreign)- config = _config(home, {"entry": {"command": command}})- result = _run(env)+ assert Path(command).samefile(f.release if owned else foreign)+ config = f.write_config({"mcpServers": {"entry": {"command": command}}})+ result = f.run()assert result.returncode == 0, result.stdout + result.stderrassert ("entry" in json.loads(config.read_text())["mcpServers"]) is not ownedassert foreign.exists()- assert not release.exists()+ assert not f.release.exists()assert Path(command).exists() is not owned@pytest.mark.parametrize("purge", [False, True])-def test_selected_home_symlink_matches_actual_removal(tmp_path: Path, purge: bool) -> None:- home, _, launcher, env = _release_fixture(tmp_path)+def test_selected_home_symlink_matches_actual_removal(release_install, tmp_path: Path, purge: bool) -> None:+ f = release_installactual = tmp_path / "actual-home"- release = actual / "packages/current/cua-driver"- _executable(release)+ external_release = actual / "packages/current/cua-driver"+ f.executable(external_release)selected = tmp_path / "selected-home"selected.symlink_to(actual, target_is_directory=True)- env["CUA_DRIVER_HOME"] = str(selected)- config = _config(home, {"entry": {"command": str(release)}})- result = _run(env, *(('--purge',) if purge else ()))+ f.env["CUA_DRIVER_HOME"] = str(selected)+ config = f.write_config({"mcpServers": {"entry": {"command": str(external_release)}}})+ result = f.run(*(('--purge',) if purge else ()))assert result.returncode == 0, result.stdout + result.stderrassert ("entry" in json.loads(config.read_text())["mcpServers"]) is purge- assert release.exists() is purge+ assert external_release.exists() is purgeassert selected.is_symlink() is not purge- assert launcher.exists() # the other installation remains+ assert f.launcher.exists() # the other installation remains-def test_linux_does_not_claim_app_or_foreign_legacy_name(tmp_path: Path) -> None:- home, _, _, env = _release_fixture(tmp_path)+def test_linux_does_not_claim_app_or_foreign_legacy_name(release_install, tmp_path: Path) -> None:+ f = release_installforeign = tmp_path / "foreign"- _executable(foreign)+ f.executable(foreign)original = {"cua-driver-rs": {"command": str(foreign)},"mac-release": {"command": "/Applications/CuaDriver.app/Contents/MacOS/cua-driver"},"legacy-app": {"command": "/Applications/CuaDriverRs.app/Contents/MacOS/cua-driver"},}- config = _config(home, original)- result = _run(env)+ config = f.write_config({"mcpServers": original})+ result = f.run()assert result.returncode == 0, result.stdout + result.stderrassert json.loads(config.read_text())["mcpServers"] == originalassert foreign.exists()@pytest.mark.parametrize("operation", ["backup", "replace"])-def test_config_write_failure_preserves_release(tmp_path: Path, operation: str) -> None:- home, release, launcher, env = _release_fixture(tmp_path)- config = _config(home, {"entry": {"command": str(release)}})+def test_config_write_failure_preserves_release(release_install, tmp_path: Path, operation: str) -> None:+ f = release_install+ config = f.write_config({"mcpServers": {"entry": {"command": str(f.release)}}})before = config.read_bytes()fake_bin = tmp_path / "fake-bin"# Fault injection stays at the existing python process seam, not in production.@@ -189,140 +117,140 @@ def test_config_write_failure_preserves_release(tmp_path: Path, operation: str)+ "exec(compile(sys.stdin.read(), '<uninstaller>', 'exec'))\n")wrapper.chmod(0o755)- result = _run(env)+ result = f.run()assert result.returncode != 0assert "fixture write failure" in result.stderrassert config.read_bytes() == before- assert release.exists() and launcher.exists()- assert not list(home.glob(".claude.json.*.tmp"))- backups = list(home.glob(".claude.json.bak-*"))+ assert f.release.exists() and f.launcher.exists()+ assert not list(f.home.glob(".claude.json.*.tmp"))+ backups = list(f.home.glob(".claude.json.bak-*"))if operation == "replace":assert len(backups) == 1 and backups[0].read_bytes() == before-def test_failed_history_purge_preserves_registration_and_launcher(tmp_path: Path) -> None:- home, release, launcher, env = _release_fixture(tmp_path)- _executable(release, "exit 1")- config = _config(home, {"entry": {"command": str(release)}})+def test_failed_history_purge_preserves_registration_and_launcher(release_install, tmp_path: Path) -> None:+ f = release_install+ f.executable(f.release, "exit 1")+ config = f.write_config({"mcpServers": {"entry": {"command": str(f.release)}}})before = config.read_bytes()- result = _run(env, "--purge")+ result = f.run("--purge")assert result.returncode != 0assert "history_purge_incomplete" in result.stderrassert config.read_bytes() == before- assert release.exists() and launcher.exists()+ assert f.release.exists() and f.launcher.exists()-def test_lexical_root_is_not_alternative_ownership_evidence(tmp_path: Path) -> None:- home, release, _, env = _release_fixture(tmp_path)+def test_lexical_root_is_not_alternative_ownership_evidence(release_install, tmp_path: Path) -> None:+ f = release_installforeign = tmp_path / "foreign/packages/cua-driver"- _executable(foreign)+ f.executable(foreign)(tmp_path / "foreign/child").mkdir()- jump = home / ".cua-driver/jump"+ jump = f.home / ".cua-driver/jump"jump.symlink_to(tmp_path / "foreign/child", target_is_directory=True)command = str(jump) + "/../packages/cua-driver"assert Path(command).samefile(foreign)- config = _config(home, {"entry": {"command": command}})+ config = f.write_config({"mcpServers": {"entry": {"command": command}}})before = config.read_bytes()- result = _run(env)+ result = f.run()assert result.returncode == 0, result.stdout + result.stderrassert config.read_bytes() == beforeassert Path(command).samefile(foreign)- assert not release.exists()+ assert not f.release.exists()-def test_final_packages_symlink_is_unlinked_not_traversed(tmp_path: Path) -> None:- home, release, _, env = _release_fixture(tmp_path)- packages = home / ".cua-driver/packages"+def test_final_packages_symlink_is_unlinked_not_traversed(release_install, tmp_path: Path) -> None:+ f = release_install+ packages = f.home / ".cua-driver/packages"external = tmp_path / "external-packages"packages.rename(external)packages.symlink_to(external, target_is_directory=True)foreign = external / "current/cua-driver"- config = _config(home, {"entry": {"command": str(foreign)}})+ config = f.write_config({"mcpServers": {"entry": {"command": str(foreign)}}})before = config.read_bytes()- result = _run(env)+ result = f.run()assert result.returncode == 0, result.stdout + result.stderrassert config.read_bytes() == beforeassert foreign.exists()assert not packages.is_symlink()- assert not release.exists()+ assert not f.release.exists()@pytest.mark.parametrize("suffix", ["/", "/.", "/..", "/../.cua-driver"])-def test_ambiguous_purge_operand_fails_before_mutation(tmp_path: Path, suffix: str) -> None:+def test_ambiguous_purge_operand_fails_before_mutation(release_install, tmp_path: Path, suffix: str) -> None:marker = tmp_path / "process-inspection"- home, release, launcher, env = _release_fixture(tmp_path, pgrep_body=f"touch {marker}; exit 1")- config = _config(home, {"entry": {"command": str(release)}})+ f = release_install+ f.executable(f.bin / "pgrep", f"touch {marker}; exit 1")+ config = f.write_config({"mcpServers": {"entry": {"command": str(f.release)}}})before = config.read_bytes()- env["CUA_DRIVER_HOME"] = str(home / ".cua-driver") + suffix- result = _run(env, "--purge")+ f.env["CUA_DRIVER_HOME"] = str(f.home / ".cua-driver") + suffix+ result = f.run("--purge")assert result.returncode != 0assert "unsafe release removal operand" in result.stderrassert config.read_bytes() == before- assert release.exists() and launcher.exists()+ assert f.release.exists() and f.launcher.exists()assert not marker.exists()-def test_original_missing_component_and_dangling_target_are_preserved(tmp_path: Path) -> None:- home, release, launcher, env = _release_fixture(tmp_path)+def test_original_missing_component_and_dangling_target_are_preserved(release_install, tmp_path: Path) -> None:+ f = release_installdangling = tmp_path / "dangling"- dangling.symlink_to(release.parent / "missing")+ dangling.symlink_to(f.release.parent / "missing")original = {- "missing-step": {"command": str(release.parent / "missing") + "/../cua-driver"},+ "missing-step": {"command": str(f.release.parent / "missing") + "/../cua-driver"},"owned-looking-dangling": {"command": str(dangling)},"tilde": {"command": "~/.local/bin/cua-driver"},}- config = _config(home, original)+ config = f.write_config({"mcpServers": original})before = config.read_bytes()- result = _run(env)+ result = f.run()assert result.returncode == 0, result.stdout + result.stderrassert config.read_bytes() == before- assert not release.exists() and not launcher.exists()+ assert not f.release.exists() and not f.launcher.exists()assert dangling.is_symlink()-def test_earlier_payload_cannot_break_later_removal_operand(tmp_path: Path) -> None:- home, release, _, env = _release_fixture(tmp_path)+def test_earlier_payload_cannot_break_later_removal_operand(release_install, tmp_path: Path) -> None:+ f = release_installexternal = tmp_path / "external-home"executable = external / "packages/current/cua-driver"- _executable(executable)- bridge = release.parents[1] / "bridge"+ f.executable(executable)+ bridge = f.release.parents[1] / "bridge"bridge.symlink_to(external, target_is_directory=True)- (home / ".cua-driver-rs").symlink_to(bridge, target_is_directory=True)- config = _config(home, {"entry": {"command": str(executable)}})- result = _run(env)+ (f.home / ".cua-driver-rs").symlink_to(bridge, target_is_directory=True)+ config = f.write_config({"mcpServers": {"entry": {"command": str(executable)}}})+ result = f.run()assert result.returncode == 0, result.stdout + result.stderrassert json.loads(config.read_text())["mcpServers"] == {}assert not executable.exists()- assert not release.exists()+ assert not f.release.exists()-def test_trailing_newline_operand_never_selects_neighbor(tmp_path: Path) -> None:- home, _, _, env = _release_fixture(tmp_path)+def test_trailing_newline_operand_never_selects_neighbor(release_install, tmp_path: Path) -> None:+ f = release_installselected = tmp_path / "selected\n"neighbor = tmp_path / "selected"intended = selected / "packages/current/cua-driver"foreign = neighbor / "packages/current/cua-driver"- _executable(intended)- _executable(foreign)- env["CUA_DRIVER_HOME"] = str(selected)- config = _config(home, {"owned": {"command": str(intended)}, "foreign": {"command": str(foreign)}})- result = _run(env, "--purge")+ f.executable(intended)+ f.executable(foreign)+ f.env["CUA_DRIVER_HOME"] = str(selected)+ config = f.write_config({"mcpServers": {"owned": {"command": str(intended)}, "foreign": {"command": str(foreign)}}})+ result = f.run("--purge")assert result.returncode == 0, result.stdout + result.stderrassert json.loads(config.read_text())["mcpServers"] == {"foreign": {"command": str(foreign)}}assert not intended.exists()assert foreign.exists()-def test_relative_home_ignores_inherited_cdpath(tmp_path: Path) -> None:- home, _, _, env = _release_fixture(tmp_path)+def test_relative_home_ignores_inherited_cdpath(release_install, tmp_path: Path) -> None:+ f = release_installintended = tmp_path / "selected/packages/current/cua-driver"foreign = tmp_path / "search/selected/packages/current/cua-driver"- _executable(intended)- _executable(foreign)- env.update({"CUA_DRIVER_HOME": "selected", "CDPATH": str(tmp_path / "search")})- config = _config(home, {"owned": {"command": str(intended)}, "foreign": {"command": str(foreign)}})- result = subprocess.run(["/bin/bash", str(UNINSTALL)], cwd=tmp_path, env=env,- text=True, capture_output=True, check=False)+ f.executable(intended)+ f.executable(foreign)+ f.env.update({"CUA_DRIVER_HOME": "selected", "CDPATH": str(tmp_path / "search")})+ config = f.write_config({"mcpServers": {"owned": {"command": str(intended)}, "foreign": {"command": str(foreign)}}})+ result = f.run(cwd=tmp_path)assert result.returncode == 0, result.stdout + result.stderrassert json.loads(config.read_text())["mcpServers"] == {"foreign": {"command": str(foreign)}}assert not intended.exists()