From a229fea72b7edb81e4b4fb2232f678705597178a Mon Sep 17 00:00:00 2001 From: Afloat Date: Mon, 30 Nov 2026 10:33:12 +0800 Subject: [PATCH] fix: map local runtime paths without rewriting host paths Signed-off-by: Afloat --- CHANGELOG.md | 4 ++ .../tier3/harbor/local_environment.py | 55 +++++------------- .../tier3/harbor/local_runtime.py | 56 +++++++++++++++++++ tests/test_harbor_local_environment.py | 48 +++++++++++++++- tests/test_harbor_local_mode.py | 6 +- 5 files changed, 123 insertions(+), 46 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6cc23bb65..5f28151df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -104,6 +104,10 @@ All notable changes to SkillEvaluator are documented in this file. ### Fixed +- Local Tier 3 shell commands map virtual paths once, preserving existing host + paths when a run or installed runtime is under `/workspace` or contains + another virtual root. Artifact directory checks and collection retain the + intended host locations, including quoted paths. - Tier 3 grading now credits successful Hermes skill reads and shell commands in trajectories from other runners. OpenCode file reads, writes, and edits keep their paths and replacement text in grading evidence. An unfinished Hermes diff --git a/src/skillevaluator/tier3/harbor/local_environment.py b/src/skillevaluator/tier3/harbor/local_environment.py index 94e288a1f..c8ae41275 100644 --- a/src/skillevaluator/tier3/harbor/local_environment.py +++ b/src/skillevaluator/tier3/harbor/local_environment.py @@ -33,6 +33,7 @@ LOCAL_RUNTIME_AGENTS, default_runtime_root, local_subprocess_env, + rewrite_local_command_paths, runtime_bin_dirs, runtime_command_roots, validate_runtime_root, @@ -1960,10 +1961,11 @@ def _path_map(self) -> list[tuple[str, Path]]: ] def _rewrite_command(self, command: str) -> str: - rewritten = command - for remote, local in self._path_map(): - rewritten = self._replace_shell_path(rewritten, remote, local) - return rewritten + return rewrite_local_command_paths( + command, + self._path_map(), + host_roots=(*self._allowed_write_roots(), self._runtime_root, Path(sys.executable).parent), + ) def _rewrite_raw_paths(self, value: str) -> str: path_map = dict(self._path_map()) @@ -1985,43 +1987,6 @@ def replace(match: re.Match[str]) -> str: return pattern.sub(replace, value) - @staticmethod - def _replace_shell_path(command: str, remote: str, local: Path) -> str: - """Replace a container path while preserving shell token boundaries.""" - output: list[str] = [] - index = 0 - quote = "" - local_text = str(local) - shell_boundaries = "/ \t\r\n'\";&|<>" - while index < len(command): - if command.startswith(remote, index) and ( - index + len(remote) == len(command) or command[index + len(remote)] in shell_boundaries - ): - if quote == "'": - replacement = local_text.replace("'", "'\"'\"'") - elif quote == '"': - replacement = ( - local_text.replace("\\", "\\\\").replace('"', '\\"').replace("$", "\\$").replace("`", "\\`") - ) - else: - replacement = shlex.quote(local_text) - output.append(replacement) - index += len(remote) - continue - - char = command[index] - output.append(char) - if char == "\\" and quote != "'" and index + 1 < len(command): - index += 1 - output.append(command[index]) - elif char in {"'", '"'}: - if not quote: - quote = char - elif quote == char: - quote = "" - index += 1 - return "".join(output) - def _rewrite_uploaded_scripts(self, target: Path) -> None: if target.is_file(): self._rewrite_uploaded_script(target) @@ -2050,6 +2015,13 @@ def _resolve_path(self, path: str | Path | None) -> Path: if path is None: return self._workspace raw = str(path) + candidate = Path(raw) + if candidate.is_absolute() and any( + candidate.is_relative_to(root.absolute()) for root in self._allowed_write_roots() + ): + if not self._path_is_within_allowed_local_roots(candidate): + raise ValueError(f"path {raw} is outside the local run directory") + return candidate # Normalize logical spellings before choosing a role mapping, without # following untrusted filesystem links through the virtual parent. logical = str(PurePosixPath(raw)) @@ -2060,7 +2032,6 @@ def _resolve_path(self, path: str | Path | None) -> Path: return local / logical[len(remote) + 1 :] if raw.startswith("~/"): return self._home / raw[2:] - candidate = Path(raw) if candidate.is_absolute(): if not self._path_is_within_allowed_local_roots(candidate): raise ValueError(f"path {raw} is outside the local run directory") diff --git a/src/skillevaluator/tier3/harbor/local_runtime.py b/src/skillevaluator/tier3/harbor/local_runtime.py index 176ab8865..b5d46c4fe 100644 --- a/src/skillevaluator/tier3/harbor/local_runtime.py +++ b/src/skillevaluator/tier3/harbor/local_runtime.py @@ -90,6 +90,62 @@ class RuntimePathResolutionError(RuntimeError): } +def rewrite_local_command_paths( + command: str, path_map: Sequence[tuple[str, Path]], *, host_roots: Sequence[Path] = () +) -> str: + """Map original shell paths once, preserving quotes and known host paths.""" + + def quote_path(path: str, quote: str) -> str: + if quote == "'": + return path.replace("'", "'\"'\"'") + if quote == '"': + return path.replace("\\", "\\\\").replace('"', '\\"').replace("$", "\\$").replace("`", "\\`") + return shlex.quote(path) + + mappings: dict[str, list[tuple[str, str]]] = {} + for quote in ("", "'", '"'): + entries = [(remote, quote_path(str(local), quote)) for remote, local in path_map] + for root in (*host_roots, *(local for _, local in path_map)): + spelling = quote_path(str(root), quote) if quote else str(root) + entries.append((spelling, spelling)) + mappings[quote] = sorted(entries, key=lambda entry: len(entry[0]), reverse=True) + + output: list[str] = [] + index = 0 + quote = "" + shell_boundaries = "/ \t\r\n'\";&|<>" + while index < len(command): + match = None + if index == 0 or not (command[index - 1].isalnum() or command[index - 1] in "_.-/"): + match = next( + ( + (remote, replacement) + for remote, replacement in mappings[quote] + if command.startswith(remote, index) + and (index + len(remote) == len(command) or command[index + len(remote)] in shell_boundaries) + ), + None, + ) + if match is not None: + remote, replacement = match + output.append(replacement) + index += len(remote) + continue + + char = command[index] + output.append(char) + if char == "\\" and quote != "'" and index + 1 < len(command): + index += 1 + output.append(command[index]) + elif char in {"'", '"'}: + if not quote: + quote = char + elif quote == char: + quote = "" + index += 1 + return "".join(output) + + def validate_runtime_root(root: Path | str) -> Path: """Return a canonical dedicated runtime root without exposing host home.""" resolved = Path(root).expanduser().resolve(strict=False) diff --git a/tests/test_harbor_local_environment.py b/tests/test_harbor_local_environment.py index 54c038abd..c9b4eb597 100644 --- a/tests/test_harbor_local_environment.py +++ b/tests/test_harbor_local_environment.py @@ -6,6 +6,7 @@ import asyncio import logging import os +import shlex import shutil import stat import subprocess @@ -33,7 +34,8 @@ def local_output_environment(tmp_path: Path) -> SkillEvaluatorLocalEnvironment: environment_dir.mkdir() runtime_root = tmp_path / "runtime" runtime_root.mkdir() - paths = TrialPaths(tmp_path / "trial") + # Host paths can contain the same components as the virtual runtime roots. + paths = TrialPaths(tmp_path / "workspace" / "tests" / "trial") paths.mkdir() return SkillEvaluatorLocalEnvironment( environment_dir=environment_dir, @@ -417,6 +419,50 @@ def test_raw_path_rewrite_ignores_url_and_local_path_suffixes(tmp_path: Path) -> assert rewritten == f'"{local_tests}{os.sep}api" "https://example.invalid/tests/api" "{local_tests}/api"' +@pytest.mark.skipif(os.name == "nt", reason="local subprocess backend requires POSIX") +@pytest.mark.parametrize("quote", ["", "'", '"']) +@pytest.mark.parametrize("reverse", [False, True]) +def test_shell_paths_are_mapped_once_with_overlapping_roots( + local_output_environment: SkillEvaluatorLocalEnvironment, tmp_path: Path, quote: str, reverse: bool +) -> None: + environment = local_output_environment + target = tmp_path / "workspace" / "tests" / "quote ' \" $ `" + mappings = [("/logs", target / "logs"), ("/logs/agent", target / "agent"), ("/workspace", target / "workspace")] + environment._path_map = lambda: list(reversed(mappings)) if reverse else mappings + operands = [f"{quote}{remote}/answer.txt{quote}" for remote, _ in mappings] + rewritten = environment._rewrite_command("printf '%s\\n' " + " ".join(operands)) + + result = subprocess.run(["bash", "-c", rewritten], capture_output=True, text=True, timeout=10) + + assert result.returncode == 0, result.stderr + assert result.stdout.splitlines() == [str(local / "answer.txt") for _, local in mappings] + + +@pytest.mark.skipif(os.name == "nt", reason="local subprocess backend requires POSIX") +def test_shell_paths_preserve_host_paths_and_adjacent_text( + local_output_environment: SkillEvaluatorLocalEnvironment, +) -> None: + environment = local_output_environment + operands = [ + str(environment._tmp / "tests" / "archive.tar"), + str(environment._workspace / "logs" / "answer.txt"), + str(environment._runtime_root / "workspace" / "bin"), + "https://example.invalid/tests/eval.py", + "prefix/workspace/answer.txt", + "项目/workspace/answer.txt", + "/workspace-other/answer.txt", + "/testsuite/eval.py", + ] + command = "printf '%s\\n' " + " ".join(shlex.quote(operand) for operand in operands) + + result = subprocess.run( + ["bash", "-c", environment._rewrite_command(command)], capture_output=True, text=True, timeout=10 + ) + + assert result.returncode == 0, result.stderr + assert result.stdout.splitlines() == operands + + @pytest.mark.integration @pytest.mark.skipif(os.name == "nt", reason="local subprocess backend requires POSIX") @pytest.mark.parametrize("secret_name", ["SANDBOX_TOKEN", "MYSECRET", "SOMEKEY", "AUTHENTICATION"]) diff --git a/tests/test_harbor_local_mode.py b/tests/test_harbor_local_mode.py index ceed3ae29..e9a0eb796 100644 --- a/tests/test_harbor_local_mode.py +++ b/tests/test_harbor_local_mode.py @@ -5303,7 +5303,7 @@ def capture_bins(runtime_root, *, agents=None): def test_shell_path_rewrite_quotes_unquoted_path_with_spaces(tmp_path: Path) -> None: target = tmp_path / "result with spaces" target.mkdir() - environment = object.__new__(SkillEvaluatorLocalEnvironment) + environment = _local_environment(tmp_path) environment._path_map = lambda: [("/logs", target)] rewritten = environment._rewrite_command("printf ok > /logs/output.txt") @@ -5317,7 +5317,7 @@ def test_shell_path_rewrite_quotes_unquoted_path_with_spaces(tmp_path: Path) -> def test_shell_path_rewrite_preserves_existing_quotes(tmp_path: Path) -> None: target = tmp_path / "result with spaces" target.mkdir() - environment = object.__new__(SkillEvaluatorLocalEnvironment) + environment = _local_environment(tmp_path) environment._path_map = lambda: [("/logs", target)] rewritten = environment._rewrite_command('printf ok > "/logs/output.txt"') @@ -5331,7 +5331,7 @@ def test_shell_path_rewrite_preserves_existing_quotes(tmp_path: Path) -> None: def test_shell_path_rewrite_handles_exact_path_before_shell_separator(tmp_path: Path) -> None: target = tmp_path / "result with spaces" target.mkdir() - environment = object.__new__(SkillEvaluatorLocalEnvironment) + environment = _local_environment(tmp_path) environment._path_map = lambda: [("/workspace", target)] rewritten = environment._rewrite_command("cd /workspace && printf ok > output.txt")