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.
Python agent-evaluationagent-pluginsagent-securityagent-skillsagentic-aibenchmarkci-templatesclaude-codecodexevaluateevaluationharnesspluginplugin-evaluationsecurity-scannerskill-evalskill-evaluationskill-evaluatorskill-gap-analysisskills
feat(tier3): add reproducible local-catalog decoy selection (#263)
YMuskrat2eb12006fc81
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c4f8e874..3c8d6829 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -25,6 +25,16 @@ All notable changes to SkillEvaluator are documented in this file.template path. Keep GitHub and GitLab as the two repository-integration choices.- Allow CI release templates to pin the reviewed report publisher separatelyfrom the verified scanner workflow and image.+- `tier3 select-decoys` selects neighboring skills from a local description-+ embedding catalog and saves a reproducible JSON manifest with scores,+ catalog/model identity, and content hashes. Group evaluations can opt in+ with `skill_workspace.decoy_manifest` in `evals/config.yml`; selected content+ is verified and shared between paired arms without selecting again.+ Explicit helper skills and existing workspace defaults remain unchanged.+ Selections exclude skills bundled inside the target and use portable roots+ for the target's collection. Decoy hashes cover the staged runtime content,+ so evaluation configs and other decoy manifests do not invalidate them.+ Output guards protect evaluation inputs and existing non-manifest files.- In local mode (`--env-mode local`), a missing Claude Code, Codex, or OpenCodeCLI is offered as a pinned npm install into the SkillEvaluator runtime folder;diff --git a/docs/agents-and-sandboxes.mdx b/docs/agents-and-sandboxes.mdxindex 9c423799..d396a047 100644--- a/docs/agents-and-sandboxes.mdx+++ b/docs/agents-and-sandboxes.mdx@@ -632,6 +632,77 @@ Use group mode when the skill delegates to companion skills and evaluating italone would be unfair; keep the default otherwise — a smaller workspace is acleaner experiment.+### Select a reproducible decoy set++`tier3 select-decoys` ranks real skills from a local description-embedding+catalog and saves a selection manifest. Selection accepts skill-only catalogs+with at most 1,000 entries. Build the catalog without `--full-body` and use the+same embedding provider and model for selection:++```bash title="Select four neighboring skills"+skillevaluator similarity-check ./skills --save-catalog ./skill-catalog.json+skillevaluator tier3 select-decoys ./skills/my-skill \+ --catalog ./skill-catalog.json --catalog-root ./skills \+ --count 4 --exclude required-helper \+ --output ./skills/my-skill/evals/decoys.json+```++Opt in through the target skill's run policy. Manifest paths, like included+skill paths, are relative to the target skill's parent directory:++```yaml title="skills/my-skill/evals/config.yml"+schema_version: 1+skill_workspace:+ mode: group+ decoy_manifest: my-skill/evals/decoys.json+ include:+ - required-helper+```++Selection excludes the target, skills bundled inside it, and duplicate+candidates, orders equal scores by catalog-relative path, and fails if too few+eligible skills remain. Required+helpers stay explicit in `include`; the selector does not infer prerequisites.+A collision between a selected skill and an explicitly included skill is an+error.++The manifest records catalog and model identity, scores, the target manifest+hash, and selected skill runtime hashes. Evaluation verifies the hashes and+uses one snapshot of the selected skills in both arms; it makes no embedding+request and does not select again. The runtime hashes exclude evaluator-only+directories, including each nested skill's `evals/`, exactly as staging does.+Editing those configs, datasets, or selection manifests does not invalidate+other skills' selections. Agent-visible references still participate in the+hash, including an ordinary `references/evals/` folder.++For a collection that contains the target, or lies inside the target's parent+directory, `catalog_root` is stored relative to that parent (`.` in the example+above). Identical clones and relocated collections can reuse the same manifest;+evaluation checks the sources in the current checkout. An unrelated external+collection retains an absolute root and must be available at that location.+The runtime hashes cover everything staging copies from a selected skill,+including files that git ignores or does not track (such as `.DS_Store` or+`.pytest_cache/`) and empty folders, so generate a manifest you plan to commit+from a fresh clone. Of the permission bits, only whether a file is executable+by its owner counts, so clones made under different umasks agree. Windows+checkouts can differ: Git may convert line endings there, and Python reports+`.exe`, `.bat`, `.cmd` and `.com` files as executable and other files as not+executable. Generate a separate selection on Windows.+Regenerate after editing the target's `SKILL.md`, changing selected runtime+content, or moving an external collection. Manifests using an earlier digest+algorithm must also be regenerated. External workspace skills retain the+existing publication-evidence limitations.++Use a separate manifest filename such as `decoys.json`. Selection output cannot+replace an evaluation dataset, run policy, embedding catalog, or existing+non-manifest file.++Similarity is a heuristic for plausible alternatives, not evidence of actual+routing confusion. Skill Lift remains conditional on the chosen workspace;+a neighboring skill may legitimately substitute for the target. Review the+selection before running the evaluation, and keep the manifest with the run+policy when comparing results.+## Readiness checks`doctor` and `health-check` run the same readiness checks and exit nonzero whendiff --git a/docs/cli-reference.mdx b/docs/cli-reference.mdxindex bcb87c1f..4e87a393 100644--- a/docs/cli-reference.mdx+++ b/docs/cli-reference.mdx@@ -31,6 +31,7 @@ commands referenced below.| [dedup-scan](#dedup-scan) | Alias of `context-optimization-check` | Embeddings + LLM provider key || [similarity-check](#similarity-check) | Detect duplicate content across a collection | Embeddings provider key || [tier3 evaluate](#tier3-evaluate) | Run Tier 3 live agent evaluation | Provider key plus a credential the selected agents can use (one `NVIDIA_API_KEY` covers both on NVIDIA Build), backend (Docker by default) |+| [tier3 select-decoys](#tier3-select-decoys) | Save a reproducible set of neighboring skills for group evaluation | Local description-embedding catalog, skill collection, embeddings provider key || [create-eval-dataset](#create-eval-dataset) | Generate synthetic eval datasets | LLM provider key (none with `--no-llm`) || [init-custom-grader](#init-custom-grader) | Scaffold a bring-your-own-grader starter | Nothing || [init-harbor-task](#init-harbor-task) | Scaffold a bring-your-own-task Harbor starter | Nothing |@@ -160,9 +161,11 @@ pipeline.| --- | --- || `tier1` | `validate`, `quality-check`, `rubric-eval`, `security-scan`, `pii-scan`, `lint-scripts` || `tier2` | `context-optimization-check`, `dedup-scan`, `similarity-check` |-| `tier3` | `evaluate`, `create-eval-dataset`, `init-custom-grader`, `init-harbor-task`, `doctor`, `view`, `compare`, `validate`, `harbor-view` |+| `tier3` | `evaluate`, `select-decoys`, `create-eval-dataset`, `init-custom-grader`, `init-harbor-task`, `doctor`, `view`, `compare`, `validate`, `harbor-view` |-`health-check` and [models](#models) are top-level only. Two expert commands are advertised **only** inside the `tier3` group: [tier3 evaluate](#tier3-evaluate), documented with its full flag set below, and `tier3 validate`:+`health-check` and [models](#models) are top-level only. The expert commands+[tier3 evaluate](#tier3-evaluate), [tier3 select-decoys](#tier3-select-decoys),+and `tier3 validate` are advertised **only** inside the `tier3` group:### tier3 validate@@ -415,6 +418,44 @@ spellings for new commands. A catalog query and a catalog build cannot becombined in one invocation, and each alias cannot be supplied alongside itsreplacement.+## tier3 select-decoys++Choose neighboring skills from a local description-embedding catalog and save+a frozen JSON manifest for group evaluation. This command makes an embedding+request for the target; it does not launch an agent or modify the run policy.++```bash title="Save a group-workspace selection"+skillevaluator tier3 select-decoys ./skills/my-skill \+ --catalog ./skill-catalog.json --catalog-root ./skills \+ --count 4 --output ./skills/my-skill/evals/decoys.json+```++| Flag | Default | Effect |+| --- | --- | --- |+| `--catalog FILE` | required | Skill-only catalog with at most 1,000 entries, saved by `similarity-check --save-catalog` without `--full-body`. |+| `--catalog-root DIRECTORY` | required | Local collection root corresponding to catalog-relative skill paths. |+| `--count INTEGER` | `4` | Number of eligible skills to select, from `1` to `1000`; fails if fewer are available. |+| `--exclude PATH` | none | Exclude a catalog-relative skill path; repeatable. |+| `--model TEXT` | configured embedding model | Embedding model override; must match the catalog. |+| `-o, --output FILE` | required | Selection manifest to write, outside the collection or inside the target's `evals/` directory. |++The manifest records the catalog hash and embedding identity, selected paths+and scores, target manifest hash, and selected runtime-content hashes. The+target's own collection uses a root relative to its parent directory, so an+identical checkout can reuse the manifest. The hashes cover everything staging+copies from a selected skill, including ignored or untracked files and empty+folders, so generate a manifest you plan to commit from a fresh clone.+Unrelated external collections+retain an absolute root. Evaluator-only files are excluded from decoy hashes;+changing a decoy's evaluation config does not require a new selection. Output+cannot overwrite evaluation inputs or an existing non-manifest file. Set+`skill_workspace.mode: group` and `skill_workspace.decoy_manifest` in+`evals/config.yml` to consume it. The manifest path is relative to the target+skill's parent directory. Evaluation validates and reuses the selection+without contacting the embedding provider. See+[Select a reproducible decoy set](agents-and-sandboxes.mdx#select-a-reproducible-decoy-set)+for a complete example and the limits of similarity-based selection.+## tier3 evaluateRun Tier 3 live agent evaluation: real agents attempt your eval cases with and without the skill, and the difference becomes Skill Lift. Requires the `tier3` extra, a provider key for grading, a credential the selected agents can use — with NVIDIA Build in `--env-mode docker`, `kata`, or `local`, the one `NVIDIA_API_KEY` covers both roles — and a running backend (Docker by default). The full walkthrough is [Tier 3: Live Evaluation](tier3-live-evaluation.mdx).diff --git a/docs/eval-datasets.mdx b/docs/eval-datasets.mdxindex 12000b0c..415f58bc 100644--- a/docs/eval-datasets.mdx+++ b/docs/eval-datasets.mdx@@ -263,6 +263,7 @@ grading:| `harbor.agents.<name>.model` | string | Per-agent model override; whitespace is trimmed. `claude` is accepted as an alias of `claude-code`, but configuring both spellings in one config is an error. || `skill_workspace.mode` | `isolated`, `group` | Whether sibling skills are visible — see [Agents & Sandboxes](agents-and-sandboxes.mdx). || `skill_workspace.include` | list of paths | Extra skills staged into a `group` workspace. |+| `skill_workspace.decoy_manifest` | path | Optional frozen selection from `tier3 select-decoys`; requires `group` mode. Relative paths resolve against the target skill's parent directory, as with `include`. Selected runtime-content hashes are checked before evaluation; evaluator-only files do not affect them. See [Workspace modes](agents-and-sandboxes.mdx#select-a-reproducible-decoy-set). || `grading.mode` | `default`, `default_plus_custom`, `custom_only` | Grading pipeline — see [Custom Graders & Tasks](custom-graders.mdx). Legacy spellings `aces_default` and `aces_plus_custom` are accepted and normalized to `default` and `default_plus_custom`. |Environment constructor kwargs are deliberately not accepted in thisdiff --git a/src/skillevaluator/cli.py b/src/skillevaluator/cli.pyindex 4c605164..e51255c9 100644--- a/src/skillevaluator/cli.py+++ b/src/skillevaluator/cli.py@@ -3625,6 +3625,10 @@ tier3.add_command(compare, "compare")tier3.add_command(view, "view")tier3.add_command(tier3_doctor_command, "doctor")+from skillevaluator.tier3.decoy_commands import select_decoys_command++tier3.add_command(select_decoys_command, "select-decoys")+from skillevaluator.tier3.workflow import build_tier3_workflowtier3.workflow = build_tier3_workflow(evaluate)diff --git a/src/skillevaluator/tier3/decoy_commands.py b/src/skillevaluator/tier3/decoy_commands.pynew file mode 100644index 00000000..ee1961ab--- /dev/null+++ b/src/skillevaluator/tier3/decoy_commands.py@@ -0,0 +1,150 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++"""Explicit authoring command for frozen group-workspace selections."""++from __future__ import annotations++import json+from pathlib import Path++import click++from skillevaluator.cli_help import RichCommand++[email protected]("select-decoys", cls=RichCommand, context_settings={"help_option_names": ["-h", "--help"]})[email protected]("skill_path", type=click.Path(exists=True, file_okay=False, path_type=Path))+ "--catalog",+ "catalog_path",+ required=True,+ type=click.Path(exists=True, dir_okay=False, path_type=Path),+ help="Description-mode embedding catalog created with similarity-check --save-catalog.",+)+ "--catalog-root",+ required=True,+ type=click.Path(exists=True, file_okay=False, path_type=Path),+ help="Local collection whose relative skill paths the catalog describes.",+)[email protected]("--count", type=click.IntRange(min=1, max=1000), default=4, show_default=True)[email protected]("--exclude", multiple=True, help="Catalog-relative skill path to exclude (repeatable).")[email protected]("--model", help="Embedding model; must match the catalog. Defaults to the configured provider's model.")+ "-o",+ "--output",+ "output_path",+ required=True,+ type=click.Path(dir_okay=False, path_type=Path),+ help="Write the frozen selection manifest here, for use with skill_workspace.decoy_manifest.",+)+def select_decoys_command(+ skill_path: Path,+ catalog_path: Path,+ catalog_root: Path,+ count: int,+ exclude: tuple[str, ...],+ model: str | None,+ output_path: Path,+) -> None:+ """Select neighboring skills for a paired group evaluation.++ Rank a local catalog by description similarity and save a reviewable+ manifest. This authoring step may call the configured embedding provider;+ evaluation reuses the manifest without querying that provider again.+ """+ from skillevaluator.embedding.client import EmbeddingClient, SimilarityConfigError+ from skillevaluator.tier3.decoys import select_decoys, write_decoy_manifest++ try:+ _validate_output_path(output_path, skill_path, catalog_path, catalog_root)+ manifest = select_decoys(+ skill_path,+ catalog_path=catalog_path,+ catalog_root=catalog_root,+ count=count,+ exclude=exclude,+ client=EmbeddingClient(model=model),+ )+ write_decoy_manifest(manifest, output_path)+ except (OSError, ValueError, SimilarityConfigError) as exc:+ raise click.ClickException(str(exc)) from exc+ click.echo(f"Saved {len(manifest['selected'])} decoys to {output_path}")+ click.echo("Review the selection, then set skill_workspace.mode: group and skill_workspace.decoy_manifest.")+++def _validate_output_path(output: Path, target: Path, catalog: Path, catalog_root: Path) -> None:+ """Keep manifest output from replacing inputs or changing selected sources."""+ destination = output.resolve()+ target_root = target.resolve()+ if destination == catalog.resolve() or _same_existing_path(destination, catalog):+ raise ValueError("Decoy manifest output must not replace the embedding catalog")+ # The target's evaluator-only directory is a natural place to version this+ # file. Other skill contents and catalog members are author-owned inputs.+ relative = _relative_to_directory(destination, target_root)+ in_target_evals = relative is not None and len(relative.parts) > 1 and relative.parts[0].casefold() == "evals"+ if in_target_evals:+ reserved = {"config.yml", "config.yaml"} | {+ f"{stem}.{extension}" for stem in ("evals", "dataset") for extension in ("json", "jsonl", "yaml", "yml")+ }+ if destination.name.casefold() in reserved:+ raise ValueError("Decoy manifest output must not replace an evaluation dataset or run policy")+ elif relative is not None or _relative_to_directory(destination, catalog_root.resolve()) is not None:+ raise ValueError("Save the decoy manifest outside the skill collection or inside the target's evals directory")+ _validate_existing_output(output)+++def _same_existing_path(first: Path, second: Path) -> bool:+ """Recognize filesystem aliases without equating distinct case-sensitive names."""+ try:+ return first.samefile(second)+ except FileNotFoundError:+ return False+++def _relative_to_directory(path: Path, directory: Path) -> Path | None:+ """Find containment through existing ancestors, including case aliases on macOS."""+ for ancestor in (path, *path.parents):+ if ancestor == directory or _same_existing_path(ancestor, directory):+ return path.relative_to(ancestor)+ return None+++def _validate_existing_output(output: Path) -> None:+ """Allow regenerating saved manifests, including ones with stale source hashes."""+ from skillevaluator.embedding.registry import _catalog_object, _read_catalog_text, _reject_json_constant+ from skillevaluator.tier3.decoys import (+ _CATALOG_FIELDS,+ _MANIFEST_FIELDS,+ _SELECTED_FIELDS,+ _TARGET_FIELDS,+ DECOY_MANIFEST_VERSION,+ DECOY_SELECTION_STRATEGY,+ _count,+ _hash,+ _object,+ )++ if not output.exists() and not output.is_symlink():+ return+ try:+ data = _object(+ json.loads(_read_catalog_text(output), object_pairs_hook=_catalog_object, parse_constant=_reject_json_constant),+ _MANIFEST_FIELDS,+ "root",+ )+ if type(data["schema_version"]) is not int or data["schema_version"] != DECOY_MANIFEST_VERSION:+ raise ValueError("Unsupported decoy manifest schema version")+ if data["strategy"] != DECOY_SELECTION_STRATEGY:+ raise ValueError("Unsupported decoy selection strategy")+ catalog = _object(data["catalog"], _CATALOG_FIELDS, "catalog")+ target = _object(data["target"], _TARGET_FIELDS, "target")+ _hash(catalog["sha256"], "catalog")+ _hash(target["manifest_sha256"], "target")+ if not isinstance(data["selected"], list) or len(data["selected"]) != _count(data["count"]):+ raise ValueError("Invalid decoy manifest selected count")+ for item in data["selected"]:+ _hash(_object(item, _SELECTED_FIELDS, "selected skill")["source_digest"], "source")+ except (OSError, ValueError) as exc:+ raise ValueError(f"Refusing to replace an existing file that is not a decoy manifest: {output}") from excdiff --git a/src/skillevaluator/tier3/decoy_identity.py b/src/skillevaluator/tier3/decoy_identity.pynew file mode 100644index 00000000..8a525e39--- /dev/null+++ b/src/skillevaluator/tier3/decoy_identity.py@@ -0,0 +1,67 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++"""Versioned identities for the runtime content of selected decoy skills.++Decoy identity follows the same projection as staging. Evaluator-only inputs+do not affect that identity; the full publication source identity retains its+separate contract, which deliberately includes authored evaluation inputs.+"""++from __future__ import annotations++import dataclasses+import hashlib+from collections.abc import Callable, Iterable+from pathlib import Path+from typing import Any++# Bump this recipe if the runtime projection or reused canonical encoding changes.+DECOY_SOURCE_DIGEST_ALGORITHM = "skill-evaluator-decoy-runtime/2"+++def _portable_mode(entry: Any) -> Any:+ """Keep only the execute state that a git checkout reproduces.++ Git records whether a file is executable and nothing for directories; the+ group and other bits of a clone follow the cloning user's umask. Encoding+ the owner execute bit of regular files keeps identical clones identical.+ """+ executable = entry.kind == "file" and bool(entry.mode & 0o100)+ return dataclasses.replace(entry, mode=0o755 if executable else 0o644)+++def decoy_source_copy_ignore(source: Path) -> Callable[[str, list[str]], Iterable[str]]:+ """Use the agent-visible skill projection for both identity and snapshots."""+ from skillevaluator.tier3.harbor.adapter import _runtime_skill_copy_ignore++ return _runtime_skill_copy_ignore(source)+++def decoy_source_digest(source: Path) -> str | None:+ """Hash one stable runtime projection, rejecting unsafe or unstable trees.++ Secure staging traversal rejects links, hard-linked files, special nodes+ and mount crossings. Three captures detect incidental changes between+ scans. As with staging, this does not promise a coherent snapshot against+ another process concurrently mutating the tree with the same OS identity.+ Paths are NFC-normalized, and the owner execute bit of each file+ participates in the digest.+ """+ from skillevaluator.publication_identity import _manifest_digest+ from skillevaluator.tier3.harbor.secure_copy import _build_tree_manifest++ try:+ ignore = decoy_source_copy_ignore(source)+ captured = _build_tree_manifest(source, allowed_root=source, ignore=ignore)+ for _ in range(2):+ if _build_tree_manifest(source, allowed_root=source, ignore=ignore) != captured:+ return None+ # Reuse the publication recipe's canonical paths, node kinds, content+ # hashes and executable-bit encoding, under a distinct runtime label.+ encoded = _manifest_digest(_portable_mode(entry) for entry in (captured.root, *captured.entries))+ return hashlib.sha256(+ DECOY_SOURCE_DIGEST_ALGORITHM.encode("ascii") + b"\0" + bytes.fromhex(encoded)+ ).hexdigest()+ except (OSError, OverflowError, RuntimeError, UnicodeError, ValueError):+ return Nonediff --git a/src/skillevaluator/tier3/decoys.py b/src/skillevaluator/tier3/decoys.pynew file mode 100644index 00000000..44dc1c2b--- /dev/null+++ b/src/skillevaluator/tier3/decoys.py@@ -0,0 +1,371 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++"""Select local workspace decoys once, then verify their frozen identities.++Description similarity is a selection policy, not evidence that a skill is a+prerequisite or that two skills are confusing to an agent. The manifest records+the policy and source identities so evaluation never repeats retrieval.+"""++from __future__ import annotations++import hashlib+import json+import math+import os+import re+import unicodedata+from pathlib import Path, PurePosixPath+from typing import Any++from skillevaluator.constants import CONTENT_TYPE_SKILL+from skillevaluator.embedding.client import EmbeddingClient+from skillevaluator.embedding.extractor import ContentEntry, _ensure_safe_content_path, extract_from_skill+from skillevaluator.embedding.registry import (+ MAX_SIMILARITY_MATCHES,+ EmbeddingRegistry,+ _catalog_object,+ _read_catalog_text,+ _reject_json_constant,+ _validate_catalog_identity,+ _validate_catalog_string,+ _write_catalog_atomically,+)+from skillevaluator.tier3.decoy_identity import DECOY_SOURCE_DIGEST_ALGORITHM, decoy_source_digest+from skillevaluator.utils.path_security import canonicalize_trusted_root_alias+from skillevaluator.validators.frontmatter_parser import FRONTMATTER_PATTERN++DECOY_MANIFEST_VERSION = 1+DECOY_SELECTION_STRATEGY = "description-similarity"+MAX_DECOYS = MAX_SIMILARITY_MATCHES+_HASH = re.compile(r"^[0-9a-f]{64}$")+_MANIFEST_FIELDS = {+ "schema_version",+ "strategy",+ "catalog_root",+ "catalog",+ "target",+ "count",+ "exclude",+ "selected",+ "source_digest_algorithm",+}+_CATALOG_FIELDS = {"sha256", "provider", "model", "mode", "endpoint_fingerprint"}+_TARGET_FIELDS = {"name", "skill_name", "manifest_sha256"}+_SELECTED_FIELDS = {"path", "name", "skill_name", "score", "source_digest"}+++def _sha256(text: str) -> str:+ return hashlib.sha256(text.encode("utf-8")).hexdigest()+++def _identity(text: str) -> str:+ return unicodedata.normalize("NFC", text).casefold()+++def _absolute_root(path: Path) -> Path:+ # Check lexical components before collapsing ``..`` so a link cannot be+ # hidden by a later parent segment in a portable catalog-root path.+ root = canonicalize_trusted_root_alias(path.expanduser().absolute())+ _ensure_safe_content_path(Path(root.anchor), root)+ root = Path(os.path.abspath(root)) # noqa: PTH100 - normalize only after no-follow checks+ if not root.is_dir():+ raise ValueError(f"Decoy skill root must be a directory: {root}")+ return root+++def _ancestor_depth(path: Path, ancestor: Path) -> int | None:+ """Count the levels from *path* up to *ancestor*, matching by file identity.++ A lexical comparison misses a case-variant spelling of the same directory+ on a case-insensitive filesystem.+ """+ for depth, candidate in enumerate((path, *path.parents)):+ try:+ if candidate.samefile(ancestor):+ return depth+ except OSError:+ continue+ return None+++def _catalog_root_record(root: Path, target: Path) -> str:+ """Keep a target's own collection relocatable; retain explicit external roots."""+ base = target.parent+ if (depth := _ancestor_depth(root, base)) is not None:+ return PurePosixPath(*root.parts[len(root.parts) - depth :]).as_posix()+ if (depth := _ancestor_depth(base, root)) is not None:+ return PurePosixPath(*[".."] * depth).as_posix()+ return str(root)+++def _is_target_path(path: Path, target: Path) -> bool:+ # Match the baseline staging policy across case-insensitive filesystems.+ from skillevaluator.tier3.harbor.adapter import _casefold_contained++ return _casefold_contained(path, target)+++def _skill(path: Path) -> ContentEntry:+ entry = extract_from_skill(path)+ if entry is None or not (path / "SKILL.md").is_file():+ raise ValueError(f"Decoy selection requires a skill with SKILL.md and name/description: {path}")+ _validate_catalog_string(entry.name, "Skill name")+ return entry+++def _relative_path(value: object) -> str:+ _validate_catalog_identity(f"skill:{value}", value, CONTENT_TYPE_SKILL)+ return str(value)+++def _selected_path(root: Path, relative: object) -> Path:+ relative = _relative_path(relative)+ candidate = root.joinpath(*PurePosixPath(relative).parts)+ _ensure_safe_content_path(root, candidate)+ if not candidate.is_dir():+ raise ValueError(f"Selected decoy is not a skill directory: {relative}")+ return candidate+++def _instructions(entry: ContentEntry) -> str:+ match = FRONTMATTER_PATTERN.match(entry.full_text)+ return match.group(2).strip() if match else entry.full_text.strip()+++def _aliases_target(entry: ContentEntry, target: ContentEntry) -> bool:+ return target.full_text in entry.full_text or bool(+ _instructions(target) and _instructions(entry) == _instructions(target)+ )+++def _source_digest(path: Path) -> str:+ digest = decoy_source_digest(path)+ if digest is None:+ raise ValueError(f"Selected decoy has an unsafe or unstable source tree: {path}")+ return digest+++def _contains_target_payload(path: Path, target: Path) -> bool:+ # Match the baseline adapter's policy, including renamed files and nested+ # packages, while ignoring files that never enter the runtime projection.+ # The caller validates the source tree before this bounded-memory scan.+ from skillevaluator.tier3.harbor.adapter import _find_target_manifest_payload++ return _find_target_manifest_payload(path, target, runtime_projection=True) is not None+++def _count(value: object) -> int:+ if type(value) is not int or not 1 <= value <= MAX_DECOYS:+ raise ValueError(f"Decoy count must be an integer from 1 to {MAX_DECOYS}")+ return value+++def select_decoys(+ target: Path,+ *,+ catalog_path: Path,+ catalog_root: Path,+ count: int,+ exclude: tuple[str, ...] = (),+ client: EmbeddingClient | None = None,+) -> dict[str, Any]:+ """Rank local skills from a description-mode Tier 2 catalog.++ Exact target copies, duplicate identities, and negative-similarity matches+ are ineligible. Ties use catalog-relative path order. No evaluation outcome+ is consulted. Invalid/stale candidate sources fail instead of being silently+ replaced with a lower-ranked candidate.+ """+ count = _count(count)+ root = _absolute_root(catalog_root)+ target = _absolute_root(target)+ target_entry = _skill(target)+ exclusions = sorted({_relative_path(path) for path in exclude})+ registry = EmbeddingRegistry(client or EmbeddingClient())+ before = _read_catalog_text(catalog_path)+ registry.load_catalog(catalog_path)+ if _read_catalog_text(catalog_path) != before:+ raise ValueError("Decoy catalog changed while being loaded")+ catalog = json.loads(before)+ if registry.size > MAX_SIMILARITY_MATCHES:+ raise ValueError(f"Decoy selection supports at most {MAX_SIMILARITY_MATCHES} catalog entries")+ if any(entry.content_type != CONTENT_TYPE_SKILL for entry in registry._entries.values()):+ raise ValueError("Decoy selection requires a skill-only catalog")+ catalog_entries = {entry.path: entry for entry in registry._entries.values()}+ unknown_exclusions = set(exclusions) - catalog_entries.keys()+ if unknown_exclusions:+ raise ValueError("Excluded decoy path is absent from catalog: " + ", ".join(sorted(unknown_exclusions)))+ matches = registry.query_entry(target_entry, threshold=0.0)+ matches.sort(key=lambda match: (-match.score, match.path_b))++ names = {_identity(target.name)}+ skill_names = {_identity(target_entry.name)}+ digests: set[str] = set()+ selected: list[dict[str, Any]] = []+ for match in matches:+ stored = catalog_entries[match.path_b]+ if stored.content_type != CONTENT_TYPE_SKILL or stored.path in exclusions:+ continue+ candidate = _selected_path(root, stored.path)+ if _is_target_path(candidate, target) or _identity(candidate.name) in names or _identity(stored.name) in skill_names:+ continue+ entry = _skill(candidate)+ if _sha256(entry.embedding_text) != stored.content_fingerprint:+ raise ValueError(f"Decoy catalog entry is stale; rebuild the catalog: {stored.path}")+ if _aliases_target(entry, target_entry):+ continue+ digest = _source_digest(candidate)+ if digest in digests or _contains_target_payload(candidate, target):+ continue+ selected.append(+ {+ "path": stored.path,+ "name": candidate.name,+ "skill_name": entry.name,+ "score": match.score,+ "source_digest": digest,+ }+ )+ names.add(_identity(candidate.name))+ skill_names.add(_identity(entry.name))+ digests.add(digest)+ if len(selected) == count:+ break+ if len(selected) != count:+ raise ValueError(f"Requested {count} decoys but only {len(selected)} eligible skills were found")+ if _skill(target).full_text != target_entry.full_text:+ raise ValueError("Target skill changed during decoy selection")+ return {+ "schema_version": DECOY_MANIFEST_VERSION,+ "strategy": DECOY_SELECTION_STRATEGY,+ "catalog_root": _catalog_root_record(root, target),+ "catalog": {+ "sha256": _sha256(before),+ **{key: catalog[key] for key in _CATALOG_FIELDS - {"sha256"}},+ },+ "target": {+ "name": target.name,+ "skill_name": target_entry.name,+ "manifest_sha256": _sha256(target_entry.full_text),+ },+ "count": count,+ "exclude": exclusions,+ "selected": selected,+ "source_digest_algorithm": DECOY_SOURCE_DIGEST_ALGORITHM,+ }+++def _object(value: object, keys: set[str], label: str) -> dict[str, Any]:+ if not isinstance(value, dict) or value.keys() != keys:+ raise ValueError(f"Invalid decoy manifest {label} fields")+ return value+++def _hash(value: object, label: str) -> str:+ if not isinstance(value, str) or not _HASH.fullmatch(value):+ raise ValueError(f"Invalid decoy manifest {label} hash")+ return value+++def _validate_manifest(manifest: object, target: Path) -> tuple[list[Path], dict[str, Any]]:+ data = _object(manifest, _MANIFEST_FIELDS, "root")+ if type(data["schema_version"]) is not int or data["schema_version"] != DECOY_MANIFEST_VERSION:+ raise ValueError("Unsupported decoy manifest schema version")+ if data["strategy"] != DECOY_SELECTION_STRATEGY:+ raise ValueError("Unsupported decoy selection strategy")+ if data["source_digest_algorithm"] != DECOY_SOURCE_DIGEST_ALGORITHM:+ raise ValueError("Unsupported decoy source digest algorithm; regenerate the selection")+ count = _count(data["count"])+ catalog = _object(data["catalog"], _CATALOG_FIELDS, "catalog")+ _hash(catalog["sha256"], "catalog")+ for key in ("provider", "model", "mode", "endpoint_fingerprint"):+ _validate_catalog_string(catalog[key], f"Decoy catalog {key}")+ if catalog["mode"] != "description" or not re.fullmatch(r"sha256:[0-9a-f]{64}", catalog["endpoint_fingerprint"]):+ raise ValueError("Invalid decoy catalog mode or endpoint fingerprint")+ root_value = _validate_catalog_string(data["catalog_root"], "Decoy catalog root")+ target = _absolute_root(target)+ root_path = Path(root_value)+ if not root_path.is_absolute():+ root_path = target.parent / root_path+ root = _absolute_root(root_path)+ entry = _skill(target)+ target_data = _object(data["target"], _TARGET_FIELDS, "target")+ _hash(target_data["manifest_sha256"], "target")+ if target_data != {+ "name": target.name,+ "skill_name": entry.name,+ "manifest_sha256": _sha256(entry.full_text),+ }:+ raise ValueError("Decoy manifest target changed; regenerate the selection")+ exclusions = data["exclude"]+ if not isinstance(exclusions, list) or len(exclusions) > MAX_SIMILARITY_MATCHES:+ raise ValueError("Invalid decoy manifest exclusions")+ exclusions = [_relative_path(value) for value in exclusions]+ if len(exclusions) != len(set(exclusions)):+ raise ValueError("Duplicate decoy manifest exclusions")+ selected = data["selected"]+ if not isinstance(selected, list) or len(selected) != count:+ raise ValueError("Decoy manifest selected count does not match count")+ paths: list[Path] = []+ names = {_identity(target.name)}+ skill_names = {_identity(entry.name)}+ digests: set[str] = set()+ for item in selected:+ item = _object(item, _SELECTED_FIELDS, "selected skill")+ path = _selected_path(root, item["path"])+ if _is_target_path(path, target):+ raise ValueError("Decoy manifest contains the target or a skill nested inside the target")+ current = _skill(path)+ score = item["score"]+ if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score):+ raise ValueError("Invalid decoy manifest similarity score")+ digest = _hash(item["source_digest"], "source")+ if (+ item["path"] in exclusions+ or _identity(path.name) in names+ or _identity(current.name) in skill_names+ or digest in digests+ or _aliases_target(current, entry)+ ):+ raise ValueError("Decoy manifest contains a target alias or duplicate skill identity")+ if item["name"] != path.name or item["skill_name"] != current.name:+ raise ValueError(f"Selected decoy identity changed: {item['path']}")+ if _source_digest(path) != digest:+ raise ValueError(f"Selected decoy source changed; regenerate the selection: {item['path']}")+ if _contains_target_payload(path, target):+ raise ValueError(f"Selected decoy contains target instructions: {item['path']}")+ names.add(_identity(path.name))+ skill_names.add(_identity(current.name))+ digests.add(digest)+ paths.append(path)+ return paths, data+++def write_decoy_manifest(manifest: dict[str, Any], output_path: Path) -> None:+ """Atomically save a bounded JSON selection without following output links."""+ payload = (json.dumps(manifest, indent=2, sort_keys=True, allow_nan=False) + "\n").encode("utf-8")+ from skillevaluator.embedding.registry import MAX_CATALOG_BYTES++ if len(payload) > MAX_CATALOG_BYTES:+ raise ValueError("Decoy manifest exceeds its byte limit")+ _write_catalog_atomically(output_path, payload)+++def load_decoy_manifest(target: Path, manifest_path: Path) -> tuple[list[Path], dict[str, Any]]:+ """Verify a saved selection against local sources, without model access.++ Paths and content hashes are checked, not silently refreshed. Callers that+ stage multiple paired environments should snapshot these verified sources+ once and verify their hashes again before running either arm.+ """+ try:+ raw = json.loads(+ _read_catalog_text(manifest_path),+ object_pairs_hook=_catalog_object,+ parse_constant=_reject_json_constant,+ )+ except (UnicodeError, json.JSONDecodeError) as exc:+ raise ValueError(f"Invalid decoy manifest JSON: {exc}") from exc+ return _validate_manifest(raw, target)diff --git a/src/skillevaluator/tier3/evals_config.py b/src/skillevaluator/tier3/evals_config.pyindex 00cfb019..29771a75 100644--- a/src/skillevaluator/tier3/evals_config.py+++ b/src/skillevaluator/tier3/evals_config.py@@ -61,7 +61,7 @@ HARBOR_TASK_SOURCES = {"auto", "evals_json", "native_harbor"}MAX_HARBOR_TIMEOUT_MULTIPLIER = sys.float_info.max / 600.0_AGENT_KEYS = {"model"}_RESOURCE_KEYS = {"cpus", "memory_mb", "storage_mb"}-_SKILL_WORKSPACE_KEYS = {"mode", "include"}+_SKILL_WORKSPACE_KEYS = {"mode", "include", "decoy_manifest"}_GRADING_KEYS = {"mode"}_ENV_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")_GKE_INFRASTRUCTURE_KWARGS: frozenset[str] = frozenset(@@ -745,6 +745,10 @@ def _skill_workspace(value: Any, config_path: Path) -> dict[str, Any]:out["mode"] = _enum(value["mode"], SKILL_WORKSPACE_MODES, config_path, "skill_workspace.mode")if "include" in value:out["include"] = _string_list(value["include"], config_path, "skill_workspace.include")+ if "decoy_manifest" in value:+ out["decoy_manifest"] = _non_empty_string(+ value["decoy_manifest"], config_path, "skill_workspace.decoy_manifest"+ )return out@@ -773,4 +777,3 @@ def load_allowed_runtime_env(skill_path: Path) -> dict[str, str]:except Exception:passreturn {}-diff --git a/src/skillevaluator/tier3/harbor/runner.py b/src/skillevaluator/tier3/harbor/runner.pyindex 1acf8952..cf4b3a64 100644--- a/src/skillevaluator/tier3/harbor/runner.py+++ b/src/skillevaluator/tier3/harbor/runner.py@@ -24,6 +24,7 @@ import tempfileimport threadingimport timeimport tomllib+import unicodedatafrom collections.abc import Iterable, Iterator, Mapping, Sequencefrom concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, as_completed, waitfrom contextlib import ExitStack, contextmanager, suppress@@ -3245,6 +3246,91 @@ def _workspace_skills(skill_path: Path, values: list[str | Path]) -> list[Path]:return resolved+def _workspace_skill_name(path: Path) -> str:+ """Reserve the effective skill name without requiring an embedding description."""+ import yaml++ from skillevaluator.constants import CONTENT_DEDUP_MAX_FILE_BYTES+ from skillevaluator.validators.frontmatter_parser import FRONTMATTER_PATTERN++ content = _read_regular_evals_file(+ path / "SKILL.md",+ label="Workspace skill manifest",+ max_bytes=CONTENT_DEDUP_MAX_FILE_BYTES,+ allowed_root=path,+ ).decode("utf-8-sig")+ match = FRONTMATTER_PATTERN.match(content)+ if match is not None:+ try:+ metadata = yaml.safe_load(match.group(1))+ except yaml.YAMLError:+ metadata = None+ name = metadata.get("name") if isinstance(metadata, dict) else None+ if isinstance(name, str) and name.strip():+ return name.strip()+ return path.name+++def _decoy_workspace_skills(+ skill_path: Path,+ workspace_config: Mapping[str, Any],+ workspace_mode: str,+ include_skills: list[str | Path] | None = None,+ reference_skills_dir: Path | None = None,+) -> tuple[list[Path], list[Path], dict[str, Any] | None]:+ """Resolve one frozen selection without changing manual workspace policy."""+ from skillevaluator.tier3.decoys import load_decoy_manifest++ raw_manifest = workspace_config.get("decoy_manifest")+ include_values = [*workspace_config.get("include", []), *(include_skills or [])]+ if (include_values or raw_manifest is not None) and workspace_mode != "group":+ field = "skill_workspace.decoy_manifest" if raw_manifest is not None else "include_skills"+ raise ValueError(f"{field} requires skill_workspace.mode=group")+ manual_skills = _workspace_skills(skill_path.resolve(), include_values)+ if raw_manifest is None:+ return manual_skills, [], None+ manifest_path = Path(raw_manifest).expanduser()+ if not manifest_path.is_absolute():+ manifest_path = skill_path.parent / manifest_path+ selected, manifest = load_decoy_manifest(skill_path, manifest_path)++ def name_key(value: str) -> str:+ return unicodedata.normalize("NFC", value).casefold()++ reserved = [skill_path, *manual_skills]+ if reference_skills_dir is not None and reference_skills_dir.is_dir():+ reserved.extend(path for path in reference_skills_dir.iterdir() if _is_skill_dir(path))+ directory_names = {name_key(path.name) for path in reserved}+ skill_names = {name_key(_workspace_skill_name(path)) for path in reserved}+ for path, record in zip(selected, manifest["selected"], strict=True):+ if name_key(path.name) in directory_names or name_key(record["skill_name"]) in skill_names:+ raise ValueError(f"Selected decoy '{path.name}' collides with another workspace skill name")+ directory_names.add(name_key(path.name))+ skill_names.add(name_key(record["skill_name"]))+ return manual_skills, selected, manifest+++@contextmanager+def _private_decoy_workspace_snapshot(selected: list[Path], manifest: Mapping[str, Any]) -> Iterator[list[Path]]:+ """Keep the same verified source bytes available to every paired task."""+ from skillevaluator.tier3.decoy_identity import decoy_source_copy_ignore, decoy_source_digest++ with tempfile.TemporaryDirectory(prefix="skillevaluator-decoys-snapshot-") as root_text:+ root = Path(root_text)+ snapshots: list[Path] = []+ for source, record in zip(selected, manifest["selected"], strict=True):+ expected = record["source_digest"]+ if decoy_source_digest(source) != expected:+ raise ValueError(f"Selected decoy '{source.name}' changed before snapshot creation")++ snapshot = root / source.name+ copytree_secure(source, snapshot, allowed_root=source, ignore=decoy_source_copy_ignore(source))+ if decoy_source_digest(snapshot) != expected or decoy_source_digest(source) != expected:+ raise ValueError(f"Selected decoy '{source.name}' changed while its snapshot was created")+ snapshots.append(snapshot)+ yield snapshots++def _limit_staged_cases(task_selectors: list[str],case_id_by_task_selector: Mapping[str, str],@@ -4797,6 +4883,9 @@ def _run_harbor_eval_impl(repo_context_exclude_paths: Sequence[Path] = (),_evaluator_skill_path: Path | None = None,_snapshot_publication_target: dict[str, str] | None = None,+ _decoy_workspace_paths: list[Path] | None = None,+ _decoy_workspace_source_paths: list[Path] | None = None,+ _decoy_manifest: dict[str, Any] | None = None,_monotonic_start: float | None = None,) -> dict[str, Any]:"""Run a public Harbor evaluation with and without the target skill."""@@ -4830,6 +4919,35 @@ def _run_harbor_eval_impl(try:snapshot_publication_target = publication_target_from_path(skill_path)evaluator_skill_path = snapshot_stack.enter_context(private_evaluator_skill_snapshot(skill_path))+ snapshot_config, _ = load_evals_config(evaluator_skill_path)+ snapshot_workspace = snapshot_config.get("skill_workspace", {})+ if "decoy_manifest" in snapshot_workspace:+ manual, selected, manifest = _decoy_workspace_skills(+ skill_path,+ snapshot_workspace,+ skill_workspace_mode or snapshot_workspace.get("mode", "isolated"),+ include_skills,+ reference_skills_dir,+ )+ assert manifest is not None+ source_paths = [*manual, *selected]+ results_root = Path(output_dir) if output_dir is not None else skill_path / "evals" / "results"+ validate_output_provenance_key_location(+ skill_path,+ results_root,+ reference_skills_dir=reference_skills_dir,+ workspace_skill_paths=source_paths,+ )+ validate_results_root_location(+ skill_path,+ results_root,+ reference_skills_dir=reference_skills_dir,+ workspace_skill_paths=source_paths,+ )+ frozen = snapshot_stack.enter_context(_private_decoy_workspace_snapshot(selected, manifest))+ forwarded["_decoy_workspace_paths"] = [*manual, *frozen]+ forwarded["_decoy_workspace_source_paths"] = source_paths+ forwarded["_decoy_manifest"] = manifestif publication_target_from_path(skill_path) != snapshot_publication_target:raise ValueError("Publication source changed while its private evaluator snapshot was created")except (OSError, ValueError) as exc:@@ -4920,6 +5038,10 @@ def _run_harbor_eval_impl(if workspace_mode not in {"isolated", "group"}:reporter.emit(ProgressEvent(stage="configuration", state="failed", detail="invalid workspace mode"))return {"error": ["skill_workspace.mode must be isolated or group"]}+ if "decoy_manifest" in workspace_config and workspace_mode != "group":+ detail = "skill_workspace.decoy_manifest requires skill_workspace.mode=group"+ reporter.emit(ProgressEvent(stage="configuration", state="failed", detail=detail))+ return {"error": [detail]}if not skip_baseline and harbor_config.get("pre_agent_setup"):if skip_with_skill:# --skip-baseline cannot be combined with --skip-with-skill, so it@@ -5255,12 +5377,21 @@ def _run_harbor_eval_impl(job_judge_verifier_env = _job_judge_verifier_env(provider_env, grading_mode)job_judge_subprocess_env = _job_judge_subprocess_env(provider_env, grading_mode)+ if _decoy_manifest is not None:+ run_config["skill_workspace"] = {+ "mode": workspace_mode,+ "decoy_manifest": _decoy_manifest,+ }include_values = [*workspace_config.get("include", []), *(include_skills or [])]if include_values and workspace_mode != "group":reporter.emit(ProgressEvent(stage="with-skill-tasks", state="failed", detail="invalid included skills"))return {"error": ["include_skills requires skill_workspace.mode=group"]}try:- workspace_skills = _workspace_skills(skill_path.resolve(), include_values if workspace_mode == "group" else [])+ workspace_skills = (+ _decoy_workspace_paths+ if _decoy_workspace_paths is not None+ else _workspace_skills(skill_path.resolve(), include_values if workspace_mode == "group" else [])+ )except ValueError as exc:reporter.emit(ProgressEvent(stage="with-skill-tasks", state="failed", detail=str(exc)))return {"error": [str(exc)]}@@ -5272,13 +5403,13 @@ def _run_harbor_eval_impl(skill_path,root,reference_skills_dir=reference_skills_dir,- workspace_skill_paths=workspace_skills,+ workspace_skill_paths=_decoy_workspace_source_paths or workspace_skills,)validate_results_root_location(skill_path,root,reference_skills_dir=reference_skills_dir,- workspace_skill_paths=workspace_skills,+ workspace_skill_paths=_decoy_workspace_source_paths or workspace_skills,)except ValueError as exc:reporter.emit(ProgressEvent(stage="with-skill-tasks", state="failed", detail=str(exc)))@@ -5630,7 +5761,7 @@ def _run_harbor_eval_impl(skill_path,staged_task_paths,reference_skills_dir=reference_skills_dir,- workspace_skill_paths=workspace_skills,+ workspace_skill_paths=_decoy_workspace_source_paths or workspace_skills,):publication_target_conflict = {"run_start": dict(publication_target) if publication_target is not None else None,diff --git a/src/skillevaluator/tier3/workflow.py b/src/skillevaluator/tier3/workflow.pyindex bed5ee92..a667f212 100644--- a/src/skillevaluator/tier3/workflow.py+++ b/src/skillevaluator/tier3/workflow.py@@ -112,6 +112,7 @@ def _preflight_options(skill_path: Path, params: dict[str, Any]) -> dict[str, Anload_evals_config,)from skillevaluator.tier3.harbor.runner import (+ _decoy_workspace_skills,_model_for_agent,_resolve_agent_runtime_plan,_resolve_runtime_env,@@ -156,7 +157,15 @@ def _preflight_options(skill_path: Path, params: dict[str, Any]) -> dict[str, Aninclude_values = [*workspace.get("include", []), *cli_includes]if include_values and workspace.get("mode", "isolated") != "group":raise ValueError("include_skills requires skill_workspace.mode=group")- _workspace_skills(params["skill_path"].resolve(), include_values)+ if "decoy_manifest" in workspace:+ _decoy_workspace_skills(+ params["skill_path"],+ workspace,+ workspace.get("mode", "isolated"),+ cli_includes,+ )+ else:+ _workspace_skills(params["skill_path"].resolve(), include_values)agents = resolve_agents(params["agents"], provider=provider.provider)if not agents:diff --git a/tests/golden/cli_surface.json b/tests/golden/cli_surface.jsonindex 816c14ee..a8870cb7 100644--- a/tests/golden/cli_surface.json+++ b/tests/golden/cli_surface.json@@ -2989,6 +2989,73 @@}]},+ "select-decoys": {+ "params": [+ {+ "name": "skill_path",+ "opts": [+ "skill_path"+ ],+ "param_type": "argument",+ "required": true,+ "type": "directory"+ },+ {+ "name": "catalog_path",+ "opts": [+ "--catalog"+ ],+ "param_type": "option",+ "required": true,+ "type": "file"+ },+ {+ "name": "catalog_root",+ "opts": [+ "--catalog-root"+ ],+ "param_type": "option",+ "required": true,+ "type": "directory"+ },+ {+ "default": "4",+ "name": "count",+ "opts": [+ "--count"+ ],+ "param_type": "option",+ "type": "integer range"+ },+ {+ "multiple": true,+ "name": "exclude",+ "opts": [+ "--exclude"+ ],+ "param_type": "option",+ "type": "text"+ },+ {+ "name": "model",+ "opts": [+ "--model"+ ],+ "param_type": "option",+ "type": "text"+ },+ {+ "name": "output_path",+ "opts": [+ "--output",+ "-o"+ ],+ "param_type": "option",+ "required": true,+ "type": "file"+ }+ ]+ },"validate": {"params": [{diff --git a/tests/tier3/test_decoy_commands.py b/tests/tier3/test_decoy_commands.pynew file mode 100644index 00000000..3b8e44aa--- /dev/null+++ b/tests/tier3/test_decoy_commands.py@@ -0,0 +1,290 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++"""CLI authoring boundary for the opt-in decoy selection workflow."""++from __future__ import annotations++import copy+import json+from pathlib import Path+from unittest.mock import Mock++import pytest+from click.testing import CliRunner++from skillevaluator.cli import cli+++def _manifest() -> dict:+ from skillevaluator.tier3.decoy_identity import DECOY_SOURCE_DIGEST_ALGORITHM++ return {+ "schema_version": 1,+ "strategy": "description-similarity",+ "catalog_root": ".",+ "catalog": {+ "sha256": "0" * 64,+ "provider": "nv_build",+ "model": "test-model",+ "mode": "description",+ "endpoint_fingerprint": "sha256:" + "1" * 64,+ },+ "target": {"name": "target", "skill_name": "target", "manifest_sha256": "2" * 64},+ "count": 1,+ "exclude": [],+ "selected": [+ {"path": "neighbor", "name": "neighbor", "skill_name": "neighbor", "score": 0.5, "source_digest": "3" * 64}+ ],+ "source_digest_algorithm": DECOY_SOURCE_DIGEST_ALGORITHM,+ }+++def _arguments(tmp_path: Path) -> list[str]:+ target = tmp_path / "skills" / "target"+ target.mkdir(parents=True)+ (target / "SKILL.md").write_text("# Target", encoding="utf-8")+ catalog = tmp_path / "catalog.json"+ catalog.write_text("{}", encoding="utf-8")+ return [+ "tier3",+ "select-decoys",+ str(target),+ "--catalog",+ str(catalog),+ "--catalog-root",+ str(target.parent),+ "--count",+ "2",+ "--exclude",+ "helper",+ "--model",+ "example-model",+ ]+++def test_selection_command_passes_explicit_options(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ from skillevaluator.tier3 import decoys++ manifest = {"selected": [{"path": "neighbor-a"}, {"path": "neighbor-b"}]}+ select = Mock(return_value=manifest)+ write = Mock()+ monkeypatch.setattr(decoys, "select_decoys", select)+ monkeypatch.setattr(decoys, "write_decoy_manifest", write)+ output = tmp_path / "selection.json"+ result = CliRunner().invoke(cli, [*_arguments(tmp_path), "--output", str(output)])++ assert result.exit_code == 0, result.output+ assert "Saved 2 decoys" in result.output+ assert select.call_args.kwargs["count"] == 2+ assert select.call_args.kwargs["exclude"] == ("helper",)+ assert select.call_args.kwargs["client"]._model == "example-model"+ write.assert_called_once_with(manifest, output)++[email protected]("destination", ["catalog.json", "skills/target/SKILL.md", "skills/neighbor/new.json"])+def test_output_cannot_replace_or_mutate_catalog_inputs(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, destination: str+) -> None:+ from skillevaluator.tier3 import decoys++ select = Mock()+ monkeypatch.setattr(decoys, "select_decoys", select)+ result = CliRunner().invoke(cli, [*_arguments(tmp_path), "--output", str(tmp_path / destination)])++ assert result.exit_code == 1+ select.assert_not_called()+ assert (tmp_path / "skills" / "target" / "SKILL.md").read_text(encoding="utf-8") == "# Target"+++def test_target_evaluator_directory_can_hold_selection(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ from skillevaluator.tier3 import decoys++ monkeypatch.setattr(decoys, "select_decoys", Mock(return_value={"selected": []}))+ write = Mock()+ monkeypatch.setattr(decoys, "write_decoy_manifest", write)+ result = CliRunner().invoke(+ cli,+ [*_arguments(tmp_path), "--output", str(tmp_path / "skills" / "target" / "evals" / "decoys.json")],+ )++ assert result.exit_code == 0, result.output+ write.assert_called_once()+++def test_selection_failure_does_not_write_manifest(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ from skillevaluator.tier3 import decoys++ monkeypatch.setattr(decoys, "select_decoys", Mock(side_effect=ValueError("Not enough eligible decoys")))+ output = tmp_path / "selection.json"+ result = CliRunner().invoke(cli, [*_arguments(tmp_path), "--output", str(output)])++ assert result.exit_code == 1+ assert "Not enough eligible decoys" in result.output+ assert not output.exists()+++def test_selection_help_does_not_require_llm_configuration(monkeypatch: pytest.MonkeyPatch) -> None:+ for key in ("NVIDIA_API_KEY", "OPENAI_API_KEY", "SKILL_EVAL_LLM_PROVIDER"):+ monkeypatch.delenv(key, raising=False)+ result = CliRunner().invoke(cli, ["tier3", "select-decoys", "--help"])++ assert result.exit_code == 0+ assert "--catalog-root" in result.output++[email protected]("filename", ["evals.json", "evals.jsonl", "config.yml", "config.yaml"])[email protected]("existing", [False, True])+def test_manifest_output_cannot_claim_evaluation_inputs(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, filename: str, existing: bool+) -> None:+ from skillevaluator.tier3 import decoys++ arguments = _arguments(tmp_path)+ output = tmp_path / "skills" / "target" / "evals" / filename+ output.parent.mkdir()+ if existing:+ output.write_bytes(b"evaluation input that must survive\n")+ select = Mock(return_value=_manifest())+ monkeypatch.setattr(decoys, "select_decoys", select)++ result = CliRunner().invoke(cli, [*arguments, "--output", str(output)])++ assert result.exit_code == 1+ assert "evaluation dataset or run policy" in result.output+ select.assert_not_called()+ if existing:+ assert output.read_bytes() == b"evaluation input that must survive\n"+ else:+ assert not output.exists()+++ ("destination", "contents"),+ [+ ("skills/target/evals/oracle.txt", "private evaluation answers\n"),+ ("skills/target/evals/custom.json", '[{"id": "case-001"}]\n'),+ ("skills/target/evals/selection.json", '{"selected": []}\n'),+ ("report.txt", "existing report\n"),+ ],+)+def test_existing_nonmanifest_output_survives_real_writer(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, destination: str, contents: str+) -> None:+ from skillevaluator.tier3 import decoys++ arguments = _arguments(tmp_path)+ output = tmp_path / destination+ output.parent.mkdir(parents=True, exist_ok=True)+ output.write_text(contents, encoding="utf-8")+ select = Mock(return_value=_manifest())+ monkeypatch.setattr(decoys, "select_decoys", select)++ result = CliRunner().invoke(cli, [*arguments, "--output", str(output)])++ assert result.exit_code == 1+ assert "not a decoy manifest" in result.output+ select.assert_not_called()+ assert output.read_text(encoding="utf-8") == contents+++def test_existing_stale_manifest_can_be_regenerated(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ from skillevaluator.tier3 import decoys++ arguments = _arguments(tmp_path)+ output = tmp_path / "skills" / "target" / "evals" / "decoys.json"+ previous = _manifest()+ # Regeneration must work after a target/source edit or a digest recipe change.+ previous["source_digest_algorithm"] = "skill-evaluator-source-tree/2"+ previous["target"]["manifest_sha256"] = "a" * 64+ decoys.write_decoy_manifest(previous, output)+ replacement = copy.deepcopy(previous)+ replacement["target"]["manifest_sha256"] = "b" * 64+ monkeypatch.setattr(decoys, "select_decoys", Mock(return_value=replacement))++ result = CliRunner().invoke(cli, [*arguments, "--output", str(output)])++ assert result.exit_code == 0, result.output+ assert json.loads(output.read_text(encoding="utf-8")) == replacement++[email protected]("destination", ["CATALOG.json", "SKILLS/neighbor/SKILL.md", "SKILLS/new/decoys.json"])+def test_case_insensitive_filesystem_identity_protects_inputs(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, destination: str+) -> None:+ from skillevaluator.tier3 import decoys++ arguments = _arguments(tmp_path)+ protected = tmp_path / "skills" / "neighbor" / "SKILL.md"+ protected.parent.mkdir()+ protected.write_text("neighbor instructions\n", encoding="utf-8")+ real_samefile = Path.samefile+ aliases = {tmp_path / "SKILLS": tmp_path / "skills", tmp_path / "CATALOG.json": tmp_path / "catalog.json"}++ def canonical(path: Path) -> Path:+ for alias, actual in aliases.items():+ if path.is_relative_to(alias):+ return actual / path.relative_to(alias)+ return path++ def samefile(path: Path, other: Path) -> bool:+ # Model only identity lookup on a case-insensitive filesystem; retain+ # ordinary missing-file behavior for not-yet-created output ancestors.+ return real_samefile(canonical(path), canonical(other))++ monkeypatch.setattr(Path, "samefile", samefile)+ select = Mock(return_value=_manifest())+ monkeypatch.setattr(decoys, "select_decoys", select)++ result = CliRunner().invoke(cli, [*arguments, "--output", str(tmp_path / destination)])++ assert result.exit_code == 1+ select.assert_not_called()+ assert protected.read_text(encoding="utf-8") == "neighbor instructions\n"+ assert (tmp_path / "catalog.json").read_text(encoding="utf-8") == "{}"+ if destination == "CATALOG.json":+ assert "must not replace the embedding catalog" in result.output+ else:+ assert "outside the skill collection" in result.output++[email protected]("destination", ["CATALOG.json", "SKILLS/neighbor/SKILL.md"])+def test_native_case_alias_cannot_overwrite_an_input(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, destination: str+) -> None:+ from skillevaluator.tier3 import decoys++ arguments = _arguments(tmp_path)+ neighbor = tmp_path / "skills" / "neighbor" / "SKILL.md"+ neighbor.parent.mkdir()+ neighbor.write_text("neighbor instructions\n", encoding="utf-8")+ output = tmp_path / destination+ if not output.exists():+ pytest.skip("requires a case-insensitive filesystem")+ before = output.read_bytes()+ select = Mock(return_value=_manifest())+ monkeypatch.setattr(decoys, "select_decoys", select)++ result = CliRunner().invoke(cli, [*arguments, "--output", str(output)])++ assert result.exit_code == 1+ select.assert_not_called()+ assert output.read_bytes() == before+++def test_distinct_case_sensitive_directory_can_hold_output(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ from skillevaluator.tier3 import decoys++ arguments = _arguments(tmp_path)+ separate = tmp_path / "SKILLS"+ separate.mkdir(exist_ok=True)+ if separate.samefile(tmp_path / "skills"):+ pytest.skip("requires distinct case-sensitive directory names")+ output = separate / "decoys.json"+ manifest = _manifest()+ monkeypatch.setattr(decoys, "select_decoys", Mock(return_value=manifest))++ result = CliRunner().invoke(cli, [*arguments, "--output", str(output)])++ assert result.exit_code == 0, result.output+ assert json.loads(output.read_text(encoding="utf-8")) == manifestdiff --git a/tests/tier3/test_decoy_identity.py b/tests/tier3/test_decoy_identity.pynew file mode 100644index 00000000..be9c9ffb--- /dev/null+++ b/tests/tier3/test_decoy_identity.py@@ -0,0 +1,189 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++"""Runtime identity must match the exact decoy content copied to agents."""++from __future__ import annotations++import os+from pathlib import Path++import pytest++from skillevaluator.publication_identity import publication_source_digest+from skillevaluator.tier3.decoy_identity import decoy_source_copy_ignore, decoy_source_digest+from skillevaluator.tier3.harbor import secure_copy+++def _skill(path: Path) -> Path:+ path.mkdir(parents=True)+ (path / "SKILL.md").write_text(f"# {path.name}\nRuntime instructions.\n", encoding="utf-8")+ return path++[email protected]("filename", ["evals/config.yml", "evals/evals.json", "evals/decoys.json"])+def test_evaluator_edits_leave_runtime_identity_unchanged(tmp_path: Path, filename: str) -> None:+ source = _skill(tmp_path / "decoy")+ runtime_before = decoy_source_digest(source)+ publication_before = publication_source_digest(source)+ assert runtime_before is not None+ evaluator_file = source / filename+ evaluator_file.parent.mkdir(exist_ok=True)+ evaluator_file.write_text("new evaluator input\n", encoding="utf-8")++ assert decoy_source_digest(source) == runtime_before+ assert publication_source_digest(source) != publication_before+ evaluator_file.write_text("changed evaluator input\n", encoding="utf-8")+ assert decoy_source_digest(source) == runtime_before+++def test_nested_skill_evals_are_excluded_but_reference_evals_are_runtime(tmp_path: Path) -> None:+ source = _skill(tmp_path / "decoy")+ nested = _skill(source / "references" / "nested-skill")+ before = decoy_source_digest(source)+ assert before is not None+ oracle = nested / "evals" / "oracle.txt"+ oracle.parent.mkdir()+ oracle.write_text("private evaluator data\n", encoding="utf-8")++ assert decoy_source_digest(source) == before+ ordinary = source / "references" / "evals" / "guide.txt"+ ordinary.parent.mkdir()+ ordinary.write_text("agent-visible reference\n", encoding="utf-8")+ assert decoy_source_digest(source) != before++[email protected]("filename", ["SKILL.md", "scripts/helper.py", "references/guide.md"])+def test_runtime_edits_change_identity(tmp_path: Path, filename: str) -> None:+ source = _skill(tmp_path / "decoy")+ before = decoy_source_digest(source)+ assert before is not None+ runtime_file = source / filename+ runtime_file.parent.mkdir(parents=True, exist_ok=True)+ runtime_file.write_text("changed runtime input\n", encoding="utf-8")++ assert decoy_source_digest(source) != before++[email protected](os.name == "nt", reason="Windows does not preserve POSIX executable bits")+def test_executable_bits_change_runtime_identity(tmp_path: Path) -> None:+ source = _skill(tmp_path / "decoy")+ script = source / "helper.sh"+ script.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")+ script.chmod(0o644)+ before = decoy_source_digest(source)+ assert before is not None+ script.chmod(0o755)++ assert decoy_source_digest(source) != before++[email protected](os.name == "nt", reason="Windows does not preserve POSIX permission bits")[email protected]("umask", [0o027, 0o077])+def test_clone_umask_leaves_runtime_identity_unchanged(tmp_path: Path, umask: int) -> None:+ source = _skill(tmp_path / "decoy")+ scripts = source / "scripts"+ scripts.mkdir()+ script = scripts / "run.sh"+ script.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")+ modes = {source: 0o755, scripts: 0o755, script: 0o755, source / "SKILL.md": 0o644}+ for path, mode in modes.items():+ path.chmod(mode)+ before = decoy_source_digest(source)+ assert before is not None++ # A clone made under another umask differs only in group and other bits.+ for path, mode in modes.items():+ path.chmod(mode & ~umask)+ assert decoy_source_digest(source) == before+++def test_secure_runtime_snapshot_has_the_same_identity(tmp_path: Path) -> None:+ source = _skill(tmp_path / "decoy")+ nested = _skill(source / "references" / "nested")+ for owner in (source, nested):+ (owner / "evals").mkdir()+ (owner / "evals" / "oracle.txt").write_text("private\n", encoding="utf-8")+ ordinary = source / "references" / "evals"+ ordinary.mkdir()+ (ordinary / "guide.txt").write_text("runtime guide\n", encoding="utf-8")+ snapshot = tmp_path / "snapshot"+ before = decoy_source_digest(source)+ assert before is not None++ secure_copy.copytree_secure(+ source,+ snapshot,+ allowed_root=source,+ ignore=decoy_source_copy_ignore(source),+ )++ assert decoy_source_digest(snapshot) == before+ assert not (snapshot / "evals").exists()+ assert not (snapshot / "references" / "nested" / "evals").exists()+ assert (snapshot / "references" / "evals" / "guide.txt").read_text() == "runtime guide\n"++[email protected]("unsafe", ["symlink", "hardlink", "root-symlink", "fifo"])+def test_unsafe_runtime_sources_fail_closed(tmp_path: Path, unsafe: str) -> None:+ source = _skill(tmp_path / "decoy")+ if unsafe == "symlink":+ (source / "linked.md").symlink_to(source / "SKILL.md")+ elif unsafe == "hardlink":+ (source / "linked.md").hardlink_to(source / "SKILL.md")+ elif unsafe == "root-symlink":+ alias = tmp_path / "alias"+ alias.symlink_to(source, target_is_directory=True)+ source = alias+ else:+ if not hasattr(os, "mkfifo"):+ pytest.skip("FIFOs are unavailable")+ os.mkfifo(source / "pipe")++ assert decoy_source_digest(source) is None+++def test_normalized_path_collisions_fail_closed(tmp_path: Path) -> None:+ source = _skill(tmp_path / "decoy")+ first = source / "caf\u00e9.md"+ second = source / "cafe\u0301.md"+ first.write_text("first\n", encoding="utf-8")+ if second.exists():+ pytest.skip("Filesystem normalizes Unicode path names")+ second.write_text("second\n", encoding="utf-8")++ assert decoy_source_digest(source) is None++[email protected]("after_capture", [1, 2])+def test_changes_between_stability_passes_fail_closed(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, after_capture: int+) -> None:+ source = _skill(tmp_path / "decoy")+ capture = secure_copy._build_tree_manifest+ count = 0++ def changing_capture(*args, **kwargs):+ nonlocal count+ manifest = capture(*args, **kwargs)+ count += 1+ if count == after_capture:+ (source / "SKILL.md").write_text("changed after capture\n", encoding="utf-8")+ return manifest++ monkeypatch.setattr(secure_copy, "_build_tree_manifest", changing_capture)++ assert decoy_source_digest(source) is None+++def test_checked_fallback_retains_runtime_projection(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ source = _skill(tmp_path / "decoy")+ (source / "evals").mkdir()+ (source / "evals" / "config.yml").write_text("private\n", encoding="utf-8")+ expected = decoy_source_digest(source)+ assert expected is not None+ monkeypatch.setattr(secure_copy, "_DESCRIPTOR_BACKEND", False)++ assert decoy_source_digest(source) == expected+ (source / "linked.md").symlink_to(source / "SKILL.md")+ assert decoy_source_digest(source) is Nonediff --git a/tests/tier3/test_decoy_workspace.py b/tests/tier3/test_decoy_workspace.pynew file mode 100644index 00000000..31b9d83c--- /dev/null+++ b/tests/tier3/test_decoy_workspace.py@@ -0,0 +1,362 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++"""Frozen decoy selections preserve the paired workspace contract."""++from __future__ import annotations++import json+import subprocess+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import MagicMock++import pytest++from skillevaluator.provider_config import ProviderConfig+from skillevaluator.tier3.decoy_identity import decoy_source_digest+from skillevaluator.tier3.evals_config import EvalsConfigError, load_evals_config+from skillevaluator.tier3.harbor import runner+from skillevaluator.tier3.harbor.adapter import generate_harbor_tasks+++def _skill(path: Path, *, skill_name: str | None = None) -> Path:+ path.mkdir(parents=True)+ (path / "SKILL.md").write_text(+ f"---\nname: {skill_name or path.name}\ndescription: Use this {path.name} workflow.\n---\n"+ f"# {path.name}\nFollow the {path.name} procedure.\n",+ encoding="utf-8",+ )+ return path+++def _manifest(selected: list[Path]) -> dict:+ return {+ "selected": [+ {"path": path.name, "skill_name": path.name, "source_digest": decoy_source_digest(path)}+ for path in selected+ ]+ }+++def _config(skill: Path, workspace: str) -> None:+ (skill / "evals").mkdir(exist_ok=True)+ (skill / "evals" / "config.yml").write_text(+ "schema_version: 1\nskill_workspace:\n" + workspace,+ encoding="utf-8",+ )++[email protected]("value", ["null", "[]", "{}", "3", "true", "''", "' '"])+def test_decoy_manifest_config_requires_nonempty_path(tmp_path: Path, value: str) -> None:+ target = _skill(tmp_path / "target")+ _config(target, f" mode: group\n decoy_manifest: {value}\n")++ with pytest.raises(EvalsConfigError, match=r"skill_workspace\.decoy_manifest"):+ load_evals_config(target)+++def test_decoy_config_defers_mode_validation_until_cli_override(tmp_path: Path, monkeypatch) -> None:+ from skillevaluator.tier3 import decoys++ target = _skill(tmp_path / "target")+ decoy = _skill(tmp_path / "decoy")+ _config(target, " mode: isolated\n decoy_manifest: frozen.json\n")+ config, _ = load_evals_config(target)+ seen: list[Path] = []++ def load(_target, path):+ seen.append(path)+ return [decoy], _manifest([decoy])++ monkeypatch.setattr(decoys, "load_decoy_manifest", load)+ with pytest.raises(ValueError, match=r"requires skill_workspace\.mode=group"):+ runner._decoy_workspace_skills(target, config["skill_workspace"], "isolated")+ assert seen == []++ manual, selected, manifest = runner._decoy_workspace_skills(target, config["skill_workspace"], "group")+ assert manual == []+ assert selected == [decoy]+ assert manifest is not None+ assert seen == [target.parent / "frozen.json"]++[email protected]("collision", ["basename", "metadata", "reference"])+def test_decoy_names_cannot_be_silently_shadowed(tmp_path: Path, monkeypatch, collision: str) -> None:+ from skillevaluator.tier3 import decoys++ target = _skill(tmp_path / "target")+ decoy = _skill(tmp_path / "catalog" / "decoy")+ helper_name = "DECOY" if collision == "basename" else "helper"+ helper = _skill(+ tmp_path / "helpers" / helper_name,+ skill_name="helper-skill" if collision == "basename" else "decoy",+ )+ references = tmp_path / "helpers" if collision == "reference" else None+ config = {"mode": "group", "decoy_manifest": "frozen.json"}+ if references is None:+ config["include"] = [str(helper)]+ monkeypatch.setattr(decoys, "load_decoy_manifest", lambda *_: ([decoy], _manifest([decoy])))++ with pytest.raises(ValueError, match="collides with another workspace skill name"):+ runner._decoy_workspace_skills(target, config, "group", reference_skills_dir=references)++[email protected]("source", ["include", "reference"])+ ("helper_directory", "manifest_text"),+ [+ ("pdf-helper", "---\nname: pdf\n---\n# PDF helper\n"),+ ("pdf", "# PDF helper without frontmatter\n"),+ ("pdf", "---\nname: ' '\n---\n# PDF helper\n"),+ ("pdf", "---\nname: 3\n---\n# PDF helper\n"),+ ],+)+def test_decoy_name_collision_uses_helper_name_without_description(+ tmp_path: Path, monkeypatch, source: str, helper_directory: str, manifest_text: str+) -> None:+ from skillevaluator.tier3 import decoys++ target = _skill(tmp_path / "target")+ decoy = _skill(tmp_path / "catalog" / "pdf-tools", skill_name="pdf")+ helper = _skill(tmp_path / "helpers" / helper_directory)+ (helper / "SKILL.md").write_text(manifest_text, encoding="utf-8")+ manifest = _manifest([decoy])+ manifest["selected"][0]["skill_name"] = "pdf"+ monkeypatch.setattr(decoys, "load_decoy_manifest", lambda *_: ([decoy], manifest))+ config = {"mode": "group", "decoy_manifest": "frozen.json"}+ references = helper.parent if source == "reference" else None+ if source == "include":+ config["include"] = [str(helper)]++ with pytest.raises(ValueError, match="collides with another workspace skill name"):+ runner._decoy_workspace_skills(target, config, "group", reference_skills_dir=references)+++def test_invalid_decoy_manifest_fails_before_provider_resolution(tmp_path: Path, monkeypatch) -> None:+ from skillevaluator.tier3 import decoys++ target = _skill(tmp_path / "target")+ _config(target, " mode: group\n decoy_manifest: frozen.json\n")++ def invalid(*_args):+ raise ValueError("Frozen decoy source changed")++ def unexpected():+ pytest.fail("Provider resolution must follow decoy validation")++ monkeypatch.setattr(decoys, "load_decoy_manifest", invalid)+ monkeypatch.setattr(runner, "resolve_llm_provider", unexpected)++ result = runner._run_harbor_eval_impl(target, ["codex"])++ assert result == {"error": ["Frozen decoy source changed"]}+++def test_decoy_snapshot_rejects_source_changed_since_selection(tmp_path: Path) -> None:+ decoy = _skill(tmp_path / "decoy")+ manifest = _manifest([decoy])+ (decoy / "SKILL.md").write_text("changed", encoding="utf-8")++ with (+ pytest.raises(ValueError, match="changed before snapshot"),+ runner._private_decoy_workspace_snapshot([decoy], manifest),+ ):+ pytest.fail("Changed source must never be exposed")+++def test_decoy_snapshot_ignores_changed_evaluator_files(tmp_path: Path) -> None:+ decoy = _skill(tmp_path / "decoy")+ (decoy / "evals").mkdir()+ config = decoy / "evals" / "config.yml"+ config.write_text("schema_version: 1\n", encoding="utf-8")+ manifest = _manifest([decoy])+ config.write_text("schema_version: 1\nharbor:\n max_cases: 2\n", encoding="utf-8")+ (decoy / "evals" / "decoys.json").write_text("{}\n", encoding="utf-8")++ with runner._private_decoy_workspace_snapshot([decoy], manifest) as frozen:+ assert (frozen[0] / "SKILL.md").read_bytes() == (decoy / "SKILL.md").read_bytes()+ assert not (frozen[0] / "evals").exists()+ assert decoy_source_digest(frozen[0]) == manifest["selected"][0]["source_digest"]+++def test_frozen_decoy_stages_identically_after_source_changes(tmp_path: Path) -> None:+ target = _skill(tmp_path / "repo" / "target")+ subprocess.run(["git", "init", "--quiet", str(target.parent)], check=True, capture_output=True)+ (target / "evals").mkdir()+ (target / "evals" / "evals.json").write_text(+ json.dumps([{"id": "case-001", "question": "Use the target procedure."}]), encoding="utf-8"+ )+ decoy = _skill(tmp_path / "decoy")+ (decoy / "evals").mkdir()+ (decoy / "evals" / "oracle.txt").write_text("private evaluator data", encoding="utf-8")+ manifest = _manifest([decoy])+ expected = (decoy / "SKILL.md").read_bytes()++ with runner._private_decoy_workspace_snapshot([decoy], manifest) as frozen:+ (decoy / "SKILL.md").write_text("changed after snapshot", encoding="utf-8")+ tasks = [+ generate_harbor_tasks(+ target,+ tmp_path / arm,+ with_skill=with_skill,+ workspace_skill_paths=frozen,+ workspace_mode="group",+ )[0]+ for arm, with_skill in (("with-skill", True), ("baseline", False))+ ]+ for task in tasks:+ staged = task / "environment" / "skills" / decoy.name+ assert (staged / "SKILL.md").read_bytes() == expected+ assert not (staged / "evals").exists()+ assert (tasks[0] / "environment" / "skills" / target.name / "SKILL.md").exists()+ assert not (tasks[1] / "environment" / "skills" / target.name).exists()+ snapshot_root = frozen[0].parent+ assert not snapshot_root.exists()+++def test_runner_reuses_frozen_selection_and_records_original_provenance(tmp_path: Path, monkeypatch) -> None:+ from skillevaluator.tier3 import decoys+ from skillevaluator.tier3.harbor import runtime_preflight++ target = _skill(tmp_path / "repo" / "target")+ subprocess.run(["git", "init", "--quiet", str(target.parent)], check=True, capture_output=True)+ _config(target, " mode: group\n decoy_manifest: frozen.json\n")+ decoy = _skill(tmp_path / "catalog" / "decoy")+ manifest = _manifest([decoy])+ expected = (decoy / "SKILL.md").read_bytes()+ emitted: list[tuple[bool, list[Path]]] = []+ provenance_sources: list[Path] = []+ monkeypatch.setattr(decoys, "load_decoy_manifest", lambda *_: ([decoy], manifest))+ monkeypatch.setattr(+ runner,+ "resolve_llm_provider",+ lambda: ProviderConfig(+ provider="nv_build",+ model="test-model",+ api_key="provider-key",+ base_url="https://provider.example/v1",+ litellm_model="openai/test-model",+ ),+ )+ monkeypatch.setattr(runner, "find_evals_file", lambda _: target / "evals" / "evals.json")+ monkeypatch.setattr(runner, "_check_prerequisites", lambda **_: [])+ monkeypatch.setattr(runner, "_run_agent_pair", lambda **_: [])+ monkeypatch.setattr(+ runner,+ "collect_harbor_results",+ lambda **_: {"execution_status": "succeeded", "execution_errors": [], "metrics": [], "agents": {}},+ )+ monkeypatch.setattr(runner, "render_agent_eval_html_report", lambda *_args, **_kw: tmp_path / "report.html")+ monkeypatch.setattr(+ runtime_preflight,+ "probe_model",+ lambda provider: runtime_preflight.ModelProbeResult(True, provider.provider, provider.model, "available"),+ )++ def emit(_skill, output, **kwargs):+ sources = kwargs["workspace_skill_paths"]+ assert (sources[0] / "SKILL.md").read_bytes() == expected+ emitted.append((kwargs["with_skill"], sources))+ (decoy / "SKILL.md").write_text("changed after first arm", encoding="utf-8")+ task = output / "case-001"+ task.mkdir(parents=True)+ return [task]++ def publication_inputs(_skill, _tasks, **kwargs):+ provenance_sources.extend(kwargs["workspace_skill_paths"])+ return False++ monkeypatch.setattr(runner, "generate_harbor_tasks", emit)+ monkeypatch.setattr(runner, "_runtime_context_is_bound_to_publication_target", publication_inputs)++ result = runner.run_harbor_eval(target, ["opencode"], output_dir=tmp_path / "results")++ assert "error" not in result+ assert [with_skill for with_skill, _ in emitted] == [True, False]+ assert emitted[0][1] == emitted[1][1]+ assert emitted[0][1][0] != decoy+ assert provenance_sources == [decoy]+ assert result["run_config"]["skill_workspace"]["decoy_manifest"] == manifest+++def test_runner_stages_config_and_cli_helpers_with_real_decoy_manifest(tmp_path: Path, monkeypatch) -> None:+ from skillevaluator.embedding.client import EmbeddingClient+ from skillevaluator.embedding.registry import EmbeddingRegistry+ from skillevaluator.tier3.decoys import select_decoys, write_decoy_manifest+ from skillevaluator.tier3.harbor import runtime_preflight++ collection = tmp_path / "repo"+ target = _skill(collection / "target")+ subprocess.run(["git", "init", "--quiet", str(collection)], check=True, capture_output=True)+ config_helper = _skill(collection / "config-helper")+ cli_helper = _skill(collection / "cli-helper")+ decoy = _skill(tmp_path / "catalog" / "decoy")+ _config(target, " mode: group\n include:\n - config-helper\n decoy_manifest: target/evals/decoys.json\n")+ (target / "evals" / "evals.json").write_text(+ json.dumps([{"id": "case-001", "question": "Use the target procedure."}]), encoding="utf-8"+ )+ client = MagicMock(spec=EmbeddingClient)+ client.model = "test-model"+ client._resolved_config.return_value = SimpleNamespace(provider="nv_build", base_url="https://example.com/v1")+ client.embed.return_value = [[1.0, 0.0]]+ client.embed_single.return_value = [1.0, 0.0]+ catalog = tmp_path / "catalog.json"+ registry = EmbeddingRegistry(client)+ registry.build_from_directory(decoy.parent, "skill")+ registry.save_catalog(catalog)+ manifest = select_decoys(target, catalog_path=catalog, catalog_root=decoy.parent, count=1, client=client)+ write_decoy_manifest(manifest, target / "evals" / "decoys.json")+ expected = {path.name: (path / "SKILL.md").read_bytes() for path in (config_helper, cli_helper, decoy)}+ staged_arms: list[bool] = []++ def stage(skill, output, **kwargs):+ paths = generate_harbor_tasks(skill, output, **kwargs)+ for task in paths:+ staged = task / "environment" / "skills"+ assert {path.name for path in staged.iterdir()} == {+ *expected,+ *([target.name] if kwargs["with_skill"] else []),+ }+ for name, content in expected.items():+ assert (staged / name / "SKILL.md").read_bytes() == content+ staged_arms.append(kwargs["with_skill"])+ return paths++ monkeypatch.setattr(runner, "generate_harbor_tasks", stage)+ monkeypatch.setattr(+ runner,+ "resolve_llm_provider",+ lambda: ProviderConfig(+ provider="nv_build",+ model="test-model",+ api_key="provider-key",+ base_url="https://provider.example/v1",+ litellm_model="openai/test-model",+ ),+ )+ monkeypatch.setattr(runner, "_check_prerequisites", lambda **_: [])+ monkeypatch.setattr(runner, "_run_agent_pair", lambda **_: [])+ monkeypatch.setattr(+ runner,+ "collect_harbor_results",+ lambda **_: {"execution_status": "succeeded", "execution_errors": [], "metrics": [], "agents": {}},+ )+ monkeypatch.setattr(runner, "render_agent_eval_html_report", lambda *_args, **_kw: tmp_path / "report.html")+ monkeypatch.setattr(+ runtime_preflight,+ "probe_model",+ lambda provider: runtime_preflight.ModelProbeResult(True, provider.provider, provider.model, "available"),+ )++ result = runner.run_harbor_eval(+ target,+ ["opencode"],+ output_dir=tmp_path / "results",+ include_skills=[str(cli_helper)],+ agent_runtime_preflight=False,+ )++ assert "error" not in result+ assert staged_arms == [True, False]+ assert result["run_config"]["skill_workspace"]["decoy_manifest"] == manifestdiff --git a/tests/tier3/test_decoys.py b/tests/tier3/test_decoys.pynew file mode 100644index 00000000..8b16d2a7--- /dev/null+++ b/tests/tier3/test_decoys.py@@ -0,0 +1,585 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++"""Offline selection and frozen-source checks for group-workspace decoys."""++from __future__ import annotations++import copy+import hashlib+import json+import shutil+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import MagicMock++import pytest++from skillevaluator.embedding.client import EmbeddingClient+from skillevaluator.embedding.registry import EmbeddingRegistry+from skillevaluator.tier3.decoy_identity import DECOY_SOURCE_DIGEST_ALGORITHM, decoy_source_digest+from skillevaluator.tier3.decoys import (+ _catalog_root_record,+ load_decoy_manifest,+ select_decoys,+ write_decoy_manifest,+)+++def _skill(root: Path, name: str, *, skill_name: str | None = None) -> Path:+ path = root / name+ path.mkdir(parents=True)+ (path / "SKILL.md").write_text(+ f"---\nname: {skill_name or path.name}\ndescription: Help with {path.name}.\n---\n\n# {path.name}\n",+ encoding="utf-8",+ )+ return path+++def _client(vectors: list[list[float]] | None = None) -> EmbeddingClient:+ client = MagicMock(spec=EmbeddingClient)+ client.model = "test-model"+ client._resolved_config.return_value = SimpleNamespace(provider="nv_build", base_url="https://example.com/v1")+ client.embed.return_value = vectors or [[1.0, 0.0], [0.8, 0.6], [0.0, 1.0]]+ client.embed_single.return_value = [1.0, 0.0]+ return client+++def _catalog(root: Path, path: Path, client: EmbeddingClient) -> None:+ registry = EmbeddingRegistry(client)+ registry.build_from_directory(root, "skill")+ registry.save_catalog(path)+++def _selected_record(path: Path, root: Path) -> dict:+ digest = decoy_source_digest(path)+ assert digest is not None+ return {+ "path": path.relative_to(root).as_posix(),+ "name": path.name,+ "skill_name": path.name,+ "score": 1.0,+ "source_digest": digest,+ }+++def selection(tmp_path: Path) -> SimpleNamespace:+ root = tmp_path / "catalog-skills"+ skills = [_skill(root, name) for name in ("api-debugger", "log-triage", "release-planner")]+ target = _skill(tmp_path, "target")+ catalog = tmp_path / "catalog.json"+ client = _client()+ _catalog(root, catalog, client)+ return SimpleNamespace(root=root, target=target, catalog=catalog, client=client, skills=skills)+++def _select(selection: SimpleNamespace, **kwargs: object) -> dict:+ return select_decoys(+ selection.target,+ catalog_path=selection.catalog,+ catalog_root=selection.root,+ client=selection.client,+ count=kwargs.pop("count", 2),+ **kwargs,+ )+++def test_selects_ranked_skills_and_records_complete_provenance(selection: SimpleNamespace) -> None:+ manifest = _select(selection)+ assert [item["path"] for item in manifest["selected"]] == ["api-debugger", "log-triage"]+ assert [item["score"] for item in manifest["selected"]] == [1.0, 0.8]+ assert manifest["catalog"]["sha256"] == hashlib.sha256(selection.catalog.read_bytes()).hexdigest()+ assert manifest["catalog"]["model"] == "test-model"+ assert manifest["catalog"]["mode"] == "description"+ assert (+ manifest["target"]["manifest_sha256"]+ == hashlib.sha256((selection.target / "SKILL.md").read_bytes()).hexdigest()+ )+ assert all(len(item["source_digest"]) == 64 for item in manifest["selected"])+ assert manifest["source_digest_algorithm"] == DECOY_SOURCE_DIGEST_ALGORITHM+++def test_ties_and_reordered_catalog_are_repeatable(selection: SimpleNamespace) -> None:+ raw = json.loads(selection.catalog.read_text())+ for item in raw["entries"]:+ item["embedding"] = [1.0, 0.0]+ selection.catalog.write_text(json.dumps(raw))+ first = _select(selection)+ raw["entries"].reverse()+ selection.catalog.write_text(json.dumps(raw))+ second = _select(selection)+ assert first["selected"] == second["selected"]+ assert [item["path"] for item in first["selected"]] == ["api-debugger", "log-triage"]+++def test_explicit_exclusion_is_respected(selection: SimpleNamespace) -> None:+ manifest = _select(selection, exclude=("api-debugger",))+ assert [item["path"] for item in manifest["selected"]] == ["log-triage", "release-planner"]+ assert manifest["exclude"] == ["api-debugger"]++[email protected]("count", [0, -1, True, 1.5, 1001])+def test_rejects_invalid_count_before_model_calls(selection: SimpleNamespace, count: object) -> None:+ with pytest.raises(ValueError, match="count"):+ _select(selection, count=count)+ selection.client.embed_single.assert_not_called()+++def test_insufficient_candidates_never_silently_reduces_count(selection: SimpleNamespace) -> None:+ with pytest.raises(ValueError, match="Requested 4 decoys but only 3"):+ _select(selection, count=4)+++def test_unknown_exclusion_is_a_configuration_error(selection: SimpleNamespace) -> None:+ with pytest.raises(ValueError, match="absent from catalog"):+ _select(selection, exclude=("typo",))+ selection.client.embed_single.assert_not_called()+++def test_stale_catalog_description_fails(selection: SimpleNamespace) -> None:+ path = selection.skills[0] / "SKILL.md"+ path.write_text(path.read_text().replace("Help with", "Changed description for"))+ with pytest.raises(ValueError, match="stale"):+ _select(selection)+++def test_excludes_target_basename_metadata_identity_and_copied_instructions(tmp_path: Path) -> None:+ root = tmp_path / "skills"+ target = _skill(root, "target")+ _skill(root, "a-collision", skill_name="target")+ clone = _skill(root, "b-clone")+ (clone / "SKILL.md").write_text((target / "SKILL.md").read_text().replace("name: target", "name: b-clone"))+ _skill(root, "c-good")+ client = _client([[1.0, 0.0]] * 4)+ catalog = tmp_path / "catalog.json"+ _catalog(root, catalog, client)+ manifest = select_decoys(target, catalog_path=catalog, catalog_root=root, count=1, client=client)+ assert manifest["selected"][0]["path"] == "c-good"+++def test_deduplicates_directory_basename_across_nested_catalog(tmp_path: Path) -> None:+ root = tmp_path / "skills"+ _skill(root, "a/shared", skill_name="one")+ _skill(root, "b/shared", skill_name="two")+ _skill(root, "c-other")+ target = _skill(tmp_path, "target")+ client = _client([[1.0, 0.0]] * 3)+ catalog = tmp_path / "catalog.json"+ _catalog(root, catalog, client)+ manifest = select_decoys(target, catalog_path=catalog, catalog_root=root, count=2, client=client)+ assert [item["path"] for item in manifest["selected"]] == ["a/shared", "c-other"]+++def test_excludes_skills_nested_inside_the_target(tmp_path: Path) -> None:+ root = tmp_path / "skills"+ target = _skill(root, "a-target")+ _skill(root, "a-target/companions/rollback-helper")+ _skill(root, "z-other")+ client = _client([[1.0, 0.0]] * 3)+ catalog = tmp_path / "catalog.json"+ _catalog(root, catalog, client)++ manifest = select_decoys(target, catalog_path=catalog, catalog_root=root, count=1, client=client)++ assert manifest["selected"][0]["path"] == "z-other"+++def test_loader_rejects_a_hand_edited_nested_target_selection(selection: SimpleNamespace, tmp_path: Path) -> None:+ manifest = _select(selection, count=1)+ nested = _skill(selection.target, "companions/rollback-helper")+ manifest["catalog_root"] = "."+ manifest["selected"] = [_selected_record(nested, selection.target.parent)]+ path = tmp_path / "nested.json"+ write_decoy_manifest(manifest, path)++ with pytest.raises(ValueError, match="nested inside the target"):+ load_decoy_manifest(selection.target, path)+++def test_portable_manifest_uses_the_evaluated_checkout(tmp_path: Path) -> None:+ original = tmp_path / "checkout-a"+ root = original / "skills"+ target = _skill(root, "target")+ neighbor = _skill(root, "neighbor")+ client = _client([[1.0, 0.0]] * 2)+ catalog = original / "catalog.json"+ _catalog(root, catalog, client)+ manifest = select_decoys(target, catalog_path=catalog, catalog_root=root, count=1, client=client)+ assert manifest["catalog_root"] == "."+ saved = target / "evals" / "decoys.json"+ write_decoy_manifest(manifest, saved)+ copied = tmp_path / "checkout-b"+ shutil.copytree(original, copied)+ copied_target = copied / "skills" / "target"+ copied_neighbor = copied / "skills" / "neighbor"+ copied_manifest = copied_target / "evals" / "decoys.json"+ client.reset_mock()++ # The original still exists, but this checkout must read its own sources.+ assert load_decoy_manifest(copied_target, copied_manifest)[0] == [copied_neighbor]+ original_text = (neighbor / "SKILL.md").read_text(encoding="utf-8")+ (copied_neighbor / "SKILL.md").write_text(original_text + "\nChanged only in checkout B.\n", encoding="utf-8")+ with pytest.raises(ValueError, match="Selected decoy source changed"):+ load_decoy_manifest(copied_target, copied_manifest)+ (copied_neighbor / "SKILL.md").write_text(original_text, encoding="utf-8")+ shutil.rmtree(original)++ assert load_decoy_manifest(copied_target, copied_manifest)[0] == [copied_neighbor]+ client.embed.assert_not_called()+ client.embed_single.assert_not_called()+++def test_collection_root_can_be_relative_to_a_nested_targets_parent(tmp_path: Path) -> None:+ root = tmp_path / "collection-a"+ target = _skill(root, "category/target")+ _skill(root, "neighbor")+ client = _client([[1.0, 0.0]] * 2)+ catalog = tmp_path / "catalog.json"+ _catalog(root, catalog, client)+ manifest = select_decoys(target, catalog_path=catalog, catalog_root=root, count=1, client=client)+ assert manifest["catalog_root"] == ".."+ write_decoy_manifest(manifest, target / "evals" / "decoys.json")+ relocated = tmp_path / "collection-b"+ shutil.copytree(root, relocated)+ shutil.rmtree(root)++ assert load_decoy_manifest(+ relocated / "category" / "target", relocated / "category" / "target" / "evals" / "decoys.json"+ )[0] == [relocated / "neighbor"]+++def _case_insensitive(path: Path) -> bool:+ probe = path / "CaseProbe"+ probe.mkdir()+ try:+ return (path / "caseprobe").exists()+ finally:+ probe.rmdir()+++ ("root_spelling", "target_spelling", "target_name", "expected"),+ [+ ("Skills", "skills/target", "target", "."),+ ("skills", "Skills/target", "target", "."),+ ("Skills", "skills/category/target", "category/target", ".."),+ ],+)+def test_case_variant_spellings_keep_a_portable_root(+ tmp_path: Path, root_spelling: str, target_spelling: str, target_name: str, expected: str+) -> None:+ if not _case_insensitive(tmp_path):+ pytest.skip("requires a case-insensitive filesystem")+ original = tmp_path / "checkout-a"+ root = original / "skills"+ _skill(root, target_name)+ _skill(root, "neighbor")+ client = _client([[1.0, 0.0]] * 2)+ catalog = original / "catalog.json"+ _catalog(root, catalog, client)+ target = original.joinpath(*target_spelling.split("/"))+ manifest = select_decoys(+ target, catalog_path=catalog, catalog_root=original / root_spelling, count=1, client=client+ )+ assert manifest["catalog_root"] == expected+ write_decoy_manifest(manifest, target / "evals" / "decoys.json")+ copied = tmp_path / "checkout-b"+ shutil.copytree(original, copied)+ shutil.rmtree(original)+ copied_target = copied.joinpath(*target_spelling.split("/"))++ # The manifest no longer names checkout-a, so it loads from the copy alone.+ loaded = load_decoy_manifest(copied_target, copied_target / "evals" / "decoys.json")[0]+ assert len(loaded) == 1+ assert loaded[0].samefile(copied / "skills" / "neighbor")+++def test_catalog_root_spellings_are_matched_by_file_identity(tmp_path: Path) -> None:+ # A linked spelling takes the same identity match as a case variant on a+ # case-insensitive filesystem, so this also runs on case-sensitive CI.+ root = tmp_path / "skills"+ target = _skill(root, "category/target")+ alias = tmp_path / "skills-alias"+ try:+ alias.symlink_to(root, target_is_directory=True)+ except OSError:+ pytest.skip("symlinks are not available")++ assert _catalog_root_record(alias, root / "target") == "."+ assert _catalog_root_record(alias, target) == ".."+ assert _catalog_root_record(alias / "category", root / "target") == "category"+ assert _catalog_root_record(tmp_path / "elsewhere", root / "target") == str(tmp_path / "elsewhere")+++def test_unrelated_external_collection_keeps_an_absolute_root(tmp_path: Path) -> None:+ target = _skill(tmp_path / "targets", "target")+ root = tmp_path / "external-collection"+ neighbor = _skill(root, "neighbor")+ client = _client([[1.0, 0.0]])+ catalog = tmp_path / "catalog.json"+ _catalog(root, catalog, client)+ manifest = select_decoys(target, catalog_path=catalog, catalog_root=root, count=1, client=client)+ assert manifest["catalog_root"] == str(root)+ saved = target / "evals" / "decoys.json"+ write_decoy_manifest(manifest, saved)++ assert load_decoy_manifest(target, saved)[0] == [neighbor]+++def test_loader_accepts_an_explicit_absolute_catalog_root(selection: SimpleNamespace, tmp_path: Path) -> None:+ manifest = _select(selection)+ manifest["catalog_root"] = str(selection.root)+ path = tmp_path / "absolute.json"+ write_decoy_manifest(manifest, path)++ assert load_decoy_manifest(selection.target, path)[0] == selection.skills[:2]++[email protected]("root_value", ["linked", "linked/../catalog-skills"])+def test_relative_catalog_root_cannot_hide_a_symlink(+ selection: SimpleNamespace,+ tmp_path: Path,+ root_value: str,+) -> None:+ manifest = _select(selection)+ (tmp_path / "linked").symlink_to(selection.root, target_is_directory=True)+ manifest["catalog_root"] = root_value+ path = tmp_path / "linked-root.json"+ write_decoy_manifest(manifest, path)++ with pytest.raises(ValueError, match="symlink"):+ load_decoy_manifest(selection.target, path)+++def test_round_trip_load_requires_no_catalog_or_model(selection: SimpleNamespace, tmp_path: Path) -> None:+ manifest = _select(selection)+ path = tmp_path / "decoys.json"+ write_decoy_manifest(manifest, path)+ selection.catalog.unlink()+ selection.client.reset_mock()+ paths, loaded = load_decoy_manifest(selection.target, path)+ assert paths == selection.skills[:2]+ assert loaded == manifest+ selection.client.embed_single.assert_not_called()++[email protected]("filename", ["SKILL.md", "scripts/helper.py", "references/guide.md"])+def test_source_changes_invalidate_frozen_selection(+ selection: SimpleNamespace,+ tmp_path: Path,+ filename: str,+) -> None:+ path = tmp_path / "decoys.json"+ write_decoy_manifest(_select(selection), path)+ changed = selection.skills[0] / filename+ changed.parent.mkdir(exist_ok=True)+ with changed.open("a") as stream:+ stream.write("\nchanged\n")+ with pytest.raises(ValueError, match="changed"):+ load_decoy_manifest(selection.target, path)++[email protected]("filename", ["evals.json", "config.yml", "decoys.json"])+def test_evaluator_only_changes_preserve_frozen_selection(+ selection: SimpleNamespace,+ tmp_path: Path,+ filename: str,+) -> None:+ path = tmp_path / "decoys.json"+ write_decoy_manifest(_select(selection), path)+ changed = selection.skills[0] / "evals" / filename+ changed.parent.mkdir()+ changed.write_text("changed evaluator input\n", encoding="utf-8")++ assert load_decoy_manifest(selection.target, path)[0] == selection.skills[:2]+++def test_target_instruction_changes_invalidate_selection(selection: SimpleNamespace, tmp_path: Path) -> None:+ path = tmp_path / "decoys.json"+ write_decoy_manifest(_select(selection), path)+ with (selection.target / "SKILL.md").open("a") as stream:+ stream.write("\nNew instructions.\n")+ with pytest.raises(ValueError, match="target changed"):+ load_decoy_manifest(selection.target, path)+++def test_manifest_can_live_in_target_evals_without_self_invalidating(selection: SimpleNamespace) -> None:+ path = selection.target / "evals" / "decoys.json"+ write_decoy_manifest(_select(selection), path)+ assert load_decoy_manifest(selection.target, path)[0] == selection.skills[:2]+++def test_mutually_selected_skills_keep_valid_manifests_after_evaluator_updates(tmp_path: Path) -> None:+ root = tmp_path / "skills"+ alpha = _skill(root, "alpha")+ beta = _skill(root, "beta")+ gamma = _skill(root, "gamma")+ client = _client([[1.0, 0.0]] * 3)+ catalog = tmp_path / "catalog.json"+ _catalog(root, catalog, client)+ alpha_manifest = alpha / "evals" / "decoys.json"+ beta_manifest = beta / "evals" / "decoys.json"++ def save(target: Path, path: Path) -> None:+ write_decoy_manifest(+ select_decoys(target, catalog_path=catalog, catalog_root=root, count=2, client=client), path+ )++ save(alpha, alpha_manifest)+ save(beta, beta_manifest)+ for target in (alpha, beta):+ (target / "evals" / "config.yml").write_text(+ f"schema_version: 1\nskill_workspace:\n mode: group\n decoy_manifest: {target.name}/evals/decoys.json\n",+ encoding="utf-8",+ )+ assert load_decoy_manifest(alpha, alpha_manifest)[0] == [beta, gamma]+ assert load_decoy_manifest(beta, beta_manifest)[0] == [alpha, gamma]+ save(alpha, alpha_manifest)+ assert load_decoy_manifest(alpha, alpha_manifest)[0] == [beta, gamma]+ assert load_decoy_manifest(beta, beta_manifest)[0] == [alpha, gamma]+++def test_old_full_source_digest_requires_regeneration(selection: SimpleNamespace, tmp_path: Path) -> None:+ manifest = _select(selection)+ manifest["source_digest_algorithm"] = "skill-evaluator-source-tree/2"+ path = tmp_path / "old-manifest.json"+ write_decoy_manifest(manifest, path)++ with pytest.raises(ValueError, match="source digest algorithm; regenerate the selection"):+ load_decoy_manifest(selection.target, path)++[email protected]("relative", ["../escape", "/absolute", "a/../api-debugger", "a\\b", "a//b"])+def test_rejects_escaping_or_noncanonical_manifest_paths(+ selection: SimpleNamespace,+ tmp_path: Path,+ relative: str,+) -> None:+ manifest = _select(selection)+ manifest["selected"][0]["path"] = relative+ path = tmp_path / "decoys.json"+ write_decoy_manifest(manifest, path)+ with pytest.raises(ValueError, match="relative"):+ load_decoy_manifest(selection.target, path)+++ "mutate",+ [+ lambda data: data.update(schema_version=True),+ lambda data: data.update(strategy="unknown"),+ lambda data: data.update(source_digest_algorithm="unknown"),+ lambda data: data.update(unexpected=True),+ lambda data: data.update(count=3),+ lambda data: data["selected"][0].update(score=True),+ lambda data: data["selected"][0].update(score=10**1000),+ lambda data: data["selected"][0].update(source_digest="invalid"),+ lambda data: data["selected"][0].update(name="wrong-name"),+ ],+)+def test_rejects_malformed_manifests(selection: SimpleNamespace, tmp_path: Path, mutate: object) -> None:+ manifest = _select(selection)+ mutate(manifest)+ path = tmp_path / "decoys.json"+ write_decoy_manifest(manifest, path)+ with pytest.raises(ValueError):+ load_decoy_manifest(selection.target, path)+++def test_rejects_duplicate_selection(selection: SimpleNamespace, tmp_path: Path) -> None:+ manifest = _select(selection)+ manifest["selected"][1] = copy.deepcopy(manifest["selected"][0])+ path = tmp_path / "decoys.json"+ write_decoy_manifest(manifest, path)+ with pytest.raises(ValueError, match="duplicate"):+ load_decoy_manifest(selection.target, path)+++def test_rejects_duplicate_json_keys(selection: SimpleNamespace, tmp_path: Path) -> None:+ path = tmp_path / "decoys.json"+ path.write_text('{"schema_version": 1, "schema_version": 1}')+ with pytest.raises(ValueError):+ load_decoy_manifest(selection.target, path)+++def test_rejects_unsafe_decoy_sources(selection: SimpleNamespace, tmp_path: Path) -> None:+ (selection.skills[0] / "linked").symlink_to(tmp_path)+ with pytest.raises(ValueError, match="unsafe or unstable"):+ _select(selection)+++def test_rejects_replaced_skill_directory_symlink(selection: SimpleNamespace, tmp_path: Path) -> None:+ path = tmp_path / "decoys.json"+ write_decoy_manifest(_select(selection), path)+ skill = selection.skills[0]+ moved = tmp_path / "moved"+ skill.rename(moved)+ skill.symlink_to(moved, target_is_directory=True)+ with pytest.raises(ValueError, match="symlink"):+ load_decoy_manifest(selection.target, path)+++def test_writer_does_not_follow_output_symlinks(selection: SimpleNamespace, tmp_path: Path) -> None:+ destination = tmp_path / "existing.json"+ destination.write_text("keep me")+ link = tmp_path / "decoys.json"+ link.symlink_to(destination)+ with pytest.raises(ValueError, match="symlink"):+ write_decoy_manifest(_select(selection), link)+ assert destination.read_text() == "keep me"++[email protected]("relative", ["references/renamed.md", "nested/package/SKILL.md"])+def test_excludes_target_payload_in_other_runtime_files(selection: SimpleNamespace, relative: str) -> None:+ copied = selection.skills[0] / relative+ copied.parent.mkdir(parents=True)+ copied.write_bytes((selection.target / "SKILL.md").read_bytes())+ manifest = _select(selection)+ assert [item["path"] for item in manifest["selected"]] == ["log-triage", "release-planner"]+++def test_loader_rejects_a_renamed_target_alias_with_a_correct_source_digest(+ selection: SimpleNamespace,+ tmp_path: Path,+) -> None:+ manifest = _select(selection, count=1)+ decoy = selection.skills[0]+ target_body = (selection.target / "SKILL.md").read_text(encoding="utf-8").split("---", 2)[2]+ (decoy / "SKILL.md").write_text(+ f"---\nname: {decoy.name}\ndescription: A differently named skill.\n---{target_body}", encoding="utf-8"+ )+ manifest["selected"] = [_selected_record(decoy, selection.root)]+ path = tmp_path / "alias.json"+ write_decoy_manifest(manifest, path)++ with pytest.raises(ValueError, match="target alias or duplicate skill identity"):+ load_decoy_manifest(selection.target, path)+++def test_loader_rejects_target_payload_with_a_correct_source_digest(+ selection: SimpleNamespace,+ tmp_path: Path,+) -> None:+ manifest = _select(selection, count=1)+ decoy = selection.skills[0]+ payload = decoy / "references" / "renamed.md"+ payload.parent.mkdir()+ payload.write_bytes((selection.target / "SKILL.md").read_bytes())+ manifest["selected"] = [_selected_record(decoy, selection.root)]+ path = tmp_path / "payload.json"+ write_decoy_manifest(manifest, path)++ with pytest.raises(ValueError, match="Selected decoy contains target instructions"):+ load_decoy_manifest(selection.target, path)+++def test_rejects_mixed_content_catalog_before_model_calls(selection: SimpleNamespace) -> None:+ raw = json.loads(selection.catalog.read_text())+ rule = copy.deepcopy(raw["entries"][0])+ rule.update(id="rules:api-debugger", content_type="rules")+ raw["entries"].append(rule)+ selection.catalog.write_text(json.dumps(raw))+ with pytest.raises(ValueError, match="skill-only"):+ _select(selection)+ selection.client.embed_single.assert_not_called()diff --git a/tests/tier3/test_workflow.py b/tests/tier3/test_workflow.pyindex e328ff35..e807a7c0 100644--- a/tests/tier3/test_workflow.py+++ b/tests/tier3/test_workflow.py@@ -375,6 +375,43 @@ def test_included_skills_need_group_mode_before_preparation(skill, configured, massert not configured+ ("manifest_state", "workspace_mode", "expected_error"),+ [+ ("missing", "group", "Catalog does not exist:"),+ ("invalid-json", "group", "Invalid decoy manifest JSON:"),+ ("missing", "isolated", "skill_workspace.decoy_manifest requires skill_workspace.mode=group"),+ ],+)+def test_bad_decoy_manifest_fails_before_dataset_preparation(+ skill, configured, monkeypatch, manifest_state, workspace_mode, expected_error+):+ from skillevaluator.tier3 import workflow++ evals = skill / "evals"+ evals.mkdir()+ manifest = evals / "decoys.json"+ if manifest_state == "invalid-json":+ manifest.write_text("{not valid JSON", encoding="utf-8")+ (evals / "config.yml").write_text(+ f"schema_version: 1\nskill_workspace:\n mode: {workspace_mode}\n"+ f" decoy_manifest: {skill.name}/evals/decoys.json\n",+ encoding="utf-8",+ )+ monkeypatch.setattr(+ workflow, "_prepare_dataset", lambda *_args, **_kwargs: pytest.fail("must preflight decoy manifest")+ )++ result = CliRunner().invoke(_command(), [str(skill), "--progress", "off"])++ assert result.exit_code != 0+ assert expected_error in result.output+ if manifest_state == "missing" and workspace_mode == "group":+ assert str(manifest) in result.output+ assert not (evals / "evals.json").exists()+ assert not configured++def test_unavailable_environment_fails_before_generation(skill, configured, monkeypatch):from skillevaluator.tier3.harbor import runner