Skip to content

Multi-tier framework for evaluating AI agent skills and plugins with quality gates, security scanning, harness compatibility checks, semantic overlap detection, synthetic evaluation dataset generation, and live agent evaluation that measures how skills affect agent behavior. Ships reusable CI templates that bring every check to any repository.

fix(tier2): stop catalog queries from matching a skill against its own entry (#296)

Narendran Raghavan9f520db6606e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 902e9dbe..292b1c25 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -571,6 +571,19 @@ All notable changes to SkillEvaluator are documented in this file.
forwarded to SkillSpector so its own deadline can be raised as well, and the
security result records the effective `skillspector_timeout_seconds`
([#155](https://github.com/NVIDIA/SkillEvaluator/issues/155)).
+- `similarity-check --catalog` and `tier2 --catalog` no longer report a skill
+ that is already in the local catalog as an `EXACT_DUPLICATE` of its own
+ entry, which failed the run. An entry is skipped as the skill's own only when
+ its content fingerprint matches, its path ends the skill's path, and more
+ than half of up to eight other catalog skills, spread evenly across the
+ catalog's path-sorted list, are present unchanged at their recorded paths
+ around it. The skip is recorded under
+ `self_matches_excluded` and `excluded_catalog_paths`. Verbatim copies and
+ same-name skills outside the catalog's tree are still reported; a copy of
+ most of the tree, such as a second checkout, counts as the same tree. An
+ edited skill whose name, description, or (with `--full-body`) `SKILL.md`
+ changed is still compared with its old entry; build the catalog from the tree
+ you screen.
### Security
diff --git a/docs/tier2-deduplication.mdx b/docs/tier2-deduplication.mdx
index 2b3a5e25..674eea73 100644
--- a/docs/tier2-deduplication.mdx
+++ b/docs/tier2-deduplication.mdx
@@ -263,6 +263,31 @@ existing set — save the collection once and query candidates against it.
</Step>
</Steps>
+Re-screening a skill that is already in the catalog does not report it as a
+duplicate of its own entry. A catalog does not record the directory it was
+built from, so an entry is skipped as the candidate's own only when all of
+these hold:
+
+- Its content fingerprint matches what the query compares: the name and
+ description, or the whole `SKILL.md` with `--full-body`.
+- Its path ends the candidate's path — `alpha` for `./skills/alpha` in a
+ catalog built from `./skills` — which locates the catalog's tree around the
+ candidate.
+- Of up to eight other catalog skills, spread evenly across the catalog's
+ path-sorted list, more than half are present unchanged at their recorded
+ paths in that tree, without symlinks. Skills that contain the candidate or are nested inside it are not
+ checked, because a copied folder carries them too.
+
+At most one entry is skipped, and the result records it under
+`excluded_catalog_paths`. A catalog with no other skill entry never skips one.
+A verbatim copy elsewhere — in a staging folder, another repository, or a new
+folder of the same repository — is still compared and reported, unless it sits
+in a copy of most of the catalog's tree, such as a second checkout of the same
+repository, which counts as the same tree. An edited skill whose compared
+content changed no longer matches its old entry and is compared with it like
+any other skill; to screen edited skills, build the catalog from the same tree
+you screen.
+
Catalogs contain finite embedding vectors, relative skill paths, display names,
descriptions, content fingerprints, and provider, model, mode, and
endpoint-fingerprint metadata for compatibility checks. They never contain API
diff --git a/src/skillevaluator/embedding/registry.py b/src/skillevaluator/embedding/registry.py
index ad23e4e5..85d1dd76 100644
--- a/src/skillevaluator/embedding/registry.py
+++ b/src/skillevaluator/embedding/registry.py
@@ -49,12 +49,13 @@ from skillevaluator.embedding.extractor import (
MAX_MANIFEST_BYTES,
ContentEntry,
discover_and_extract,
+ extract_from_skill,
)
from skillevaluator.embedding.limits import validate_max_entries, validate_max_scalar_comparisons
from skillevaluator.logging_config import get_logger
from skillevaluator.models.result import Severity
from skillevaluator.utils.path_security import canonicalize_trusted_root_alias
-from skillevaluator.utils.tier2_paths import safe_path_label
+from skillevaluator.utils.tier2_paths import is_link_or_reparse, safe_path_label
logger = get_logger(__name__)
@@ -67,6 +68,10 @@ EMBEDDING_BATCH_SIZE = 64
MAX_DESCRIPTION_EMBEDDING_TEXT_CHARS = 16_384
MAX_FULL_BODY_EMBEDDING_TEXT_BYTES = MAX_MANIFEST_BYTES
MAX_SIMILARITY_MATCHES = 1_000
+# At most this many other catalog skills are read under a target's inferred
+# scan root before its own entry is skipped; more than half must be present
+# there unchanged. Each read is bounded by MAX_MANIFEST_BYTES.
+SELF_ENTRY_SAMPLE_SIZE = 8
_SHA256_PATTERN = re.compile(r"^[0-9a-f]{64}$")
_ENDPOINT_FINGERPRINT_PATTERN = re.compile(r"^sha256:[0-9a-f]{64}$")
_CATALOG_CONTENT_TYPES = {
@@ -346,8 +351,93 @@ class EmbeddingRegistry:
matches.sort(key=lambda m: m.score, reverse=True)
return matches
- def query_entry(self, entry: ContentEntry, threshold: float) -> list[SimilarityMatch]:
- """Compare one extracted target entry against every catalog entry."""
+ def catalog_self_entry(self, target: ContentEntry) -> RegistryEntry | None:
+ """Return the catalog entry that records *target* itself, if any.
+
+ Catalog paths are relative to a scan root the catalog does not record,
+ so an entry counts as the target only with positive evidence that the
+ target sits at that path in the tree the catalog was built from:
+
+ - its content fingerprint matches the target in this registry's mode;
+ - its path ends the target's resolved directory path, which infers the
+ scan root (the longest such path wins; a case-only difference counts
+ when both spellings name the same directory); and
+ - more than half of up to ``SELF_ENTRY_SAMPLE_SIZE`` other catalog skill
+ entries (spread evenly across the path-sorted list, none containing or
+ inside the target's own path) are present under that root at their
+ recorded paths, through no links, with matching fingerprints.
+
+ A root (``.``) entry, a catalog with no other skill entry, and copies or
+ same-name skills outside such a tree never match, so they stay
+ comparable.
+ """
+ if target.content_type != CONTENT_TYPE_SKILL:
+ return None
+ target_dir = Path(target.path).resolve()
+ fingerprint = self._entry_fingerprint(target)
+ skills = sorted(
+ (entry for entry in self._entries.values() if entry.content_type == CONTENT_TYPE_SKILL),
+ key=lambda entry: entry.path,
+ )
+ candidate: RegistryEntry | None = None
+ candidate_depth = 0
+ scan_root: Path | None = None
+ for catalog_entry in skills:
+ parts = PurePosixPath(catalog_entry.path).parts
+ if catalog_entry.content_fingerprint != fingerprint or len(parts) <= candidate_depth:
+ continue
+ inferred_root = _inferred_scan_root(target_dir, parts)
+ if inferred_root is not None:
+ candidate, candidate_depth, scan_root = catalog_entry, len(parts), inferred_root
+ if candidate is None or scan_root is None or not self._holds_catalog_tree(scan_root, candidate, skills):
+ return None
+ return candidate
+
+ def _holds_catalog_tree(self, scan_root: Path, own: RegistryEntry, skills: list[RegistryEntry]) -> bool:
+ """Return whether *scan_root* holds more than half of the sampled other catalog skills unchanged.
+
+ At most ``SELF_ENTRY_SAMPLE_SIZE`` other skills are read, spread evenly
+ across the path-sorted list so the sample stands for the whole tree.
+ """
+ own_parts = PurePosixPath(own.path).parts
+ others: list[tuple[RegistryEntry, tuple[str, ...]]] = []
+ for catalog_entry in skills:
+ parts = PurePosixPath(catalog_entry.path).parts
+ shared = min(len(parts), len(own_parts))
+ if parts[:shared] == own_parts[:shared]:
+ # The entry itself, the scan root, an ancestor, or a skill nested
+ # in the target: a copy of the target's subtree carries these too.
+ continue
+ others.append((catalog_entry, parts))
+ if len(others) > SELF_ENTRY_SAMPLE_SIZE:
+ others = [others[index * len(others) // SELF_ENTRY_SAMPLE_SIZE] for index in range(SELF_ENTRY_SAMPLE_SIZE)]
+ present = 0
+ for catalog_entry, parts in others:
+ directory = _unlinked_directory(scan_root, parts)
+ if directory is None:
+ continue
+ with suppress(ValueError, OSError):
+ found = extract_from_skill(directory)
+ if found is not None and self._entry_fingerprint(found) == catalog_entry.content_fingerprint:
+ present += 1
+ return present * 2 > len(others)
+
+ def _entry_fingerprint(self, entry: ContentEntry) -> str:
+ """Fingerprint *entry* the way this registry's mode records catalog entries."""
+ return _fingerprint(entry.full_text if self._full_body else entry.embedding_text)
+
+ def query_entry(
+ self,
+ entry: ContentEntry,
+ threshold: float,
+ *,
+ exclude_entry_id: str | None = None,
+ ) -> list[SimilarityMatch]:
+ """Compare one extracted target entry against every catalog entry.
+
+ ``exclude_entry_id`` skips one catalog entry, such as the target's own
+ record from :meth:`catalog_self_entry`, before thresholds apply.
+ """
_validate_threshold(threshold)
catalog_entries = list(self._entries.values())
vector_dimension = _registry_vector_dimension(catalog_entries, self._vector_dimension)
@@ -361,6 +451,8 @@ class EmbeddingRegistry:
matches: list[SimilarityMatch] = []
for catalog_entry, unit_vector in zip(catalog_entries, unit_vectors, strict=True):
+ if catalog_entry.entry_id == exclude_entry_id:
+ continue
score = unit_vector_similarity(query_vector, unit_vector)
if score >= threshold:
if len(matches) >= MAX_SIMILARITY_MATCHES:
@@ -533,6 +625,36 @@ def _fingerprint(text: str) -> str:
return hashlib.sha256(text.encode("utf-8")).hexdigest()
+def _inferred_scan_root(target_dir: Path, entry_parts: tuple[str, ...]) -> Path | None:
+ """Return the scan root that places *target_dir* at the catalog path *entry_parts*, if any."""
+ depth = len(entry_parts)
+ if depth == 0 or depth >= len(target_dir.parts):
+ return None
+ scan_root = Path(*target_dir.parts[:-depth])
+ tail = target_dir.parts[-depth:]
+ if tail == entry_parts:
+ return scan_root
+ if tuple(part.casefold() for part in tail) != tuple(part.casefold() for part in entry_parts):
+ return None
+ # A case-insensitive filesystem may spell the target differently from the
+ # catalog; accept that only when both spellings name the same directory.
+ directory = _unlinked_directory(scan_root, entry_parts)
+ with suppress(OSError):
+ if directory is not None and os.path.samestat(directory.lstat(), target_dir.lstat()):
+ return scan_root
+ return None
+
+
+def _unlinked_directory(root: Path, parts: tuple[str, ...]) -> Path | None:
+ """Return ``root/parts`` when every component below *root* is a directory and none is a link."""
+ current = root
+ for part in parts:
+ current = current / part
+ if is_link_or_reparse(current) or not current.is_dir():
+ return None
+ return current
+
+
def _client_provider(client: EmbeddingClient) -> str:
config = client._resolved_config()
provider = getattr(config, "provider", None)
diff --git a/src/skillevaluator/validators/similarity.py b/src/skillevaluator/validators/similarity.py
index 00e5aa43..30c1d259 100644
--- a/src/skillevaluator/validators/similarity.py
+++ b/src/skillevaluator/validators/similarity.py
@@ -131,12 +131,29 @@ class SimilarityValidator(ValidatorBase):
if target is None:
result.add_error("Catalog comparison requires a skill directory with a root SKILL.md")
return result
- matches = registry.query_entry(target, self._threshold)
+ # A catalog built from the tree that holds the target records the
+ # target itself; never report it as its own duplicate. Copies
+ # outside that tree keep their catalog matches.
+ self_entry = registry.catalog_self_entry(target)
+ matches = registry.query_entry(
+ target,
+ self._threshold,
+ exclude_entry_id=self_entry.entry_id if self_entry is not None else None,
+ )
+ excluded_paths = [self_entry.path] if self_entry is not None else []
+ compared_message = f"Compared '{target.name}' against {registry.size} catalog entries"
+ if self_entry is not None:
+ compared_message = (
+ f"Compared '{target.name}' against {registry.size - 1} other catalog entries; "
+ f"skipped its own entry '{self_entry.path}' (same path and content in the catalog's tree)"
+ )
result.add_success(
"catalog_compared",
- f"Compared '{target.name}' against {registry.size} catalog entries",
+ compared_message,
catalog_entry_count=registry.size,
target_name=target.name,
+ self_matches_excluded=len(excluded_paths),
+ excluded_catalog_paths=excluded_paths,
)
else:
minimum_entries = 1 if self._save_catalog_path is not None else 2
diff --git a/tests/embedding/test_catalog.py b/tests/embedding/test_catalog.py
index a6ac06bf..32a12298 100644
--- a/tests/embedding/test_catalog.py
+++ b/tests/embedding/test_catalog.py
@@ -10,6 +10,8 @@ import hashlib
import json
import math
import os
+import re
+import shutil
import socket
import subprocess
import sys
@@ -22,7 +24,7 @@ import pytest
import skillevaluator.embedding.registry as registry_module
from skillevaluator.embedding.client import EmbeddingClient
-from skillevaluator.embedding.extractor import ContentEntry
+from skillevaluator.embedding.extractor import ContentEntry, extract_from_skill
from skillevaluator.embedding.registry import EmbeddingRegistry, RegistryEntry
@@ -587,3 +589,263 @@ def test_catalog_query_match_limit_fails_closed(tmp_path: Path, monkeypatch) ->
with pytest.raises(ValueError, match="match limit"):
registry.query_entry(target, 0.75)
+
+
+_SKILL_NAMES = ("alpha", "beta", "gamma", "delta", "epsilon")
+
+
+def _keyed_client() -> EmbeddingClient:
+ """Embed each known skill name as its own unit vector, whatever else its text says."""
+
+ def embed_one(text: str) -> list[float]:
+ words = set(re.findall(r"[a-z]+", text))
+ key = next((name for name in _SKILL_NAMES[1:] if name in words), _SKILL_NAMES[0])
+ return [1.0 if name == key else 0.0 for name in _SKILL_NAMES]
+
+ client = _client()
+ client.embed.side_effect = lambda texts: [embed_one(text) for text in texts]
+ client.embed_single.side_effect = embed_one
+ client.embed_chunked.side_effect = embed_one
+ return client
+
+
+def _saved_catalog(tmp_path: Path, scan_root: Path, *, full_body: bool = False) -> EmbeddingRegistry:
+ builder = EmbeddingRegistry(_keyed_client(), full_body=full_body)
+ builder.build_from_directory(scan_root, "skill")
+ catalog_path = tmp_path / "catalog.json"
+ builder.save_catalog(catalog_path)
+ registry = EmbeddingRegistry(_keyed_client(), full_body=full_body)
+ registry.load_catalog(catalog_path)
+ return registry
+
+
+def _write_skills(write_skill, root: Path, *names: str) -> Path:
+ for name in names:
+ write_skill(root, name, f"{name.title()} catalog skill")
+ return root
+
+
+def _target(skill_dir: Path) -> ContentEntry:
+ target = extract_from_skill(skill_dir)
+ assert target is not None
+ return target
+
+
+def _copy_alpha_to(relative: str):
+ def build(tmp_path: Path, skills: Path) -> Path:
+ return Path(shutil.copytree(skills / "alpha", tmp_path / relative))
+
+ return build
+
+
+def _new_nested_alpha(tmp_path: Path, skills: Path) -> Path:
+ # A new skill in the catalog tree with the same name and description but its own body.
+ nested = skills / "team" / "alpha"
+ nested.mkdir(parents=True)
+ (nested / "SKILL.md").write_text("---\nname: alpha\ndescription: Alpha catalog skill\n---\n\n# team alpha\n")
+ return nested
+
+
+def _filesystem_is_case_insensitive(directory: Path) -> bool:
+ probe = directory / "case-probe"
+ probe.write_text("")
+ try:
+ return (directory / "CASE-PROBE").exists()
+ finally:
+ probe.unlink()
+
+
+class TestCatalogSelfEntry:
+ def test_existing_skill_skips_only_its_own_entry(self, tmp_path: Path, write_skill) -> None:
+ skills = _write_skills(write_skill, tmp_path / "repo" / "skills", "alpha", "beta")
+ registry = _saved_catalog(tmp_path, skills)
+ target = _target(skills / "alpha")
+
+ self_entry = registry.catalog_self_entry(target)
+
+ assert self_entry is not None
+ assert self_entry.path == "alpha"
+ assert [match.classification for match in registry.query_entry(target, 0.75)] == ["EXACT_DUPLICATE"]
+ assert registry.query_entry(target, 0.75, exclude_entry_id=self_entry.entry_id) == []
+
+ @pytest.mark.parametrize("full_body", [False, True])
+ def test_another_checkout_of_the_catalog_tree_skips_its_own_entry(
+ self, tmp_path: Path, write_skill, full_body: bool
+ ) -> None:
+ build_skills = _write_skills(write_skill, tmp_path / "build" / "skills", "alpha", "beta", "gamma")
+ registry = _saved_catalog(tmp_path, build_skills, full_body=full_body)
+ shutil.copytree(tmp_path / "build", tmp_path / "ci")
+
+ self_entry = registry.catalog_self_entry(_target(tmp_path / "ci" / "skills" / "alpha"))
+
+ assert self_entry is not None
+ assert self_entry.path == "alpha"
+
+ @pytest.mark.parametrize("full_body", [False, True])
+ @pytest.mark.parametrize(
+ "make_target",
+ [
+ _copy_alpha_to("candidates/alpha"),
+ _copy_alpha_to("other-repo/skills/alpha"),
+ _copy_alpha_to("repo/skills/alpha-copy"),
+ _new_nested_alpha,
+ ],
+ ids=["candidates-copy", "other-repo-copy", "renamed-copy", "new-nested-same-name"],
+ )
+ def test_copies_and_same_name_skills_outside_the_catalog_tree_are_still_reported(
+ self, tmp_path: Path, write_skill, full_body: bool, make_target
+ ) -> None:
+ skills = _write_skills(write_skill, tmp_path / "repo" / "skills", "alpha", "beta")
+ registry = _saved_catalog(tmp_path, skills, full_body=full_body)
+ target = _target(make_target(tmp_path, skills))
+ assert target.name == "alpha"
+
+ assert registry.catalog_self_entry(target) is None
+ matches = registry.query_entry(target, 0.75)
+ assert [(match.path_b, match.classification) for match in matches] == [("alpha", "EXACT_DUPLICATE")]
+
+ def test_copies_of_a_few_catalog_skills_are_not_a_catalog_tree(self, tmp_path: Path, write_skill) -> None:
+ skills = _write_skills(write_skill, tmp_path / "repo" / "skills", *_SKILL_NAMES)
+ registry = _saved_catalog(tmp_path, skills)
+ for name in ("alpha", "beta"):
+ shutil.copytree(skills / name, tmp_path / "candidates" / name)
+
+ assert registry.catalog_self_entry(_target(tmp_path / "candidates" / "alpha")) is None
+
+ def test_catalog_tree_with_a_minority_of_edited_skills_still_skips(self, tmp_path: Path, write_skill) -> None:
+ skills = _write_skills(write_skill, tmp_path / "repo" / "skills", *_SKILL_NAMES)
+ registry = _saved_catalog(tmp_path, skills)
+ # Three of the four other catalog skills are still present unchanged.
+ manifest = skills / "beta" / "SKILL.md"
+ manifest.write_text(manifest.read_text().replace("catalog skill", "catalog skill, revised"))
+
+ self_entry = registry.catalog_self_entry(_target(skills / "alpha"))
+
+ assert self_entry is not None
+ assert self_entry.path == "alpha"
+
+ def test_catalog_without_another_skill_entry_never_skips(self, tmp_path: Path, write_skill) -> None:
+ skills = _write_skills(write_skill, tmp_path / "repo" / "skills", "alpha")
+ registry = _saved_catalog(tmp_path, skills)
+
+ assert registry.catalog_self_entry(_target(skills / "alpha")) is None
+
+ def test_skills_nested_in_the_target_are_not_catalog_tree_evidence(self, tmp_path: Path, write_skill) -> None:
+ skills = _write_skills(write_skill, tmp_path / "repo" / "skills", "alpha", "beta")
+ _write_skills(write_skill, skills / "alpha", "gamma", "delta")
+ registry = _saved_catalog(tmp_path, skills)
+ candidate = Path(shutil.copytree(skills / "alpha", tmp_path / "candidates" / "alpha"))
+
+ assert registry.catalog_self_entry(_target(candidate)) is None
+ assert registry.catalog_self_entry(_target(skills / "alpha")) is not None
+
+ def test_linked_catalog_skill_is_not_catalog_tree_evidence(self, tmp_path: Path, write_skill) -> None:
+ skills = _write_skills(write_skill, tmp_path / "repo" / "skills", "alpha", "beta")
+ registry = _saved_catalog(tmp_path, skills)
+ candidate = Path(shutil.copytree(skills / "alpha", tmp_path / "candidates" / "alpha"))
+ try:
+ (tmp_path / "candidates" / "beta").symlink_to(skills / "beta", target_is_directory=True)
+ except OSError as exc:
+ pytest.skip(f"symlinks unavailable: {exc}")
+
+ assert registry.catalog_self_entry(_target(candidate)) is None
+
+ def test_catalog_tree_evidence_reads_a_bounded_sample(self, tmp_path: Path, write_skill, monkeypatch) -> None:
+ others = [f"skill-{index:02d}" for index in range(12)]
+ skills = _write_skills(write_skill, tmp_path / "repo" / "skills", "alpha", *others)
+ registry = _saved_catalog(tmp_path, skills)
+ target = _target(skills / "alpha")
+ reads: list[str] = []
+
+ def counting_extract(skill_dir: Path) -> ContentEntry | None:
+ reads.append(skill_dir.name)
+ return extract_from_skill(skill_dir)
+
+ monkeypatch.setattr(registry_module, "extract_from_skill", counting_extract)
+
+ assert registry.catalog_self_entry(target) is not None
+ # The sample is spread evenly across the sorted list, not its first entries.
+ assert reads == [others[index] for index in (0, 1, 3, 4, 6, 7, 9, 10)]
+
+ def test_staging_copy_of_the_first_sorted_catalog_skills_is_not_a_catalog_tree(
+ self, tmp_path: Path, write_skill
+ ) -> None:
+ others = [f"skill-{index:02d}" for index in range(39)]
+ skills = _write_skills(write_skill, tmp_path / "repo" / "skills", "alpha", *others)
+ registry = _saved_catalog(tmp_path, skills)
+ staging = tmp_path / "staging"
+ for name in ("alpha", *others[:5]):
+ shutil.copytree(skills / name, staging / name)
+
+ assert registry.catalog_self_entry(_target(staging / "alpha")) is None
+
+ def test_catalog_tree_missing_some_first_sorted_skills_still_skips(self, tmp_path: Path, write_skill) -> None:
+ others = [f"skill-{index:02d}" for index in range(39)]
+ skills = _write_skills(write_skill, tmp_path / "repo" / "skills", "alpha", *others)
+ registry = _saved_catalog(tmp_path, skills)
+ # Four of the first eight other skills are gone; 35 of the 39 are intact.
+ for name in others[0:8:2]:
+ shutil.rmtree(skills / name)
+
+ self_entry = registry.catalog_self_entry(_target(skills / "alpha"))
+
+ assert self_entry is not None
+ assert self_entry.path == "alpha"
+
+ def test_longest_catalog_path_identifies_the_target(self, tmp_path: Path, write_skill) -> None:
+ repo = tmp_path / "repo"
+ _write_skills(write_skill, repo / "skills", "alpha")
+ _write_skills(write_skill, repo / "vendor" / "skills", "alpha")
+ registry = _saved_catalog(tmp_path, repo)
+ target = _target(repo / "vendor" / "skills" / "alpha")
+
+ self_entry = registry.catalog_self_entry(target)
+
+ assert self_entry is not None
+ assert self_entry.path == "vendor/skills/alpha"
+ matches = registry.query_entry(target, 0.75, exclude_entry_id=self_entry.entry_id)
+ assert [match.path_b for match in matches] == ["skills/alpha"]
+
+ @pytest.mark.parametrize(
+ ("full_body", "old_text", "new_text", "is_self"),
+ [
+ (False, "# alpha", "# alpha, revised body", True),
+ (False, "Alpha catalog skill", "Alpha catalog skill, revised", False),
+ (True, "# alpha", "# alpha, revised body", False),
+ ],
+ )
+ def test_edited_skill_matches_its_entry_only_while_compared_content_is_unchanged(
+ self,
+ tmp_path: Path,
+ write_skill,
+ full_body: bool,
+ old_text: str,
+ new_text: str,
+ is_self: bool,
+ ) -> None:
+ skills = _write_skills(write_skill, tmp_path / "skills", "alpha", "beta")
+ registry = _saved_catalog(tmp_path, skills, full_body=full_body)
+ manifest = skills / "alpha" / "SKILL.md"
+ manifest.write_text(manifest.read_text().replace(old_text, new_text))
+
+ assert (registry.catalog_self_entry(_target(skills / "alpha")) is not None) is is_self
+
+ def test_scan_root_entry_never_identifies_a_target(self, tmp_path: Path, write_skill) -> None:
+ # A catalog built from one skill root records it as ".", which carries no path evidence.
+ alpha = write_skill(tmp_path / "skills", "alpha", "Alpha catalog skill")
+ registry = _saved_catalog(tmp_path, alpha)
+
+ assert registry.catalog_self_entry(_target(alpha)) is None
+
+ def test_differently_cased_target_path(self, tmp_path: Path, write_skill) -> None:
+ skills = _write_skills(write_skill, tmp_path / "skills", "alpha", "beta")
+ registry = _saved_catalog(tmp_path, skills)
+ if _filesystem_is_case_insensitive(tmp_path):
+ # The same directory, spelled differently, is still the catalog's own entry.
+ self_entry = registry.catalog_self_entry(_target(skills / "ALPHA"))
+ assert self_entry is not None
+ assert self_entry.path == "alpha"
+ else:
+ # A separate directory that differs only in case is a copy.
+ shutil.copytree(skills / "alpha", skills / "ALPHA")
+ assert registry.catalog_self_entry(_target(skills / "ALPHA")) is None
diff --git a/tests/validators/test_similarity.py b/tests/validators/test_similarity.py
index 5d7617b6..76fc863e 100644
--- a/tests/validators/test_similarity.py
+++ b/tests/validators/test_similarity.py
@@ -6,12 +6,14 @@
from __future__ import annotations
import math
+import shutil
from pathlib import Path
+from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import pytest
-from skillevaluator.embedding.client import SimilarityConfigError
+from skillevaluator.embedding.client import EmbeddingClient, SimilarityConfigError
from skillevaluator.embedding.extractor import ContentEntry
from skillevaluator.embedding.registry import SimilarityMatch
from skillevaluator.models.result import Severity
@@ -266,6 +268,7 @@ class TestValidateCacheWorkflow:
mock_registry = MagicMock()
mock_registry.size = 2
+ mock_registry.catalog_self_entry.return_value = None
mock_registry.query_entry.return_value = []
mock_registry_cls.return_value = mock_registry
target = ContentEntry(
@@ -281,7 +284,7 @@ class TestValidateCacheWorkflow:
result = validator.validate(tmp_path)
mock_registry.load_catalog.assert_called_once_with(cache_file)
- mock_registry.query_entry.assert_called_once_with(target, 0.75)
+ mock_registry.query_entry.assert_called_once_with(target, 0.75, exclude_entry_id=None)
assert result.passed
@patch("skillevaluator.validators.similarity.EmbeddingRegistry")
@@ -382,12 +385,14 @@ class TestLocalCatalogWorkflow:
mock_extract.return_value = target
registry = mock_registry_cls.return_value
registry.size = 3
+ registry.catalog_self_entry.return_value = None
registry.query_entry.return_value = []
result = SimilarityValidator(content_type="skill", catalog_path=catalog).validate(tmp_path / "candidate")
registry.load_catalog.assert_called_once_with(catalog)
- registry.query_entry.assert_called_once_with(target, 0.75)
+ registry.catalog_self_entry.assert_called_once_with(target)
+ registry.query_entry.assert_called_once_with(target, 0.75, exclude_entry_id=None)
registry.find_duplicates.assert_not_called()
assert result.passed
assert any("3 catalog entries" in detail.message for detail in result.success_details)
@@ -421,6 +426,7 @@ class TestLocalCatalogWorkflow:
(nested / "SKILL.md").write_text("---\nname: nested-skill\ndescription: Nested reference skill\n---\n")
registry = mock_registry_cls.return_value
registry.size = 1
+ registry.catalog_self_entry.return_value = None
registry.query_entry.return_value = []
result = SimilarityValidator(content_type="skill", catalog_path=catalog).validate(target)
@@ -428,6 +434,7 @@ class TestLocalCatalogWorkflow:
assert result.passed
queried_entry = registry.query_entry.call_args.args[0]
assert queried_entry.name == "root-skill"
+ assert registry.query_entry.call_args.kwargs == {"exclude_entry_id": None}
@patch("skillevaluator.validators.similarity.extract_from_skill")
@patch("skillevaluator.validators.similarity.EmbeddingRegistry")
@@ -446,6 +453,7 @@ class TestLocalCatalogWorkflow:
(tmp_path / "candidate").mkdir()
mock_extract.return_value = target
mock_registry_cls.return_value.size = 1
+ mock_registry_cls.return_value.catalog_self_entry.return_value = None
mock_registry_cls.return_value.query_entry.return_value = [
SimilarityMatch(
entry_a="shared-name",
@@ -460,6 +468,7 @@ class TestLocalCatalogWorkflow:
result = SimilarityValidator(content_type="skill", catalog_path=catalog).validate(tmp_path / "candidate")
+ mock_registry_cls.return_value.query_entry.assert_called_once_with(target, 0.75, exclude_entry_id=None)
finding = result.findings[0]
assert "Target skill 'shared-name'" in finding.message
assert "catalog skill 'shared-name'" in finding.message
@@ -524,3 +533,55 @@ class TestLocalCatalogWorkflow:
def test_similarity_validator_rejects_invalid_threshold(threshold: float) -> None:
with pytest.raises(ValueError, match=r"finite.*\[0, 1\]"):
SimilarityValidator(threshold=threshold)
+
+
+def _keyed_embedding_client(model: str | None = None) -> EmbeddingClient:
+ """Embed alpha and beta skills as orthogonal vectors."""
+
+ def embed_one(text: str) -> list[float]:
+ return [0.0, 1.0] if "beta" in text else [1.0, 0.0]
+
+ client = MagicMock(spec=EmbeddingClient)
+ client.embed.side_effect = lambda texts: [embed_one(text) for text in texts]
+ client.embed_single.side_effect = embed_one
+ client.embed_chunked.side_effect = embed_one
+ client.model = "test-model"
+ client._resolved_config.return_value = SimpleNamespace(
+ provider="nv_build",
+ base_url="https://integrate.api.nvidia.com/v1",
+ )
+ return client
+
+
+class TestCatalogSelfEntry:
+ @patch("skillevaluator.validators.similarity.EmbeddingClient", side_effect=_keyed_embedding_client)
+ def test_rescreening_a_cataloged_skill_skips_only_its_own_entry(self, _mock_client_cls, tmp_path: Path) -> None:
+ skills = tmp_path / "repo" / "skills"
+ for name in ("alpha", "beta"):
+ (skills / name).mkdir(parents=True)
+ (skills / name / "SKILL.md").write_text(f"---\nname: {name}\ndescription: {name} catalog skill\n---\n")
+ catalog = tmp_path / "catalog.json"
+ assert SimilarityValidator(content_type="skill", save_catalog_path=catalog).validate(skills).passed
+ # Verbatim copies that would pass Tier 1 (directory named after the skill), outside the catalog tree.
+ copies = [
+ Path(shutil.copytree(skills / "alpha", tmp_path / location / "alpha"))
+ for location in ("candidates", "other-repo/skills")
+ ]
+
+ existing = SimilarityValidator(content_type="skill", catalog_path=catalog).validate(skills / "alpha")
+
+ assert existing.passed
+ assert existing.findings == []
+ compared = next(detail for detail in existing.success_details if detail.check_name == "catalog_compared")
+ assert compared.metadata["self_matches_excluded"] == 1
+ assert compared.metadata["excluded_catalog_paths"] == ["alpha"]
+ assert "against 1 other catalog entries; skipped its own entry 'alpha'" in compared.message
+ for copy_dir in copies:
+ copy = SimilarityValidator(content_type="skill", catalog_path=catalog).validate(copy_dir)
+ assert not copy.passed
+ assert [(finding.check_name, finding.metadata["path_b"]) for finding in copy.findings] == [
+ ("EXACT_DUPLICATE", "alpha")
+ ]
+ compared = next(detail for detail in copy.success_details if detail.check_name == "catalog_compared")
+ assert compared.metadata["self_matches_excluded"] == 0
+ assert compared.metadata["excluded_catalog_paths"] == []