Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,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.
- `quality-check` recognizes English, Russian, and Chinese vocabulary for
triggers, instructions, examples, error handling, expected headings, and
documentation for scripts, APIs, and resources. The packaged `quality_config`
Expand Down
55 changes: 13 additions & 42 deletions src/skillevaluator/tier3/harbor/local_environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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())
Expand All @@ -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)
Expand Down Expand Up @@ -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()
Comment thread
Afloat16 marked this conversation as resolved.
Resolved
):
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))
Expand All @@ -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")
Expand Down
56 changes: 56 additions & 0 deletions src/skillevaluator/tier3/harbor/local_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 "_.-/"):
Comment thread
Afloat16 marked this conversation as resolved.
Resolved
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)
Expand Down
48 changes: 47 additions & 1 deletion tests/test_harbor_local_environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import asyncio
import logging
import os
import shlex
import shutil
import stat
import subprocess
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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"])
Expand Down
6 changes: 3 additions & 3 deletions tests/test_harbor_local_mode.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -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"')
Expand All @@ -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")
Expand Down