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
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,16 @@ All notable changes to SkillEvaluator are documented in this file.
scoring agree, while scoped searches and slash-valued patterns retain their
classification.

- Tier 2 `similarity-check` and `context-optimization-check` no longer abort
with a "symlink or reparse point" error when a skill or collection aliases
one agent directory to another, such as `.agents -> .claude`. A directory
link whose name is not a scanned file type and whose relative target is a
regular directory found by the same scan is skipped without being followed,
so the target directory is scanned once. Absolute links and Windows
junctions, broken or escaping links, links to the scan root or one of the
alias's parent directories, `..` after a named component, and aliases that
point at another link remain rejected.

- Tier 3 `claude-code` trials no longer hang until the agent timeout after the
agent has already answered. Claude Code moves a shell command that outlasts
its Bash timeout to the background, and a headless run waits for background
Expand Down
23 changes: 16 additions & 7 deletions docs/tier2-deduplication.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -307,12 +307,19 @@ you intend to skip Tier 2 entirely.
| High-confidence duplicate boundary | `0.70` | Maps actionable duplicate verdicts to HIGH rather than MEDIUM |

Tier 2 treats skill content and catalog files as untrusted input. Before any
provider call, it rejects linked roots, linked directories and manifests,
hard-linked selected files, non-regular files, paths outside the verified scan
root, and all file redirects except the exact contained
`CLAUDE.md -> AGENTS.md` compatibility alias. That alias is validated but never
followed; its exactly named, independently discovered, single-link regular
sibling target is scanned once. Explicit limits bound
provider call, it rejects linked roots and manifests, hard-linked selected
files, non-regular files, paths outside the verified scan root, and all
redirects except two kinds of contained compatibility alias. The exact
`CLAUDE.md -> AGENTS.md` file alias is validated but never followed; its exactly
named, independently discovered, single-link regular sibling target is scanned
once. A directory alias such as `.agents -> .claude` is accepted only when its
name is not a scanned file type, its raw link text is relative with `..` only
as leading segments, the target stays below the scan root and is neither the
root nor one of the alias's own parent directories, and the same walk finds
that target as a regular directory. The alias is never followed, so the target
directory is scanned once. Absolute links and Windows junctions, broken links,
links that escape the root, and aliases that point at another link remain
rejected. Explicit limits bound
discovered paths, file counts, per-file and total input bytes, content chunks,
candidate clusters, catalog size and entry count, vector length, returned
matches, and pairwise scalar work. Catalog loading also rejects duplicate JSON
Expand Down Expand Up @@ -352,7 +359,8 @@ handling terms before sending confidential skill content to a hosted endpoint.
| Duplicate sections occur in one file | Reports the relevant headings and line ranges |
| Skill contains an exactly named, single-link regular `AGENTS.md` plus `CLAUDE.md -> AGENTS.md` | Validates and skips the alias, then scans `AGENTS.md` once |
| Skill carries large generated snapshots (`evals`, `.evals`, `results`, `.results`, `versions`, `.versions`) | Excluded directories are pruned during traversal, so their contents never count toward the discovered-path limit |
| A directory is a Windows junction or other reparse point | Rejected during the walk, like symbolic links |
| Skill contains a relative directory alias such as `.agents -> .claude` whose target is a regular directory in the same skill | Skips the alias without following it, then scans the target directory once |
| A directory is a Windows junction, other reparse point, or a symbolic link that does not qualify as a contained alias | Rejected during the walk, before descent |
| Embedding or chat-LLM analysis is incomplete | Reports an error; does not claim a clean result |
| Skill exceeds the content-chunk, comparison-work, or LLM-review limit (candidate clusters, cluster members, or prompt size) | Stops before the remaining analysis and reports the scan as incomplete; no duplicate-content finding is added |
</Accordion>
Expand All @@ -364,6 +372,7 @@ handling terms before sending confidential skill content to a hosted endpoint.
| Catalog path is missing | Returns an error and does not rebuild it silently |
| Candidate lacks a root `SKILL.md` | Rejects the catalog query |
| A skill contains an exactly named, single-link regular `AGENTS.md` plus `CLAUDE.md -> AGENTS.md` | Validates and skips the unrelated compatibility alias while discovering `SKILL.md` |
| The collection contains a relative directory alias such as `.agents -> .claude` whose target is a regular directory in the same collection | Skips the alias without following it, so manifests in the target are discovered once |
| Candidate matches multiple catalog entries | Reports matches in descending similarity order |
| Provider, endpoint, model, mode, or vector length differs | Rejects the catalog; query with matching settings or rebuild it |
| Catalog is malformed, non-finite, or oversized | Rejects it before comparison |
Expand Down
53 changes: 45 additions & 8 deletions src/skillevaluator/deduplication/utils/skill_collector.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,11 @@
CONTENT_DEDUP_SCANNABLE_EXTENSIONS,
)
from skillevaluator.utils.path_security import matches_filesystem_name
from skillevaluator.utils.tier2_paths import is_contained_compatibility_alias
from skillevaluator.utils.tier2_paths import (
contained_directory_alias_target,
is_contained_compatibility_alias,
is_link_or_reparse,
)
from skillevaluator.validators.frontmatter_parser import FRONTMATTER_PATTERN

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -440,6 +444,8 @@ def _collect_files_anchored(

candidates: list[_CandidateFile] = []
declared_total_bytes = 0
regular_directories: set[str] = set()
directory_aliases: dict[Path, tuple[str, str]] = {}

def _raise_traversal_error(error: OSError) -> None:
raise error
Expand All @@ -457,18 +463,34 @@ def _iter_paths(root: Path) -> Iterator[Path]:
rel_path = directory.relative_to(root).as_posix()
if matches_filesystem_name(directory, excluded):
logger.debug("Skipping excluded path: %s", rel_path)
# A pruned regular directory is still a valid alias
# target; its contents stay excluded either way.
if not is_link_or_reparse(directory):
regular_directories.add(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.
# reparse points and may still be traversed. Never descend
# into a retained redirect: an unselected, contained alias
# such as ``.agents -> .claude`` is recorded for validation
# after the walk; every other redirect is rejected here.
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.",
target = (
None
if directory.suffix.lower() in CONTENT_DEDUP_SCANNABLE_EXTENSIONS
else contained_directory_alias_target(directory, directory.relative_to(root))
)
if target is None:
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.",
)
directory_aliases[directory] = (rel_path, target)
yield directory
continue
regular_directories.add(rel_path)
kept.append(name)
dirnames[:] = kept
for name in kept:
Expand Down Expand Up @@ -496,6 +518,17 @@ def _iter_paths(root: Path) -> Iterator[Path]:
"limit": CONTENT_DEDUP_MAX_DISCOVERED_PATHS,
},
)
for alias_rel_path, target in directory_aliases.values():
if target not in regular_directories:
raise SkillCollectionError(
"unsafe_path",
(
"Refusing symbolic link or reparse point whose target is not a regular directory "
f"in the skill: {alias_rel_path} -> {target}"
),
rel_path=alias_rel_path,
suggestion="Point the link at a regular directory stored inside the skill directory.",
)
discovered_paths.sort()
discovered_names_by_parent: dict[Path, set[str]] = {}
for discovered_path in discovered_paths:
Expand All @@ -518,6 +551,10 @@ def _iter_paths(root: Path) -> Iterator[Path]:
logger.debug("Skipping excluded path: %s", rel_path)
continue

if file_path in directory_aliases:
logger.debug("Skipping directory alias in favor of regular target: %s", rel_path)
continue

if _is_link_or_reparse(file_path, rel_path):
if is_contained_compatibility_alias(
file_path,
Expand Down
54 changes: 49 additions & 5 deletions src/skillevaluator/embedding/extractor.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,11 @@
from skillevaluator.deduplication.utils.skill_collector import _SecureReadError, _SecureRoot
from skillevaluator.embedding.limits import validate_max_entries
from skillevaluator.logging_config import get_logger
from skillevaluator.utils.tier2_paths import is_contained_compatibility_alias, safe_path_label
from skillevaluator.utils.tier2_paths import (
contained_directory_alias_target,
is_contained_compatibility_alias,
safe_path_label,
)
from skillevaluator.validators.frontmatter_parser import FRONTMATTER_PATTERN

logger = get_logger(__name__)
Expand Down Expand Up @@ -323,14 +327,31 @@ def _read_bounded_manifest(
raise ValueError(f"Manifest is not valid UTF-8: {file_path.name}") from exc


def _is_discovery_manifest_name(name: str) -> bool:
"""Return whether *name* could be selected as a skill, rule, or workflow manifest."""
folded = name.casefold()
return any(folded == variant.casefold() for variant in SKILL_MANIFEST_VARIANTS) or folded.endswith(
RULES_FILE_EXTENSION
)


def _iter_discovery_files(root: Path):
"""Yield bounded files from one pruned inter-skill traversal."""
"""Yield bounded files from one pruned inter-skill traversal.

A contained directory alias such as ``.agents -> .claude`` is never
followed. It is skipped only when its name cannot be a manifest and the
same walk enumerates its target as a regular directory, so the canonical
directory is scanned once. Every other directory redirect is rejected.
"""
if _is_symlink_or_reparse(root):
raise ValueError(f"Discovery root is a symlink or reparse point: {root.name}")
if not root.is_dir():
return

discovered_paths = 0
discovered_files: list[Path] = []
regular_directories: set[str] = set()
directory_aliases: list[tuple[str, str]] = []

def _raise_walk_error(error: OSError) -> None:
raise ValueError(f"Cannot safely traverse the Tier 2 collection: {error}") from error
Expand All @@ -343,11 +364,25 @@ def _raise_walk_error(error: OSError) -> None:
discovered_paths += 1
if discovered_paths > MAX_DISCOVERED_PATHS:
raise ValueError(f"Collection path limit exceeded ({MAX_DISCOVERED_PATHS}) before embedding")
directory = Path(dirpath) / dirname
relative = directory.relative_to(root)
if dirname in DISCOVERY_EXCLUDED_DIRS:
# A pruned regular directory is still a valid alias target;
# its contents stay excluded either way.
if not _is_symlink_or_reparse(directory):
regular_directories.add(relative.as_posix())
continue
directory = Path(dirpath) / dirname
if _is_symlink_or_reparse(directory):
raise ValueError(f"Discovery path contains a symlink or reparse point: {dirname}")
target = (
None
if _is_discovery_manifest_name(dirname)
else contained_directory_alias_target(directory, relative)
)
if target is None:
raise ValueError(f"Discovery path contains a symlink or reparse point: {dirname}")
directory_aliases.append((relative.as_posix(), target))
continue
regular_directories.add(relative.as_posix())
kept_dirs.append(dirname)
dirnames[:] = kept_dirs

Expand All @@ -365,7 +400,16 @@ def _raise_walk_error(error: OSError) -> None:
)
continue
raise ValueError(f"Discovery path contains a symlink or reparse point: {filename}")
yield file_path
discovered_files.append(file_path)

for alias, target in directory_aliases:
if target not in regular_directories:
raise ValueError(
"Discovery path contains a symlink or reparse point whose target is not a regular "
f"directory in the scan root: {alias} -> {target}"
)
logger.debug("Skipping directory alias in favor of regular target: %s -> %s", alias, target)
yield from discovered_files


def _discover_skills(root: Path, budget: _ExtractionBudget) -> list[ContentEntry]:
Expand Down
41 changes: 40 additions & 1 deletion src/skillevaluator/utils/tier2_paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import stat
from collections.abc import Collection
from contextlib import suppress
from pathlib import Path
from pathlib import Path, PurePosixPath
from typing import TYPE_CHECKING

if TYPE_CHECKING:
Expand Down Expand Up @@ -64,6 +64,44 @@ def is_contained_compatibility_alias(path: Path, *, sibling_names: Collection[st
)


def contained_directory_alias_target(path: Path, relative: Path) -> str | None:
"""Return the in-root target that an unselected directory alias names, or ``None``.

``relative`` is the alias path below the scan root. Only the raw link text
is read; the alias is never followed. The text must be relative, may climb
only through the alias's own (already traversed) parent directories, and
must then name a path below the root that is neither the root nor an
ancestor of the alias. The returned POSIX-style relative path is an identity
claim only: callers skip the alias and accept it only when the same walk
independently enumerates that path as a regular directory.
"""
try:
metadata = path.lstat()
target_text = os.readlink(path) # noqa: PTH115 - validate the raw link text without following it
except (OSError, ValueError):
return None
if getattr(metadata, "st_nlink", 1) != 1 or not target_text or "\x00" in target_text:
return None
target = Path(target_text)
if target.anchor:
return None

parts = target.parts
ascent = 0
while ascent < len(parts) and parts[ascent] == "..":
ascent += 1
descent = parts[ascent:]
base = relative.parent.parts
# A ``..`` after a named component could climb out of a linked directory,
# making the lexical claim differ from the physical target.
if ascent > len(base) or not descent or ".." in descent:
return None
normalized = PurePosixPath(*base[: len(base) - ascent], *descent)
if PurePosixPath(relative.as_posix()).is_relative_to(normalized):
return None
return normalized.as_posix()


def paths_refer_to_same_location(left: Path, right: Path) -> bool:
"""Compare output paths after resolving aliases, symlinks, and hard links."""
with suppress(OSError):
Expand Down Expand Up @@ -143,6 +181,7 @@ def sanitize_tier2_results(results: list[ValidationResult], *paths: Path | None)


__all__ = [
"contained_directory_alias_target",
"is_contained_compatibility_alias",
"is_link_or_reparse",
"paths_refer_to_same_location",
Expand Down
Loading
Loading