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): expose collection coverage and transactional rebuilds (#436)

Narendran Raghavan2bd67ca6ce62
diff --git a/CHANGELOG.md b/CHANGELOG.md
index edff1e18..18e6a7d5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -85,6 +85,14 @@ All notable changes to SkillEvaluator are documented in this file.
gaps in text and JSON. Generated one-case starters now explain their limits
and point authors to full dataset generation and coverage validation.
+- Collection similarity reports selected, indexed and skipped manifests with bounded
+ exclusion reasons. Malformed selected manifests now make the scan incomplete and
+ block catalog writes. A standalone synthetic scale benchmark records limits and
+ stage measurements without provider requests. Reused Python registries now
+ replace the complete selection on successful builds and preserve committed
+ entries, vector dimensions and coverage together on failure; callers that
+ relied on undocumented merging must pass their complete intended selection.
+
- Document an additive qualitative assessment review worksheet with bounded
evidence from real successful, failed-setup and invalid-judge runs. Preserve
numeric grading and identify the separate decisions needed for scoreless support.
diff --git a/docs/tier2-deduplication.mdx b/docs/tier2-deduplication.mdx
index 5b65229a..e8606879 100644
--- a/docs/tier2-deduplication.mdx
+++ b/docs/tier2-deduplication.mdx
@@ -262,6 +262,28 @@ skillevaluator similarity-check ./skills --max-entries 500 --max-scalar-comparis
The entry budget counts selected manifests even when their frontmatter is
invalid. It applies before any embedding request and never truncates a scan.
+Every selected manifest is accounted for: reports include `collection_coverage`
+with `selected_count`, `indexed_count`, and `skipped_count`. Here indexed means
+valid manifests eligible for embedding; a provider or work-limit error can still
+stop the index build. Missing frontmatter, malformed YAML, a non-mapping header,
+or missing name/title or description produces an exclusion reason. Up to 100
+exclusions are listed with collection-relative paths (each bounded to 512
+characters); `omitted_exclusions` counts additional diagnostics. An excluded
+manifest makes the scan **INCOMPLETE** and blocking, even when the indexed subset
+has no matches. Matches in the valid subset remain available. Fix excluded
+manifests and rerun; an incomplete collection cannot replace or create a saved
+catalog. Unsafe paths and input limits continue to stop discovery outright.
+
+For Python callers reusing an `EmbeddingRegistry`, each successful
+`build_from_directory()` or `build_from_paths()` replaces the entire indexed
+selection, vector dimensions and committed coverage. An empty directory build
+clears the index. A failed build preserves the prior index and its catalog-saving
+eligibility; `latest_attempt_coverage` retains the attempted directory selection
+for error diagnostics. Builds do not append: pass the complete intended
+selection when rebuilding a registry. This replaces the previous undocumented
+merge behavior, which could retain stale entries or discard incomplete-coverage
+provenance.
+
Fresh pairwise scans check the comparison budget after the first validated
embedding batch (or first full-body vector), before requesting the remaining
embeddings or saving a catalog. Python index-only builds remain available for
@@ -282,6 +304,39 @@ For a saved catalog query, `--max-entries` does not reduce the catalog's existin
5,000-entry capacity. Its comparison work is `catalog entries * dimensions`,
bounded by `--max-scalar-comparisons`.
+### Reproduce scale and limit measurements
+
+The repository includes `scripts/benchmark_tier2_scale.py` as a separate CLI,
+so scale runs do not add runtime to the unit suite:
+
+```bash title="Synthetic limit matrix (no provider requests)"
+uv run python scripts/benchmark_tier2_scale.py --output /tmp/tier2-scale.json
+```
+
+The default matrix covers 1,024, 2,500 and 5,000 selected manifests, flat and
+nested layouts, one supporting file per skill, clean and malformed collections,
+and description and full-body modes. It measures extraction, index building,
+all-pairs scans, catalog save/load, saved candidate queries when a catalog fits,
+and fresh-scan comparison preflight. JSON records stage wall time and peak
+Python allocations, coverage, vector dimensions, scalar work, index bytes,
+budget overrides, and synthetic embedding calls/input bytes. Provider tokens are
+unmeasured (`null`); the client makes zero provider requests. Full-body synthetic
+vectors do not simulate provider token chunking or HTTP request latency.
+
+These are synthetic limit measurements, **not production throughput or embedding
+quality claims**. Memory tracing adds runtime overhead and excludes native
+allocations. At 2,048 dimensions, even 1,024 entries exceed the default all-pairs
+work budget; 5,000 need 25,594,880,000 scalar operations. A catalog can also exceed
+the independent 32 MiB serialized-file ceiling. The benchmark records these
+rejections instead of raising limits silently; saved candidate queries run only
+when serialization succeeds. Use a measured real provider/catalog workload to
+establish an operational envelope for your model and machine.
+
+```bash title="Small smoke run; then explicitly allow a measured workload"
+uv run python scripts/benchmark_tier2_scale.py --sizes 8 --dimensions 64 --output /tmp/tier2-smoke.json
+uv run python scripts/benchmark_tier2_scale.py --sizes 1024 --layouts flat --modes description --malformed-counts 0 --max-scalar-comparisons 1072693248 --output /tmp/tier2-1024.json
+```
+
## Use a local catalog
For repeated screening — say, every new skill submission against your team's
diff --git a/scripts/benchmark_tier2_scale.py b/scripts/benchmark_tier2_scale.py
new file mode 100644
index 00000000..ff925dab
--- /dev/null
+++ b/scripts/benchmark_tier2_scale.py
@@ -0,0 +1,243 @@
+#!/usr/bin/env python3
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+"""Reproducible synthetic Tier 2 scale/limit measurements; never calls a provider.
+
+Run with the project's Python environment. Results measure the real discovery,
+registry, all-pairs, serialization and saved-candidate paths, but synthetic
+one-hot vectors do not establish production embedding latency or match quality.
+Each stage records Python allocation peaks (tracemalloc slows computation).
+"""
+
+from __future__ import annotations
+
+import argparse
+import gc
+import json
+import platform
+import re
+import sys
+import tempfile
+import time
+import tracemalloc
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+from skillevaluator.constants import SIMILARITY_DEFAULT_MAX_SCALAR_COMPARISONS
+from skillevaluator.embedding.extractor import (
+ MAX_COLLECTION_BYTES,
+ MAX_DISCOVERED_PATHS,
+ MAX_MANIFEST_BYTES,
+ discover_and_extract_detailed,
+ extract_from_skill,
+)
+from skillevaluator.embedding.registry import (
+ MAX_CATALOG_BYTES,
+ MAX_SIMILARITY_MATCHES,
+ MAX_VECTOR_DIMENSION,
+ EmbeddingRegistry,
+)
+
+
+class SyntheticClient:
+ """Deterministic sparse vectors for exercising limits, with zero paid usage."""
+
+ model = "synthetic-one-hot-v1"
+
+ def __init__(self, dimension: int) -> None:
+ self.dimension = dimension
+ self.embedding_calls = 0
+ self.embedding_inputs = 0
+ self.input_utf8_bytes = 0
+
+ def _resolved_config(self) -> SimpleNamespace:
+ return SimpleNamespace(provider="synthetic", base_url="https://synthetic.invalid/v1")
+
+ def embed(self, texts: list[str]) -> list[list[float]]:
+ self.embedding_calls += 1
+ self.embedding_inputs += len(texts)
+ self.input_utf8_bytes += sum(len(text.encode("utf-8")) for text in texts)
+ vectors = []
+ for text in texts:
+ match = re.search(r"skill-(\d+)", text)
+ index = int(match[1]) if match else 0
+ vector = [0.0] * self.dimension
+ vector[index % self.dimension] = 1.0
+ vectors.append(vector)
+ return vectors
+
+ def embed_single(self, text: str) -> list[float]:
+ return self.embed([text])[0]
+
+ def embed_chunked(self, text: str) -> list[float]:
+ # Deliberately one synthetic vector; does not simulate production token
+ # chunking, pooling, HTTP calls, token usage or provider batch latency.
+ return self.embed_single(text)
+
+
+def measure(stages: dict[str, Any], name: str, action):
+ gc.collect()
+ tracemalloc.reset_peak()
+ started = time.perf_counter()
+ try:
+ value = action()
+ except (ValueError, OSError) as exc:
+ stages[name] = {"status": "rejected", "reason": str(exc)}
+ value = None
+ else:
+ stages[name] = {"status": "ok"}
+ stages[name].update(seconds=time.perf_counter() - started, peak_python_bytes=tracemalloc.get_traced_memory()[1])
+ return value
+
+
+def populate(root: Path, size: int, layout: str, supporting: int, malformed: int) -> None:
+ for index in range(size):
+ parent = root if layout == "flat" else root / f"group-{index // 100:03d}" / "skills"
+ skill = parent / f"skill-{index:05d}"
+ skill.mkdir(parents=True)
+ text = (
+ "---\nname: [invalid\n---\n"
+ if index >= size - malformed
+ else f"---\nname: skill-{index:05d}\ndescription: Synthetic task {index}\n---\n\n# Procedure\nSynthetic benchmark instructions.\n"
+ )
+ (skill / "SKILL.md").write_text(text, encoding="utf-8")
+ for number in range(supporting):
+ (skill / f"reference-{number}.txt").write_text("Synthetic supporting file.\n", encoding="utf-8")
+
+
+def run_case(args: argparse.Namespace, size: int, layout: str, mode: str, malformed: int) -> dict[str, Any]:
+ client = SyntheticClient(args.dimensions)
+ stages: dict[str, Any] = {}
+ result: dict[str, Any] = {
+ "embedding_model": client.model,
+ "vector_source": "synthetic one-hot; no production quality or latency model",
+ "size": size,
+ "layout": layout,
+ "mode": mode,
+ "supporting_files_per_skill": args.supporting_files,
+ "malformed_manifests": malformed,
+ "dimensions": args.dimensions,
+ "budgets": {"max_entries": size, "max_scalar_comparisons": args.max_scalar_comparisons},
+ "fixed_limits": {
+ "discovered_paths": MAX_DISCOVERED_PATHS,
+ "manifest_bytes": MAX_MANIFEST_BYTES,
+ "collection_bytes": MAX_COLLECTION_BYTES,
+ "catalog_bytes": MAX_CATALOG_BYTES,
+ "vector_dimensions": MAX_VECTOR_DIMENSION,
+ "result_count": MAX_SIMILARITY_MATCHES,
+ },
+ "stages": stages,
+ }
+ tracemalloc.start()
+ with tempfile.TemporaryDirectory(prefix="tier2-scale-") as temporary:
+ root = Path(temporary) / "collection"
+ root.mkdir()
+ measure(stages, "fixture_generation", lambda: populate(root, size, layout, args.supporting_files, malformed))
+ coverage = measure(stages, "extraction", lambda: discover_and_extract_detailed(root, "skill", max_entries=size))
+ if coverage is not None:
+ result["coverage"] = coverage.to_metadata()
+ registry = EmbeddingRegistry(
+ client, full_body=mode == "full-body", max_entries=size, max_scalar_comparisons=args.max_scalar_comparisons
+ )
+ # Index-only build permits the saved-candidate workflow even when a
+ # collection's all-pairs workload exceeds the independent work budget.
+ built = measure(
+ stages, "index_build_including_extraction", lambda: registry.build_from_directory(root, "skill")
+ )
+ if built is not None:
+ result["pairwise_scalar_work"] = built * (built - 1) // 2 * args.dimensions
+ result["candidate_scalar_work"] = built * args.dimensions
+ matches = measure(stages, "all_pairs", lambda: registry.find_duplicates(0.75))
+ if matches is not None:
+ result["all_pairs_matches"] = len(matches)
+ catalog = Path(temporary) / "catalog.json"
+ measure(stages, "catalog_save", lambda: registry.save_catalog(catalog))
+ result["index_bytes"] = catalog.stat().st_size if catalog.exists() else None
+ if catalog.exists():
+ loaded = EmbeddingRegistry(
+ client,
+ full_body=mode == "full-body",
+ max_entries=size,
+ max_scalar_comparisons=args.max_scalar_comparisons,
+ )
+ measure(stages, "catalog_load", lambda: loaded.load_catalog(catalog))
+ target_path = (
+ root / "skill-00000" if layout == "flat" else root / "group-000" / "skills" / "skill-00000"
+ )
+ target = extract_from_skill(target_path)
+ own = loaded.catalog_self_entry(target)
+ matches = measure(
+ stages,
+ "saved_candidate_query",
+ lambda: loaded.query_entry(target, 0.75, exclude_entry_id=own.entry_id if own else None),
+ )
+ if matches is not None:
+ result["candidate_matches"] = len(matches)
+ result["self_entries_excluded"] = int(own is not None)
+ # Separately exercise fresh-scan preflight, including its early stop
+ # after the first batch when all-pairs work is over budget.
+ preflight = EmbeddingRegistry(
+ client, full_body=mode == "full-body", max_entries=size, max_scalar_comparisons=args.max_scalar_comparisons
+ )
+ measure(
+ stages,
+ "fresh_pairwise_build",
+ lambda: preflight.build_from_directory(root, "skill", for_pairwise_scan=True),
+ )
+ result["synthetic_usage"] = {
+ "embedding_calls": client.embedding_calls,
+ "embedding_inputs": client.embedding_inputs,
+ "input_utf8_bytes": client.input_utf8_bytes,
+ }
+ result["provider_usage"] = {
+ "provider": "none",
+ "calls": 0,
+ "tokens": None,
+ "note": "Synthetic embed_chunked does not measure production tokenization or requests",
+ }
+ tracemalloc.stop()
+ return result
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--sizes", type=int, nargs="+", default=[1024, 2500, 5000])
+ parser.add_argument("--layouts", choices=["flat", "nested"], nargs="+", default=["flat", "nested"])
+ parser.add_argument(
+ "--modes", choices=["description", "full-body"], nargs="+", default=["description", "full-body"]
+ )
+ parser.add_argument("--malformed-counts", type=int, nargs="+", default=[0, 1])
+ parser.add_argument("--supporting-files", type=int, default=1)
+ parser.add_argument("--dimensions", type=int, default=2048)
+ parser.add_argument("--max-scalar-comparisons", type=int, default=SIMILARITY_DEFAULT_MAX_SCALAR_COMPARISONS)
+ parser.add_argument("--output", type=Path, required=True)
+ args = parser.parse_args()
+ if any(not 2 <= size <= 5000 for size in args.sizes) or not 1 <= args.dimensions <= 65536:
+ parser.error("sizes must be 2..5000 and dimensions 1..65536")
+ if args.max_scalar_comparisons < 1:
+ parser.error("max-scalar-comparisons must be positive")
+ if args.supporting_files < 0 or any(count < 0 or count > min(args.sizes) for count in args.malformed_counts):
+ parser.error("supporting files and malformed counts must be nonnegative; malformed counts must fit every size")
+ output = {
+ "kind": "synthetic-limit-benchmark",
+ "production_performance_claim": False,
+ "python": sys.version,
+ "platform": platform.platform(),
+ "command": sys.argv,
+ "memory_measurement": "tracemalloc stage peak absolute Python allocations; excludes native allocations; tracing adds runtime overhead",
+ "cases": [],
+ }
+ for size in args.sizes:
+ for layout in args.layouts:
+ for mode in args.modes:
+ for malformed in args.malformed_counts:
+ output["cases"].append(run_case(args, size, layout, mode, malformed))
+ args.output.parent.mkdir(parents=True, exist_ok=True)
+ args.output.write_text(json.dumps(output, indent=2) + "\n", encoding="utf-8")
+ print(f"Recorded {size} {layout} {mode} malformed={malformed}", flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/skillevaluator/embedding/extractor.py b/src/skillevaluator/embedding/extractor.py
index 6b1a66d0..42581073 100644
--- a/src/skillevaluator/embedding/extractor.py
+++ b/src/skillevaluator/embedding/extractor.py
@@ -12,7 +12,7 @@ from __future__ import annotations
import os
import stat
-from dataclasses import dataclass
+from dataclasses import dataclass, field
from pathlib import Path
import yaml
@@ -46,6 +46,8 @@ MAX_MANIFEST_BYTES = CONTENT_DEDUP_MAX_FILE_BYTES
MAX_COLLECTION_BYTES = CONTENT_DEDUP_MAX_TOTAL_BYTES
MAX_DISCOVERED_PATHS = SIMILARITY_MAX_DISCOVERED_PATHS
DISCOVERY_EXCLUDED_DIRS = SCAN_EXCLUDED_DIRS
+MAX_EXTRACTION_EXCLUSIONS = 100
+MAX_EXCLUSION_PATH_CHARS = 512
@dataclass
@@ -72,6 +74,37 @@ class ContentEntry:
return f"{self.name}: {self.description}"
+@dataclass
+class ExtractionResult:
+ """Selected-manifest coverage, with a bounded inventory of exclusions.
+
+ ``indexed_count`` counts entries eligible for embedding; provider and index
+ errors still abort the build independently. Paths are relative to the scan
+ root and reasons never include manifest content or YAML parser excerpts.
+ """
+
+ entries: list[ContentEntry]
+ selected_count: int
+ exclusions: list[dict[str, str]]
+
+ @property
+ def indexed_count(self) -> int:
+ return len(self.entries)
+
+ @property
+ def skipped_count(self) -> int:
+ return self.selected_count - self.indexed_count
+
+ def to_metadata(self) -> dict[str, object]:
+ return {
+ "selected_count": self.selected_count,
+ "indexed_count": self.indexed_count,
+ "skipped_count": self.skipped_count,
+ "exclusions": self.exclusions,
+ "omitted_exclusions": self.skipped_count - len(self.exclusions),
+ }
+
+
@dataclass
class _ExtractionBudget:
"""Tracks collection bounds before any embedding request is made."""
@@ -79,6 +112,13 @@ class _ExtractionBudget:
max_entries: int = SIMILARITY_DEFAULT_MAX_ENTRIES
entry_count: int = 0
total_bytes: int = 0
+ root: Path | None = None
+ exclusions: list[dict[str, str]] = field(default_factory=list)
+
+ def exclude(self, path: Path, reason: str) -> None:
+ if len(self.exclusions) < MAX_EXTRACTION_EXCLUSIONS:
+ label = path.relative_to(self.root).as_posix() if self.root is not None else path.name
+ self.exclusions.append({"path": label[:MAX_EXCLUSION_PATH_CHARS], "reason": reason})
def reserve(self, file_path: Path, declared_bytes: int) -> None:
self.entry_count += 1
@@ -197,15 +237,26 @@ def discover_and_extract(
Returns:
List of successfully extracted ContentEntry objects.
"""
+ return discover_and_extract_detailed(root, content_type, max_entries=max_entries).entries
+
+
+def discover_and_extract_detailed(
+ root: Path, content_type: str, *, max_entries: int = SIMILARITY_DEFAULT_MAX_ENTRIES
+) -> ExtractionResult:
+ """Extract entries while accounting for every selected manifest.
+
+ Unsafe paths, read failures and resource limits continue to abort discovery;
+ only malformed frontmatter is excluded with a structured reason.
+ """
validate_max_entries(max_entries)
strategy = _DISCOVERY_STRATEGIES.get(content_type)
if strategy is None:
logger.warning("Unknown content type '%s' for discovery", content_type)
- return []
-
- entries = strategy(root, _ExtractionBudget(max_entries=max_entries))
+ return ExtractionResult([], 0, [])
+ budget = _ExtractionBudget(max_entries=max_entries, root=root)
+ entries = strategy(root, budget)
logger.debug("Discovered %d %s entries in %s", len(entries), content_type, safe_path_label(root))
- return entries
+ return ExtractionResult(entries, budget.entry_count, budget.exclusions)
# ---------------------------------------------------------------------------
@@ -267,6 +318,8 @@ def _extract_from_file(
)
match = FRONTMATTER_PATTERN.match(full_text)
if not match:
+ if budget is not None:
+ budget.exclude(file_path, "missing_frontmatter")
logger.debug("Missing YAML frontmatter in %s", file_path)
return None
@@ -274,15 +327,21 @@ def _extract_from_file(
try:
data = yaml.safe_load(frontmatter_yaml)
except yaml.YAMLError as exc:
+ if budget is not None:
+ budget.exclude(file_path, "invalid_yaml")
logger.debug("Invalid YAML frontmatter in %s: %s", file_path, exc)
return None
if not data or not isinstance(data, dict):
+ if budget is not None:
+ budget.exclude(file_path, "invalid_frontmatter_mapping")
logger.debug("Frontmatter in %s is not a non-empty mapping", file_path)
return None
name = data.get(name_field)
description = data.get(description_field)
if not name or not description:
+ if budget is not None:
+ budget.exclude(file_path, "missing_name_or_description")
logger.debug(
"Missing %s or %s in %s",
name_field,
diff --git a/src/skillevaluator/embedding/registry.py b/src/skillevaluator/embedding/registry.py
index ccf2cb11..46fa01fd 100644
--- a/src/skillevaluator/embedding/registry.py
+++ b/src/skillevaluator/embedding/registry.py
@@ -48,7 +48,8 @@ from skillevaluator.embedding.client import (
from skillevaluator.embedding.extractor import (
MAX_MANIFEST_BYTES,
ContentEntry,
- discover_and_extract,
+ ExtractionResult,
+ discover_and_extract_detailed,
extract_from_skill,
)
from skillevaluator.embedding.limits import validate_max_entries, validate_max_scalar_comparisons
@@ -198,11 +199,23 @@ class EmbeddingRegistry:
self._max_scalar_comparisons = max_scalar_comparisons
self._entries: dict[str, RegistryEntry] = {}
self._vector_dimension: int | None = None
+ self._coverage: ExtractionResult | None = None
+ self._latest_attempt_coverage: ExtractionResult | None = None
@property
def size(self) -> int:
return len(self._entries)
+ @property
+ def coverage(self) -> ExtractionResult | None:
+ """Coverage committed with the current index, if built from a directory."""
+ return self._coverage
+
+ @property
+ def latest_attempt_coverage(self) -> ExtractionResult | None:
+ """Last directory selection for diagnostics, including a failed build."""
+ return self._latest_attempt_coverage
+
def build_from_directory(
self,
root: Path,
@@ -211,7 +224,10 @@ class EmbeddingRegistry:
minimum_entries: int = 1,
for_pairwise_scan: bool = False,
) -> int:
- """Discover content items, embed them, and populate the index.
+ """Discover and embed a complete replacement selection.
+
+ Successful builds replace prior entries, dimensions and coverage, even
+ for an empty selection. Failures retain the previously committed index.
Set ``for_pairwise_scan`` when the caller will compare all entries.
The first validated response then checks the pairwise work budget
@@ -221,16 +237,19 @@ class EmbeddingRegistry:
Returns:
Number of entries successfully indexed.
"""
- content_entries = discover_and_extract(root, content_type, max_entries=self._max_entries)
- return self._build_entries(root, content_entries, minimum_entries, for_pairwise_scan)
+ self._latest_attempt_coverage = None
+ coverage = discover_and_extract_detailed(root, content_type, max_entries=self._max_entries)
+ self._latest_attempt_coverage = coverage
+ return self._build_entries(root, coverage.entries, minimum_entries, for_pairwise_scan, coverage=coverage)
def build_from_paths(self, root: Path, skills: list[Path]) -> int:
- """Index explicit skills across multiple roots under one trusted checkout.
+ """Replace the index with explicit skills under one trusted checkout.
Paths retain their checkout-relative identity, avoiding collisions when
separate skill roots contain folders with the same name. Validate every
input before the first credential-bearing embedding call.
"""
+ self._latest_attempt_coverage = None
root = root.resolve(strict=True)
unique = sorted(set(skills))
if not unique or len(unique) > self._max_entries:
@@ -260,8 +279,13 @@ class EmbeddingRegistry:
content_entries: list[ContentEntry],
minimum_entries: int,
for_pairwise_scan: bool,
+ *,
+ coverage: ExtractionResult | None = None,
) -> int:
if not content_entries:
+ self._entries = {}
+ self._vector_dimension = None
+ self._coverage = coverage
logger.debug("No content entries found in %s", safe_path_label(root))
return 0
if len(content_entries) < minimum_entries:
@@ -294,9 +318,9 @@ class EmbeddingRegistry:
)
)
- entry_count = len(self._entries.keys() | {entry.entry_id for entry in pending_entries})
+ entry_count = len({entry.entry_id for entry in pending_entries})
comparison_count = entry_count * (entry_count - 1) // 2
- vector_dimension = self._vector_dimension
+ vector_dimension: int | None = None
validated_vectors: list[list[float]] = []
batch_size = 1 if self._full_body else EMBEDDING_BATCH_SIZE
for start in range(0, len(texts), batch_size):
@@ -314,8 +338,9 @@ class EmbeddingRegistry:
for entry, vector in zip(pending_entries, validated_vectors, strict=True):
entry.embedding = vector
- self._entries.update((entry.entry_id, entry) for entry in pending_entries)
+ self._entries = {entry.entry_id: entry for entry in pending_entries}
self._vector_dimension = vector_dimension
+ self._coverage = coverage
logger.debug("Indexed %d entries from %s", len(self._entries), safe_path_label(root))
return len(self._entries)
@@ -514,6 +539,10 @@ class EmbeddingRegistry:
def save_catalog(self, catalog_path: Path) -> None:
"""Persist a validated, versioned local embedding catalog."""
+ if self._coverage is not None and self._coverage.skipped_count:
+ raise ValueError(
+ "Cannot save a catalog with incomplete collection coverage; fix excluded manifests and rebuild"
+ )
if not self._entries:
raise ValueError("Cannot save an empty catalog")
if len(self._entries) > MAX_CATALOG_ENTRIES:
@@ -649,6 +678,8 @@ class EmbeddingRegistry:
self._entries = loaded
self._vector_dimension = vector_dimension
+ self._coverage = None
+ self._latest_attempt_coverage = None
logger.debug("Loaded %d entries from local catalog %s", len(self._entries), safe_path_label(catalog_path))
def save_cache(self, cache_path: Path) -> None:
diff --git a/src/skillevaluator/validators/similarity.py b/src/skillevaluator/validators/similarity.py
index 30c1d259..42541771 100644
--- a/src/skillevaluator/validators/similarity.py
+++ b/src/skillevaluator/validators/similarity.py
@@ -19,7 +19,7 @@ from skillevaluator.constants import (
SIMILARITY_DEFAULT_THRESHOLD,
)
from skillevaluator.embedding.client import EmbeddingClient, SimilarityConfigError
-from skillevaluator.embedding.extractor import extract_from_skill
+from skillevaluator.embedding.extractor import ExtractionResult, extract_from_skill
from skillevaluator.embedding.limits import validate_max_entries, validate_max_scalar_comparisons
from skillevaluator.embedding.registry import EmbeddingRegistry, SimilarityMatch
from skillevaluator.logging_config import get_logger
@@ -163,6 +163,7 @@ class SimilarityValidator(ValidatorBase):
minimum_entries=minimum_entries,
for_pairwise_scan=True,
)
+ self._record_coverage(registry, result)
if count == 0:
if self._save_catalog_path:
result.add_error(f"Cannot save a catalog from an empty {content_type} collection")
@@ -176,13 +177,14 @@ class SimilarityValidator(ValidatorBase):
entry_count=count,
)
matches = registry.find_duplicates(self._threshold)
- if self._save_catalog_path:
+ if self._save_catalog_path and not result.is_incomplete:
registry.save_catalog(self._save_catalog_path)
result.add_success(
"catalog_saved",
f"Saved local catalog to {self._catalog_display_name(self._save_catalog_path)}",
)
except SimilarityConfigError as exc:
+ self._record_coverage(registry, result)
result.mark_scan_incomplete("embedding-provider")
result.add_error(
sanitize_path_text(
@@ -192,6 +194,7 @@ class SimilarityValidator(ValidatorBase):
)
return result
except (ValueError, OSError) as exc:
+ self._record_coverage(registry, result)
result.add_error(
sanitize_path_text(
str(exc),
@@ -206,7 +209,7 @@ class SimilarityValidator(ValidatorBase):
catalog_comparison=self._catalog_path is not None,
)
- if not matches:
+ if not matches and not result.is_incomplete:
result.add_success(
"similarity_check",
f"No duplicates detected (threshold: {self._threshold})",
@@ -227,6 +230,29 @@ class SimilarityValidator(ValidatorBase):
return detect_content_type(path)
+ @staticmethod
+ def _record_coverage(registry: EmbeddingRegistry, result: ValidationResult) -> None:
+ coverage = registry.latest_attempt_coverage
+ if not isinstance(coverage, ExtractionResult):
+ return
+ if any(detail.check_name == "collection_coverage" for detail in result.success_details):
+ return
+ result.add_success(
+ "collection_coverage",
+ f"Selected {coverage.selected_count}; indexed {coverage.indexed_count}; skipped {coverage.skipped_count} manifests",
+ **coverage.to_metadata(),
+ )
+ if coverage.skipped_count:
+ result.mark_scan_incomplete("collection-coverage")
+ excluded = "; ".join(f"{item['path']}: {item['reason']}" for item in coverage.exclusions)
+ omitted = coverage.skipped_count - len(coverage.exclusions)
+ if omitted:
+ excluded += f"; {omitted} additional exclusions omitted"
+ result.add_error(
+ f"Incomplete collection coverage: {coverage.skipped_count} selected manifests were excluded; "
+ f"fix the reported frontmatter errors and rerun. Any matches cover only indexed entries; no catalog saved. {excluded}"
+ )
+
@staticmethod
def _catalog_display_name(path: Path) -> str:
"""Return a result-safe catalog label without host directory details."""
diff --git a/tests/embedding/test_collection_coverage.py b/tests/embedding/test_collection_coverage.py
new file mode 100644
index 00000000..4cfbc50a
--- /dev/null
+++ b/tests/embedding/test_collection_coverage.py
@@ -0,0 +1,300 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+"""A valid subset must never stand in for collection coverage."""
+
+import json
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import MagicMock
+
+import pytest
+from click.testing import CliRunner
+
+from skillevaluator.cli import cli
+from skillevaluator.embedding import extractor
+from skillevaluator.embedding.client import EmbeddingClient, SimilarityConfigError
+from skillevaluator.embedding.registry import EmbeddingRegistry
+from skillevaluator.validators.similarity import SimilarityValidator
+
+
+def _collection(root: Path, malformed: int = 1) -> None:
+ for name, description in [("alpha", "Analyze logs"), ("beta", "Build packages")]:
+ path = root / name
+ path.mkdir(parents=True)
+ (path / "SKILL.md").write_text(f"---\nname: {name}\ndescription: {description}\n---\n")
+ for index in range(malformed):
+ path = root / f"broken-{index:03d}"
+ path.mkdir()
+ (path / "SKILL.md").write_text("---\nname: [invalid YAML\n---\n")
+
+
+def _client() -> MagicMock:
+ client = MagicMock(spec=EmbeddingClient)
+ client.model = "test-model"
+ client._resolved_config.return_value = SimpleNamespace(provider="openai", base_url="https://api.openai.com/v1")
+ client.embed.side_effect = lambda texts: [[1.0, 0.0] if "alpha" in text else [0.0, 1.0] for text in texts]
+ return client
+
+
+def test_detailed_extraction_counts_selected_and_bounds_relative_reasons(tmp_path: Path) -> None:
+ _collection(tmp_path, malformed=103)
+ detailed = extractor.discover_and_extract_detailed(tmp_path, "skill")
+ assert detailed.selected_count == 105
+ assert detailed.indexed_count == 2
+ assert detailed.skipped_count == 103
+ metadata = detailed.to_metadata()
+ assert len(metadata["exclusions"]) == 100
+ assert metadata["omitted_exclusions"] == 3
+ assert metadata["exclusions"][0] == {"path": "broken-000/SKILL.md", "reason": "invalid_yaml"}
+ assert str(tmp_path) not in json.dumps(metadata)
+ assert extractor.discover_and_extract(tmp_path, "skill") == detailed.entries
+ with pytest.raises(ValueError, match="entry limit"):
+ extractor.discover_and_extract_detailed(tmp_path, "skill", max_entries=104)
+
+
[email protected]("malformed", [0, 1])
+def test_validator_distinguishes_complete_from_incomplete_no_matches(
+ tmp_path: Path, monkeypatch, malformed: int
+) -> None:
+ _collection(tmp_path, malformed)
+ monkeypatch.setattr("skillevaluator.validators.similarity.EmbeddingClient", lambda **_kwargs: _client())
+ result = SimilarityValidator(content_type="skill").validate(tmp_path)
+ assert result.is_incomplete is bool(malformed)
+ assert result.passed is (not malformed)
+ details = [detail for detail in result.success_details if detail.check_name == "collection_coverage"]
+ assert len(details) == 1
+ assert details[0].metadata["selected_count"] == 2 + malformed
+ assert details[0].metadata["indexed_count"] == 2
+ assert details[0].metadata["skipped_count"] == malformed
+ assert any("No duplicates detected" in detail.message for detail in result.success_details) is (not malformed)
+
+
+def test_incomplete_coverage_is_saved_in_report_without_replacing_catalog(tmp_path: Path, monkeypatch) -> None:
+ root = tmp_path / "skills"
+ _collection(root)
+ monkeypatch.setattr("skillevaluator.validators.similarity.EmbeddingClient", lambda **_kwargs: _client())
+ catalog = tmp_path / "catalog.json"
+ catalog.write_text("original catalog")
+ reports = tmp_path / "reports"
+ result = CliRunner().invoke(
+ cli,
+ [
+ "similarity-check",
+ str(root),
+ "--type",
+ "skill",
+ "--save-catalog",
+ str(catalog),
+ "-r",
+ "json",
+ "-o",
+ str(reports),
+ ],
+ )
+ assert result.exit_code == 1, result.output
+ assert catalog.read_text() == "original catalog"
+ report = json.loads((reports / "skillevaluator-similarity.json").read_text())["results"][0]
+ coverage = next(
+ detail["metadata"] for detail in report["success_details"] if detail["check"] == "collection_coverage"
+ )
+ assert coverage["exclusions"] == [{"path": "broken-000/SKILL.md", "reason": "invalid_yaml"}]
+ assert report["status"] == "incomplete"
+
+
+def test_registry_rejects_partial_catalog_save(tmp_path: Path) -> None:
+ _collection(tmp_path)
+ registry = EmbeddingRegistry(_client())
+ assert registry.build_from_directory(tmp_path, "skill") == 2
+ with pytest.raises(ValueError, match="incomplete"):
+ registry.save_catalog(tmp_path / "catalog.json")
+ assert not (tmp_path / "catalog.json").exists()
+
+
+ "content_type,filename,name_field",
+ [("skill", "SKILL.md", "name"), ("rules", "rule.mdc", "title"), ("workflows", "workflow-rules.mdc", "title")],
+)
+def test_exclusion_reasons_account_for_every_selected_manifest(
+ tmp_path: Path, content_type: str, filename: str, name_field: str
+) -> None:
+ documents = ["No frontmatter", "---\n[]\n---\n", f"---\n{name_field}: example\n---\n"]
+ for index, document in enumerate(documents):
+ path = tmp_path / str(index)
+ path.mkdir()
+ (path / filename).write_text(document)
+ result = extractor.discover_and_extract_detailed(tmp_path, content_type)
+ assert result.selected_count == 3
+ assert result.indexed_count == 0
+ assert result.skipped_count == 3
+ assert [item["reason"] for item in result.exclusions] == [
+ "missing_frontmatter",
+ "invalid_frontmatter_mapping",
+ "missing_name_or_description",
+ ]
+
+
+def test_incomplete_coverage_preserves_valid_subset_findings(tmp_path: Path, monkeypatch) -> None:
+ _collection(tmp_path)
+ client = _client()
+ client.embed.side_effect = lambda texts: [[1.0, 0.0] for _ in texts]
+ monkeypatch.setattr("skillevaluator.validators.similarity.EmbeddingClient", lambda **_kwargs: client)
+ result = SimilarityValidator(content_type="skill").validate(tmp_path)
+ assert result.is_incomplete
+ assert len(result.findings) == 1
+ assert result.findings[0].check_name == "EXACT_DUPLICATE"
+ assert not any("No duplicates detected" in detail.message for detail in result.success_details)
+
+
+def test_too_few_valid_entries_still_reports_exclusions(tmp_path: Path, monkeypatch) -> None:
+ _collection(tmp_path)
+ (tmp_path / "beta" / "SKILL.md").unlink()
+ monkeypatch.setattr("skillevaluator.validators.similarity.EmbeddingClient", lambda **_kwargs: _client())
+ result = SimilarityValidator(content_type="skill").validate(tmp_path)
+ assert result.is_incomplete
+ assert any("broken-000/SKILL.md: invalid_yaml" in error for error in result.errors)
+ assert any("at least 2" in error for error in result.errors)
+
+
+def test_successful_explicit_rebuild_replaces_incomplete_selection(tmp_path: Path) -> None:
+ _collection(tmp_path)
+ registry = EmbeddingRegistry(_client())
+ registry.build_from_directory(tmp_path, "skill")
+ registry.build_from_paths(tmp_path, [tmp_path / "alpha", tmp_path / "beta"])
+ registry.save_catalog(tmp_path / "explicit.json")
+ assert (tmp_path / "explicit.json").is_file()
+
+
+def test_provider_failure_retains_selection_coverage(tmp_path: Path, monkeypatch) -> None:
+ _collection(tmp_path)
+ client = _client()
+ client.embed.side_effect = SimilarityConfigError("synthetic unavailable")
+ monkeypatch.setattr("skillevaluator.validators.similarity.EmbeddingClient", lambda **_kwargs: client)
+ result = SimilarityValidator(content_type="skill").validate(tmp_path)
+ assert result.is_incomplete
+ assert any(detail.check_name == "collection_coverage" for detail in result.success_details)
+ assert any("broken-000/SKILL.md: invalid_yaml" in error for error in result.errors)
+
+
+def _single_skill(root: Path, name: str) -> Path:
+ path = root / name
+ path.mkdir(parents=True)
+ (path / "SKILL.md").write_text(f"---\nname: {name}\ndescription: Task {name}\n---\n")
+ return path
+
+
[email protected]("initial_malformed", [0, 1])
[email protected]("failure", ["provider", "preflight", "minimum", "vector", "input"])
+def test_failed_build_preserves_committed_index_and_coverage(
+ tmp_path: Path, initial_malformed: int, failure: str
+) -> None:
+ first = tmp_path / "first"
+ _collection(first, initial_malformed)
+ second = tmp_path / "second"
+ _single_skill(second, "gamma")
+ _single_skill(second, "delta")
+ if not initial_malformed:
+ invalid = _single_skill(second, "broken")
+ (invalid / "SKILL.md").write_text("No valid frontmatter")
+ client = _client()
+ client.embed_single.return_value = [1.0, 0.0]
+ registry = EmbeddingRegistry(client, max_scalar_comparisons=1)
+ registry.build_from_directory(first, "skill")
+ committed_coverage = registry.coverage
+ original = {key: entry.embedding[:] for key, entry in registry._entries.items()}
+ if failure == "provider":
+ client.embed.side_effect = SimilarityConfigError("synthetic failure")
+ elif failure == "vector":
+ client.embed.side_effect = lambda texts: [[float("nan"), 0.0] for _ in texts]
+ elif failure == "input":
+ (second / "gamma" / "SKILL.md").write_text("---\nname: gamma\ndescription: " + "x" * 17000 + "\n---\n")
+ with pytest.raises((ValueError, SimilarityConfigError)):
+ registry.build_from_directory(
+ second, "skill", minimum_entries=3 if failure == "minimum" else 1, for_pairwise_scan=failure == "preflight"
+ )
+ assert registry.coverage is committed_coverage
+ assert registry.latest_attempt_coverage.skipped_count == (not initial_malformed)
+ assert registry._vector_dimension == 2
+ assert {key: entry.embedding for key, entry in registry._entries.items()} == original
+ # Query behavior must continue to describe the committed index.
+ registry._max_scalar_comparisons = 128000000
+ assert [match.entry_b for match in registry.query("target", 0.75)] == ["alpha"]
+ destination = tmp_path / "retained.json"
+ if initial_malformed:
+ with pytest.raises(ValueError, match="incomplete"):
+ registry.save_catalog(destination)
+ assert not destination.exists()
+ else:
+ registry.save_catalog(destination)
+ assert {entry["name"] for entry in json.loads(destination.read_text())["entries"]} == {"alpha", "beta"}
+
+
[email protected]("selection", ["strict_subset", "disjoint_explicit", "disjoint_directory", "clean_refresh"])
+def test_successful_build_replaces_partial_index_completely(tmp_path: Path, selection: str) -> None:
+ first = tmp_path / "first"
+ _collection(first)
+ client = _client()
+ client.embed_single.return_value = [1.0, 0.0]
+ registry = EmbeddingRegistry(client)
+ registry.build_from_directory(first, "skill")
+ expected = "alpha" if selection in {"strict_subset", "clean_refresh"} else "gamma"
+ if selection == "strict_subset":
+ count = registry.build_from_paths(first, [first / "alpha"])
+ elif selection == "clean_refresh":
+ (first / "beta" / "SKILL.md").unlink()
+ (first / "broken-000" / "SKILL.md").unlink()
+ count = registry.build_from_directory(first, "skill")
+ else:
+ second = tmp_path / "second"
+ path = _single_skill(second, "gamma")
+ count = (
+ registry.build_from_paths(second, [path])
+ if selection == "disjoint_explicit"
+ else registry.build_from_directory(second, "skill")
+ )
+ assert count == 1
+ assert registry.size == 1
+ client.embed_single.return_value = [1.0, 0.0] if expected == "alpha" else [0.0, 1.0]
+ assert [match.entry_b for match in registry.query("target", 0.75)] == [expected]
+ destination = tmp_path / "replacement.json"
+ registry.save_catalog(destination)
+ assert [entry["name"] for entry in json.loads(destination.read_text())["entries"]] == [expected]
+ if selection in {"strict_subset", "disjoint_explicit"}:
+ assert registry.coverage is None
+ else:
+ assert registry.coverage.selected_count == 1
+ assert registry.coverage.indexed_count == 1
+ assert registry.coverage.skipped_count == 0
+ assert registry.latest_attempt_coverage is registry.coverage
+
+
+def test_empty_directory_replacement_does_not_retain_previous_entries(tmp_path: Path) -> None:
+ first = tmp_path / "first"
+ _collection(first)
+ registry = EmbeddingRegistry(_client())
+ registry.build_from_directory(first, "skill")
+ empty = tmp_path / "empty"
+ empty.mkdir()
+ assert registry.build_from_directory(empty, "skill") == 0
+ assert registry.size == 0
+ assert registry._vector_dimension is None
+ with pytest.raises(ValueError, match="empty"):
+ registry.save_catalog(tmp_path / "empty.json")
+
+
+def test_complete_replacement_can_change_vector_width(tmp_path: Path) -> None:
+ first = tmp_path / "first"
+ _collection(first)
+ client = _client()
+ registry = EmbeddingRegistry(client)
+ registry.build_from_directory(first, "skill")
+ second = tmp_path / "second"
+ _single_skill(second, "gamma")
+ client.embed.side_effect = lambda texts: [[0.0, 0.0, 1.0] for _ in texts]
+ assert registry.build_from_directory(second, "skill") == 1
+ assert registry._vector_dimension == 3
+ destination = tmp_path / "three-dimensional.json"
+ registry.save_catalog(destination)
+ saved = json.loads(destination.read_text())
+ assert saved["vector_dimension"] == 3
+ assert [entry["name"] for entry in saved["entries"]] == ["gamma"]
diff --git a/tests/embedding/test_registry.py b/tests/embedding/test_registry.py
index 64d5cf3a..ec200f95 100644
--- a/tests/embedding/test_registry.py
+++ b/tests/embedding/test_registry.py
@@ -109,7 +109,6 @@ class TestBuildFromDirectory:
collection = tmp_path / "nested" / "external-skills"
collection.mkdir(parents=True)
debug = MagicMock()
- monkeypatch.setattr(registry_module, "discover_and_extract", lambda *_args, **_kwargs: [])
monkeypatch.setattr(registry_module.logger, "debug", debug)
count = EmbeddingRegistry(_make_mock_client([])).build_from_directory(collection, "skill")