Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,9 @@ All notable changes to Skill Evaluator are documented in this file.
filename patterns, `execution_performed=false`, and
`coverage_measured=false`; projects must run tests and measure coverage in a
trusted environment or explicit sandbox.

### Fixed

- Tier 2 content collection now prunes configured evaluation and version
artifact directories before enforcing the discovered-path limit, so excluded
generated results cannot cause false path-count failures.
39 changes: 37 additions & 2 deletions src/skillevaluator/deduplication/utils/skill_collector.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
import logging
import os
import stat
from collections.abc import Iterable
from collections.abc import Iterable, Iterator
from dataclasses import dataclass
from itertools import islice
from pathlib import Path
Expand Down Expand Up @@ -437,8 +437,43 @@ def _collect_files_anchored(
candidates: list[_CandidateFile] = []
declared_total_bytes = 0

def _raise_traversal_error(error: OSError) -> None:
raise error

def _iter_paths(root: Path) -> Iterator[Path]:
# Prune the excluded dirs DURING traversal, not just when filtering
# the discovered list: generated artifacts (evals/results snapshots)
# must not consume the path budget, or a well-used skill fails the
# path-count limit on content it was never going to scan.
for dirpath, dirnames, filenames in os.walk(root, onerror=_raise_traversal_error):
base = Path(dirpath)
kept: list[str] = []
for name in dirnames:
directory = base / name
rel_path = directory.relative_to(root).as_posix()
if name in excluded:
logger.debug("Skipping excluded path: %s", rel_path)
continue
# ``os.walk(..., followlinks=False)`` does not follow normal
# symlinks, but Windows directory junctions are separate
# reparse points and may still be traversed. Reject every
# retained redirect before allowing the walk to recurse.
if _is_link_or_reparse(directory, rel_path):
raise SkillCollectionError(
"unsafe_path",
f"Refusing symbolic link or reparse point: {rel_path}",
rel_path=rel_path,
suggestion="Replace the link with a regular directory stored inside the skill directory.",
)
kept.append(name)
dirnames[:] = kept
for name in kept:
yield base / name
for name in filenames:
yield base / name

try:
discovered_paths = list(islice(skill_root.rglob("*"), CONTENT_DEDUP_MAX_DISCOVERED_PATHS + 1))
discovered_paths = list(islice(_iter_paths(skill_root), CONTENT_DEDUP_MAX_DISCOVERED_PATHS + 1))
except OSError as e:
raise SkillCollectionError(
"path_access_error",
Expand Down
103 changes: 100 additions & 3 deletions tests/deduplication/utils/test_skill_collector.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import logging
import os
import stat
import subprocess
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import patch
Expand Down Expand Up @@ -271,10 +272,12 @@ def test_rejects_unbounded_directory_traversal(self, skill_root: Path, monkeypat
assert exc_info.value.metadata == {"actual": 3, "limit": 2}

def test_directory_traversal_error_is_actionable(self, skill_root: Path, monkeypatch) -> None:
def deny_traversal(_path: Path, _pattern: str):
raise PermissionError("permission denied")
def deny_traversal(_root: Path, *, onerror=None, **_kwargs):
assert onerror is not None
onerror(PermissionError("permission denied"))
return iter(())

monkeypatch.setattr(Path, "rglob", deny_traversal)
monkeypatch.setattr(os, "walk", deny_traversal)

with pytest.raises(SkillCollectionError) as exc_info:
collect_files(skill_root)
Expand All @@ -299,6 +302,67 @@ def test_rejects_symlinked_scannable_file(self, skill_root: Path, tmp_path: Path
assert "symbolic link or reparse point" in str(exc_info.value)
assert "replace" in exc_info.value.suggestion.lower()

def test_rejects_reparse_directory_before_descending(self, skill_root: Path) -> None:
target = skill_root / "reparse-directory"
target.mkdir()
(target / "private.md").write_text("private host content")
original_lstat = Path.lstat

def guarded_walk(root: Path, **_kwargs):
yield root, [target.name], []
raise AssertionError("walk descended into a reparse directory")

def fake_lstat(path: Path):
if path == target:
return SimpleNamespace(
st_mode=stat.S_IFDIR,
st_file_attributes=stat.FILE_ATTRIBUTE_REPARSE_POINT,
)
return original_lstat(path)

with (
patch.object(Path, "lstat", fake_lstat),
patch.object(os, "walk", guarded_walk),
pytest.raises(SkillCollectionError) as exc_info,
):
collect_files(skill_root)

assert exc_info.value.check_name == "unsafe_path"
assert exc_info.value.rel_path == "reparse-directory"
assert "symbolic link or reparse point" in str(exc_info.value)

@pytest.mark.skipif(os.name != "nt", reason="directory junctions are Windows-specific")
def test_rejects_windows_junction_before_walking_target(
self, skill_root: Path, tmp_path: Path, monkeypatch
) -> None:
outside = tmp_path / "outside"
outside.mkdir()
(outside / "private.md").write_text("private host content")
junction = skill_root / "junction"
subprocess.run(
["cmd", "/c", "mklink", "/J", str(junction), str(outside)],
check=True,
capture_output=True,
text=True,
)
real_walk = os.walk
visited: list[Path] = []

def recording_walk(*args, **kwargs):
for entry in real_walk(*args, **kwargs):
visited.append(Path(entry[0]))
yield entry

monkeypatch.setattr(os, "walk", recording_walk)

with pytest.raises(SkillCollectionError) as exc_info:
collect_files(skill_root)

assert exc_info.value.check_name == "unsafe_path"
assert exc_info.value.rel_path == "junction"
assert "symbolic link or reparse point" in str(exc_info.value)
assert junction not in visited

def test_rejects_windows_reparse_point_even_when_not_a_symlink(self, skill_root: Path) -> None:
target = skill_root / "reparse.md"
target.write_text("content")
Expand Down Expand Up @@ -587,3 +651,36 @@ def test_custom_exclusion_set_extends_filter(self, skill_root: Path) -> None:
result = collect_files(skill_root, excluded_dirs={"build_cache"})
rel_paths = sorted(f.rel_path for f in result)
assert rel_paths == ["SKILL.md"]


class TestPathBudgetExcludesArtifacts:
def test_path_limit_ignores_generated_artifact_trees(self, tmp_path: Path, monkeypatch) -> None:
# Live regression: a well-used skill accumulates thousands of trial
# artifacts under evals/results/. They are excluded content and must
# not consume the path-count budget (managing-calendar failed Tier 2
# with "more than 4096 paths" on generated files it never scans).
monkeypatch.setattr(skill_collector, "CONTENT_DEDUP_MAX_DISCOVERED_PATHS", 8)
skill = tmp_path / "busy-skill"
skill.mkdir()
(skill / "SKILL.md").write_text("# Busy skill\n\nAuthored content.", encoding="utf-8")
trials = skill / "evals" / "results" / "20260101_000000" / "trials"
trials.mkdir(parents=True)
for index in range(10):
(trials / f"artifact-{index}.json").write_text("{}", encoding="utf-8")

result = collect_files(skill)

assert [f.rel_path for f in result] == ["SKILL.md"]

def test_path_limit_still_applies_to_authored_content(self, tmp_path: Path, monkeypatch) -> None:
monkeypatch.setattr(skill_collector, "CONTENT_DEDUP_MAX_DISCOVERED_PATHS", 8)
skill = tmp_path / "huge-skill"
(skill / "docs").mkdir(parents=True)
for index in range(10):
(skill / "docs" / f"note-{index}.md").write_text("hi", encoding="utf-8")

with pytest.raises(SkillCollectionError) as exc_info:
collect_files(skill)

assert exc_info.value.check_name == "path_count_limit"
assert exc_info.value.metadata == {"actual": 9, "limit": 8}
19 changes: 19 additions & 0 deletions tests/reporting/test_reporters.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,25 @@ def test_render_escapes_markup_in_legacy_errors(self) -> None:

assert "[/red]" in plain_output

def test_failed_tier2_scan_is_reported_as_an_error_not_a_duplicate(self, tmp_path: Path, monkeypatch) -> None:
from skillevaluator.deduplication.intra_skill.intra_skill_validator import IntraSkillValidator
from skillevaluator.deduplication.utils import skill_collector

monkeypatch.setattr(skill_collector, "CONTENT_DEDUP_MAX_DISCOVERED_PATHS", 2)
skill = tmp_path / "over-budget"
skill.mkdir()
for name in ("SKILL.md", "a.bin", "b.bin"):
(skill / name).write_text("content", encoding="utf-8")

result = IntraSkillValidator().validate(skill)
assert result.findings[0].check_name == "path_count_limit"

output = re.sub(r"\x1b\[[0-9;]*m", "", CLIReporter().render_all([result]))

assert "Errors:" in output
assert "Skill tree contains more than 2 paths." in output
assert "duplicates found" not in output.lower()

def test_render_escapes_markup_in_success_details(self) -> None:
result = ValidationResult(
validator_name="SIMILARITY",
Expand Down
Loading