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
fix(tier3): keep generated and validated eval datasets fair to the no-skill baseline (#456)
Narendran Raghavan81b1e2730537
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c992bcf8..c237d316 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,8 +4,22 @@ All notable changes to SkillEvaluator are documented in this file.## Unreleased+### Fixed++- Tier 3 dataset fairness validation checks the skill's own identities and+ nested judge expectations, recognizes required reads after negated actions,+ and bounds diagnostics and repeated-negation work. Template prompts avoid+ requiring bundled scripts; upgrade guidance explains strict CI preflight+ failures for older datasets that grade skill use.+### Added+- Dataset fairness validation checks the evaluated skill's own names and nested+ graded text, distinguishes negated reads from required reads, and bounds+ warning excerpts and repeated-match scanning. Common Unicode, Markdown and+ script references are checked too; generated prompts avoid skill scripts.+ Older datasets may need outcome-only wording to pass strict CI preflight.+- Classify explicit `SKILL.md` ownership contacts (`metadata.pic` and`metadata.email`) as `PII.ownership_emails`, still HIGH by default. Add`--policy` to `tier1` and `tier1 validate` so operators can permit reviewed@@ -418,10 +432,56 @@ All notable changes to SkillEvaluator are documented in this file.none can make Tier 3 block CI. Standalone validation and benchmarkpublication policies are unchanged.+- Standalone `create-eval-dataset` and `DatasetOptions` now default to `auto`+ grounding: substantive author guidance beyond headings first, then usable+ matching retained trajectories from completed skill-scoped runs. Missing input+ fails before provider access, collection, or writes; existing skill-only scripts must pass+ `--grounding skill`, even with `--no-llm`. Auto trace selection preserves+ authored cases and flags unmatched coverage and observed answers for review;+ retained identity and trace files are checked before reading, and legacy+ `cases` wrappers retain root metadata when converted to `evals`.+ Provenance records the effective grounding and retained source hashes; auto+ trace refinement records template fallback and a safe reason when its LLM+ operation is unavailable or fails, preserving authored expectations and review+ state.+ Auto leaves existing datasets unchanged without `--force` or `--refine`,+ including when matching traces exist; explicit trace grounding still opts into+ in-place refinement. When auto selects traces, answer proposals that describe+ skill use leave the inferred expected outcome empty for independent authoring+ and review;+ existing authored expectations are retained. Recovery guidance and examples name+ usable author inputs, retained-results refinement, and explicit skill-only opt-in. Explicit grounding+ modes remain available. Unattended autopilot keeps its skill-grounded one-case+ starter behavior.+- Give staged Tier 3 main images a fixed liveness healthcheck so Docker Compose2 can wait for readiness while authored image healthchecks remain suppressed.Keep custom service healthchecks and their readiness dependencies intact.+- Generated eval datasets no longer grade skill use. Template cases from+ `create-eval-dataset`, and the one starter case that `validate`, `tier3` and+ `tier3 evaluate --autopilot` write when no dataset exists, asserted that the+ agent read `SKILL.md`, ran the skill's script, or used or identified the+ skill. The no-skill baseline is graded on the same expected output and+ assertions and could not meet them, so its `behavior_check`, `accuracy` and+ `goal_accuracy` scores dropped and lift was inflated. Template cases now+ describe only the task outcome, and do not quote a skill description that+ names the skill or its script; a template prompt calls a `SKILL.md` named in+ the description `my SKILL.md`. The LLM generation and `--refine` prompts ask+ for outcome checks, and template `--refine` no longer turns reads or runs of+ `SKILL.md`, the skill directory or the skill's scripts into behaviors. The+ autopilot starter case leaves out LLM or `EVAL.md` text that grades skill+ use, and `create-eval-dataset` prints a warning for each generated case that+ still grades it. The starter case from `init-custom-grader` and `init-harbor-task`+ asserts the task outcome instead of "using the relevant skill workflow". The+ negative template case is unchanged. `tier3 validate` now warns when a+ prompt points at the skill's files or an expected output or assertion grades+ skill use, including runs of the skill's own scripts. The warning fails+ `--strict` and the strict dataset check that all-tier CI runs before its+ advisory Tier 3 step; it never blocks a local run or autopilot. On newly+ generated datasets, baseline scores rise and lift falls; existing datasets+ are not rewritten.+- Tier 3 tool efficiency counts writing, editing and patching files, scopednative searches and listings (`Grep`, `Glob`, `LS`, OpenCode `list`, Codex`list_dir` and `grep_files`) and MCP tools named `mcp__server__tool` (Claudediff --git a/README.md b/README.mdindex 12644504..60c81379 100644--- a/README.md+++ b/README.md@@ -10,8 +10,8 @@> 📺 **Livestream:** [Ask the Experts: Evaluating Agent Skills](https://www.youtube.com/watch?v=4rI0zATFxYI)-SkillEvaluator is an open-source tool that checks AI agent skills and measures their effect on task results:-start with quality checks, then compare live runs with and without a skill.+SkillEvaluator checks AI agent skills and measures their effect on task results:+start with quality checks, then compare runs with and without a skill.Agent skills are folders of instructions and supporting files defined by the[Agent Skills specification](https://agentskills.io/). SkillEvaluator is part of@@ -20,8 +20,7 @@ the [NVIDIA Verified Skills pipeline](https://github.com/NVIDIA/skills).## Bring skill evaluation to your repositoryCheck changed skills in GitHub or GitLab with quality checks, SkillSpector-security scanning and reports. Choose folders and thresholds; no evaluator code-to import.+security scanning and reports. Choose folders and thresholds.**GitHub guided setup:** run inside your checked-out repository:@@ -47,7 +46,7 @@ See [GitHub](docs/github-actions.mdx) and [GitLab](docs/gitlab-ci.mdx) setup,## Quickstart-Both paths use the bundled `text-analyzer` skill.+Both paths use bundled `text-analyzer`.| Start here | Requires | First result || --- | --- | --- |@@ -62,7 +61,7 @@ git clone --depth 1 https://github.com/NVIDIA/SkillEvaluator.gitcd SkillEvaluator```-uv provisions Python 3.13 and dependencies. Run from this checkout; for a standalone CLI, see+uv provisions Python 3.13 and dependencies. For standalone installation, see[Installation](https://docs.nvidia.com/skills/skillevaluator/installation).### Run without an LLM@@ -110,7 +109,7 @@ The same key supports Tier 2 embeddings and supported Tier 3 agents. See the-Each tier is independent. Add the relevant extra to your checkout command:+Each tier is independent. Add its extra to your command:| Tier | Question | Example after setup | Additional setup || --- | --- | --- | --- |@@ -126,9 +125,9 @@ are missing; Semgrep is optional. See [scanners](docs/installation.mdx#system-tosecurity scanning; [Harbor](https://github.com/harbor-framework/harbor), theopen-source agent evaluation framework, powers sandboxed agent runs.-Tier 2 reports when inter-skill comparison did not run. Tier 3 reuses evaluation-sources or creates one starter case with limited coverage. See the-[tier guides](https://docs.nvidia.com/skills/skillevaluator/) for details.+Tier 2 reports when inter-skill comparison did not run. Tier 3 autopilot reuses+sources or creates one skill-grounded case with limited coverage. See+[tier guides](https://docs.nvidia.com/skills/skillevaluator/).## Run the combined pipeline@@ -144,15 +143,18 @@ autopilot for skills. Use `--tiers 1,2` to skip live evaluation or `--tiers 1` fstatic checks. `--no-autopilot` requires an existing source. Other artifact typesretain their applicable stages.-Tier 1 always gates `validate`. Tier 2 gates unless `--no-block-on-dedup` is set;+Tier 1 gates `validate`. Tier 2 gates unless `--no-block-on-dedup` is set;Tier 3 gates only with `--block-on-agent-eval`. Model and managed-sandbox usagecan incur charges; see [runtime and cost](docs/tier3-live-evaluation.mdx#plan-for-cost).-For broader coverage, generate and review additional cases. Templates omit-negatives unless authored in `EVAL.md`:+Standalone generation needs substantive `evals/EVAL.md` guidance, a `--prompt`+file with task requests and outcomes, or matching retained traces. `--force`+below replaces the autopilot starter; `--refine` refines it. Explicit+`--grounding skill` permits skill-only starters. Review cases; templates omit+unauthored negatives.```bash-uv run --python 3.13 --extra tier3 skillevaluator tier3 create-eval-dataset ./my-skill --full+uv run --python 3.13 --extra tier3 skillevaluator tier3 create-eval-dataset ./my-skill --full --prompt eval-guidance.md --force```## Run from a source checkoutdiff --git a/docs/agent-skill.mdx b/docs/agent-skill.mdxindex dd13078f..18bc447e 100644--- a/docs/agent-skill.mdx+++ b/docs/agent-skill.mdx@@ -116,7 +116,7 @@ skill tells the agent never to print or store them.| "Check my skill before I publish it, no API keys" | `skillevaluator tier1 <skill-dir> --no-llm` | Pass or fail with security, PII, schema, and quality findings || "Score the quality of this SKILL.md" | `skillevaluator quality-check` and `rubric-eval` | Quality score and grade, rubric feedback || "Does it overlap with my other skills?" | `skillevaluator tier2` | Duplicate and similarity findings |-| "Write eval cases for my skill" | `skillevaluator create-eval-dataset --full`, then `tier3 validate --strict` | A reviewed `evals/evals.json` with positive and negative cases |+| "Write eval cases for my skill" | Write task requests and outcomes in `<skill-dir>/evals/EVAL.md`, run `skillevaluator create-eval-dataset <skill-dir> --full --prompt <skill-dir>/evals/EVAL.md`, then `tier3 validate <skill-dir> --strict` | A reviewed `evals/evals.json` with positive and negative cases || "Does my skill actually make the agent better?" | `skillevaluator tier3 evaluate` with and without the skill | Verdict, five dimension scores, and Skill Lift || "Explain this benchmark report" | Reads `result.json`, `tier3-benchmark.md`, `what_to_fix.json` | Plain-language verdict and prioritized fixes || "Gate skills in our CI" | `skillevaluator ci init` | A workflow with the right exit-code gates |@@ -140,6 +140,9 @@ Effectiveness 68.6% 95.3% +26.7This is the SkillEvaluator skill evaluated by SkillEvaluator. Its own eval casesship in [`skills/skillevaluator/evals/`](https://github.com/NVIDIA/SkillEvaluator/tree/main/skills/skillevaluator/evals).+The run above used an earlier version of case 001 that also asserted the agent+read the skill's `SKILL.md`, which the baseline cannot do; that assertion has+since been removed.<Warning>Asking one agent to answer with and without a skill and grade itself is not andiff --git a/docs/cli-reference.mdx b/docs/cli-reference.mdxindex b596d683..f2c6ba5d 100644--- a/docs/cli-reference.mdx+++ b/docs/cli-reference.mdx@@ -8,7 +8,7 @@ layout: reference`skillevaluator --help` output. Re-verify every flag table each release;tests/golden/cli_surface.json also records compatibility aliases hidden in help. */}-This page lists every `skillevaluator` command with its full flag set and exact defaults. If you want task-oriented guidance instead, start from the tier guides: [Tier 1: Validation](tier1-validation.mdx), [Tier 2: Deduplication](tier2-deduplication.mdx), and [Tier 3: Live Evaluation](tier3-live-evaluation.mdx).+This page lists every `skillevaluator` command with its full flag set and exact defaults. If you want task-oriented guidance instead, start from the tier guides: [Tier 1: Validation](/skills/skillevaluator/tier1-validation), [Tier 2: Deduplication](/skills/skillevaluator/tier2-deduplication), and [Tier 3: Live Evaluation](/skills/skillevaluator/tier3-live-evaluation).[Harbor](https://github.com/harbor-framework/harbor) is the open-source agentevaluation framework behind the Tier 3 task, environment, trial, and trajectory@@ -34,7 +34,7 @@ commands referenced below.| [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 || [tier3 interact](#tier3-interact) | Measure departure from additive skill gains | At least two skills, one reviewed evaluation source, Tier 3 runtime and credentials || [tier3 compare-versions](#tier3-compare-versions) | Compare current and prior retained with-skill scores without writes | Two compatible retained runs |-| [create-eval-dataset](#create-eval-dataset) | Generate synthetic eval datasets | LLM provider key (none with `--no-llm`) |+| [create-eval-dataset](#create-eval-dataset) | Generate eval datasets | Substantive author guidance or usable matching retained traces; explicit `--grounding skill` permits skill-only generation. LLM provider key unless `--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 || [view](#view) | Open the latest HTML live-evaluation report | A previous `tier3 evaluate` run |@@ -74,9 +74,9 @@ Direct `tier1 PATH`, `tier1 validate PATH`, and `tier2 PATH` default to| `-r, --report [cli\|json\|html\|markdown\|sarif]` | `cli,json,html` for direct workflows; `cli` for focused commands | Report format(s). Accepts comma- or space-separated values (`-r cli,json,html` or `-r cli json html`) and may be repeated. The compact default view writes html+json unless `-r` is passed explicitly, which is honored exactly (including `cli`). || `-o, --output-dir DIRECTORY` | `reports` | Directory for generated reports. |-In practice: a default `validate` run (no `-r`) shows the compact pipeline view **and** writes `json` + `html` report files; passing `-r` takes over completely — `-r cli` really means terminal output only, no files. The focused expert commands take the `cli` default literally: they print the full terminal report and write files only for the formats you request with `-r`. A `validate` run writes `skillevaluator-output-<timestamp>.json` / `.html` (plus `.md` with `-r markdown` or `.sarif.json` with `-r sarif`); standalone commands write a fixed `skillevaluator-<kind>` basename (for example `skillevaluator-quality.json`), so a re-run overwrites the previous report. Direct workflows write `skillevaluator-tier1` or `skillevaluator-tier2` reports in the selected formats and also overwrite previous files with that basename. Filename conventions and report anatomy live in [Reports & Results](reports.mdx).+In practice: a default `validate` run (no `-r`) shows the compact pipeline view **and** writes `json` + `html` report files; passing `-r` takes over completely — `-r cli` really means terminal output only, no files. The focused expert commands take the `cli` default literally: they print the full terminal report and write files only for the formats you request with `-r`. A `validate` run writes `skillevaluator-output-<timestamp>.json` / `.html` (plus `.md` with `-r markdown` or `.sarif.json` with `-r sarif`); standalone commands write a fixed `skillevaluator-<kind>` basename (for example `skillevaluator-quality.json`), so a re-run overwrites the previous report. Direct workflows write `skillevaluator-tier1` or `skillevaluator-tier2` reports in the selected formats and also overwrite previous files with that basename. Filename conventions and report anatomy live in [Reports & Results](/skills/skillevaluator/reports).-**Exit codes.** Commands communicate through a small exit-code contract — this is what your CI gates on (see [Gate Your CI](ci-integration.mdx)):+**Exit codes.** Commands communicate through a small exit-code contract — this is what your CI gates on (see [Gate Your CI](/skills/skillevaluator/ci-integration)):| Code | Meaning || --- | --- |@@ -125,7 +125,7 @@ its own. Tier 1 always runs and gates the exit code, so `--tiers 2`,| | Direct workflows | `validate PATH --tiers ...` || --- | --- | --- || Tiers run | Only the named tier | Tier 1 plus any selected tiers |-| Tier 1 dependency audit | Included in `tier1 PATH` | Opt-in with `--checks`, which replaces the default list, so name every check you want plus `dependency` ([selection rules](tier1-validation.mdx#narrow-to-specific-checks)) |+| Tier 1 dependency audit | Included in `tier1 PATH` | Opt-in with `--checks`, which replaces the default list, so name every check you want plus `dependency` ([selection rules](/skills/skillevaluator/tier1-validation#narrow-to-specific-checks)) || Tier 1 LLM stages | Rubric, LLM security, and verification run when a provider is configured; `--no-llm` skips them | LLM security analysis runs only with `--llm`, and finding verification only with `--llm-verify`; no rubric stage || Reports | `tier1` and `tier2` default to `-r cli,json,html` and write `skillevaluator-tier1.*` or `skillevaluator-tier2.*` under `-o`. `tier3` writes its run under `--results-dir` and does not accept `-r` or `-o` | The compact view writes HTML and JSON as `skillevaluator-output-<timestamp>.*`; skill targets also get `BENCHMARK.md` || Exit code `1` | `tier1`: a check failed or required evidence is incomplete. `tier2`: HIGH or CRITICAL findings or a blocking analysis error. `tier3`: the run did not complete; a `FAIL` verdict alone exits `0` | Tier 1 failed; Tier 2 findings unless `--no-block-on-dedup`; Tier 3 only with `--block-on-agent-eval` |@@ -150,12 +150,12 @@ errors, such as an option the workflow does not accept, exit `2`.| `--skip CHECKS` | none | Comma-separated checks to leave out, e.g. `secrets` for the Gitleaks scan. Skipped checks are shown and reported as skipped, nothing is installed for them, and the run cannot certify Tier 1 for publication || `--llm / --no-llm` | Enabled when a provider is configured | Enable or skip rubric, LLM security, and finding verification; explicit `--llm` requires valid provider configuration || `--min-score INTEGER` | `70` | Minimum passing quality and rubric score, from 0 to 100; quality severity overrides cannot waive the minimum |-| `--quality-config PATH` | packaged `quality-default.yaml` | YAML file that adjusts the quality check's expected headings and error-handling rules; settings it omits keep their packaged values. See [Tier 1: Validation](tier1-validation.mdx#the-checks). |-| `--pii-waivers PATH` | none | Reviewed, expiring PII waivers applied by the `pii` check. See [PII waivers](tier1-validation.mdx#pii-waivers). |+| `--quality-config PATH` | packaged `quality-default.yaml` | YAML file that adjusts the quality check's expected headings and error-handling rules; settings it omits keep their packaged values. See [Tier 1: Validation](/skills/skillevaluator/tier1-validation#the-checks). |+| `--pii-waivers PATH` | none | Reviewed, expiring PII waivers applied by the `pii` check. See [PII waivers](/skills/skillevaluator/tier1-validation#pii-waivers). || `--profile TEXT` | `SKILLEVALUATOR_PROFILE`, then `default` | Validation policy; `external` is a compatibility alias || `--policy FILE` | none | Explicit policy overlay, including reviewed ownership-contact severity. See [Tier 1 policies](tier1-validation.mdx#validation-profiles-and-policies). || `--previous-version TEXT` | `SKILLEVALUATOR_PREVIOUS_VERSION`, else unset | Previous version for version checks |-| `--skillspector-baseline FILE` | unset | Audited SkillSpector suppression baseline; never discovered from the skill. See [Audited SkillSpector baselines](tier1-validation.mdx#audited-skillspector-baselines). |+| `--skillspector-baseline FILE` | unset | Audited SkillSpector suppression baseline; never discovered from the skill. See [Audited SkillSpector baselines](/skills/skillevaluator/tier1-validation#audited-skillspector-baselines). |Also accepts `-r/--report` and `-o/--output-dir` described above.@@ -195,7 +195,7 @@ pipeline.### tier3 import-tracesImport a production trace export into redacted candidates outside the skill.-See [Trace Datasets](trace-datasets.mdx) for the v1 JSON/JSONL contract and redaction limits.+See [Trace Datasets](/skills/skillevaluator/trace-datasets) for the v1 JSON/JSONL contract and redaction limits.```bashskillevaluator tier3 import-traces ./my-skill ./sessions.jsonl -o ./review@@ -227,7 +227,7 @@ skillevaluator tier3 accept-traces ./my-skill ./review### tier3 validate-Validate the Tier 3 `evals/` directory and the optional Harbor bring-your-own-task contract before you spend money on a live run. The dataset and directory rules it enforces are documented in [Eval Datasets](eval-datasets.mdx).+Validate the Tier 3 `evals/` directory and the optional Harbor bring-your-own-task contract before you spend money on a live run. The dataset and directory rules it enforces are documented in [Eval Datasets](/skills/skillevaluator/eval-datasets). Because the no-skill baseline is graded on the same text, it warns when a case's prompt points at `skills/<name>`, `<name>/SKILL.md` or reading or following `SKILL.md`, or when its expected output or an assertion names those files, calls `<name>` a skill, says the agent used, invoked or identified `<name>`, or runs one of the skill's scripts from `scripts/` or `tools/`. The check is a wording heuristic, and these warnings fail the command only with `--strict`.```bash title="Check evals/ before a live run"skillevaluator tier3 validate ./my-skill --strict@@ -237,7 +237,7 @@ skillevaluator tier3 validate ./my-skill --strict| --- | --- | --- || `--json` | off | Emit JSON output. || `--strict` | off | Treat warnings as failures. |-| `--harbor-contract` | off | Validate the Harbor task and reward contract (see [Custom Graders & Tasks](custom-graders.mdx)). |+| `--harbor-contract` | off | Validate the Harbor task and reward contract (see [Custom Graders & Tasks](/skills/skillevaluator/custom-graders)). |## validate@@ -301,12 +301,12 @@ Static checks; LLM-free by default. Tier 1 gates the exit code and always runs.| `--previous-version VERSION` | `SKILLEVALUATOR_PREVIOUS_VERSION`, else unset | Previous released version; the skill's version must be a strictly greater SemVer. Single-skill targets only. || `--fail-fast` | off | Stop on the first failing check instead of collecting all issues. || `-c, --continue-on-failure` | off | Run the full pipeline without stopping early; record all issues in the reports. Overrides `--fail-fast`, and for folder validation keeps scanning every skill past a CRITICAL finding. |-| `--llm, --tier1-llm / --no-llm, --no-tier1-llm` | `no-llm` | Enable LLM-backed security analysis (requires a configured public provider — see [Providers & Credentials](configuration.mdx)). |+| `--llm, --tier1-llm / --no-llm, --no-tier1-llm` | `no-llm` | Enable LLM-backed security analysis (requires a configured public provider — see [Providers & Credentials](/skills/skillevaluator/configuration)). || `--llm-verify` | off | Run a second LLM pass to suppress false-positive findings. |-| `--skillspector-baseline FILE` | unset | Audited SkillSpector suppression baseline for the `security` check; never discovered from the skill. See [Audited SkillSpector baselines](tier1-validation.mdx#audited-skillspector-baselines). |+| `--skillspector-baseline FILE` | unset | Audited SkillSpector suppression baseline for the `security` check; never discovered from the skill. See [Audited SkillSpector baselines](/skills/skillevaluator/tier1-validation#audited-skillspector-baselines). || `--min-score INTEGER` | `70` | Minimum quality score (0–100) required per skill when the `quality` check runs; policy severity overrides cannot waive this gate. |-| `--quality-config PATH` | packaged `quality-default.yaml` | YAML file that adjusts the quality check's expected headings and error-handling rules; settings it omits keep their packaged values. See [Tier 1: Validation](tier1-validation.mdx#the-checks). |-| `--pii-waivers PATH` | none | Reviewed, expiring PII waivers applied by the `pii` check; forwarded to each skill of a catalog run. See [PII waivers](tier1-validation.mdx#pii-waivers). |+| `--quality-config PATH` | packaged `quality-default.yaml` | YAML file that adjusts the quality check's expected headings and error-handling rules; settings it omits keep their packaged values. See [Tier 1: Validation](/skills/skillevaluator/tier1-validation#the-checks). |+| `--pii-waivers PATH` | none | Reviewed, expiring PII waivers applied by the `pii` check; forwarded to each skill of a catalog run. See [PII waivers](/skills/skillevaluator/tier1-validation#pii-waivers). |### Tier 2 · Deduplication@@ -341,7 +341,7 @@ The following flags are forwarded to the live-eval engine when Tier 3 is enabled| `--max-judge-calls INTEGER` | unset | Maximum recorded non-salvage judge attempts; excludes transport retries and RAGAS-internal requests. || `--max-attempts-total INTEGER` | unset | Maximum logical Harbor attempts admitted across agents and arms, including private comparison arms. || `--max-cost-usd FLOAT` | unset | Maximum agent model spend; requires a price book and excludes judge spend, setup, and container time. |-| `--price-file FILE` | unset | JSON price book keyed by exact resolved model identifier; see [cost limits](tier3-live-evaluation.mdx#cost-limits). |+| `--price-file FILE` | unset | JSON price book keyed by exact resolved model identifier; see [cost limits](/skills/skillevaluator/tier3-live-evaluation#cost-limits). || `--stop-on-pass / --no-stop-on-pass` | unset | Stop a case's remaining attempts once one passes. || `--model TEXT` | unset | Global agent model override. || `--agent-model TEXT` | unset | Per-agent model override, `AGENT=MODEL` (repeatable). |@@ -354,7 +354,7 @@ The following flags are forwarded to the live-eval engine when Tier 3 is enabled| `--agent-runtime-preflight / --no-agent-runtime-preflight` | disabled | Opt into an extra agent-only execution of the first staged task before the measured A/B matrix. The CLI value overrides `harbor.agent_runtime_preflight`; without either, no extra agent runs. || `--tolerate-baseline-timeouts / --no-tolerate-baseline-timeouts` | disabled | Keep an agent scored on its clean with-skill arm when only baseline attempts hit the agent execution timeout; its baseline and Skill Lift are not reported, and the run is not complete publication evidence. The CLI value overrides `harbor.tolerate_baseline_timeouts`. See [Baseline timeouts](/skills/skillevaluator/tier3-live-evaluation#baseline-timeouts). |-Flags marked "unset" fall back to their matching keys in `evals/config.yml` where one exists, then to the built-in defaults ([Eval Datasets](eval-datasets.mdx) documents the config keys and precedence). The exception is `--results-dir`, which resolves independently of `evals/config.yml` (see [Reports & Results](reports.mdx)).+Flags marked "unset" fall back to their matching keys in `evals/config.yml` where one exists, then to the built-in defaults ([Eval Datasets](/skills/skillevaluator/eval-datasets) documents the config keys and precedence). The exception is `--results-dir`, which resolves independently of `evals/config.yml` (see [Reports & Results](/skills/skillevaluator/reports)).### Evaluated source provenance@@ -364,7 +364,7 @@ Flags marked "unset" fall back to their matching keys in `evals/config.yml` wher| `--evaluated-source-revision TEXT` | unset | Immutable revision of the evaluated source: a full Git object id, or a `sha256`/`sha384`/`sha512` digest. A short prefix is refused. || `--evaluator-container-revision TEXT` | unset | Digest-pinned evaluator image reference recorded beside the evaluated source. |-The identity is recorded on `BENCHMARK.md`, forwarded to every child of a parallel catalog run so each card names the same source tree, and persisted into a Tier 3 run's `run_config.json` (see [Reports & Results](reports.mdx)).+The identity is recorded on `BENCHMARK.md`, forwarded to every child of a parallel catalog run so each card names the same source tree, and persisted into a Tier 3 run's `run_config.json` (see [Reports & Results](/skills/skillevaluator/reports)).## quality-check@@ -382,7 +382,7 @@ skillevaluator quality-check ./my-skillPlus the standard report options. A collection's displayed average does notreplace the minimum required of each skill. Scoring weights, grade bands, theindependent minimum-score gate, and the `--quality-config` file format are-documented in [Tier 1: Validation](tier1-validation.mdx).+documented in [Tier 1: Validation](/skills/skillevaluator/tier1-validation).## rubric-eval@@ -410,7 +410,7 @@ skillevaluator security-scan ./my-skill| --- | --- | --- || `--llm / --no-llm` | `no-llm` | Enable LLM security analysis. || `--llm-verify` | off | Use LLM verification to reduce false positives. |-| `--skillspector-baseline FILE` | unset | Audited SkillSpector suppression baseline; never discovered from the skill. See [Audited SkillSpector baselines](tier1-validation.mdx#audited-skillspector-baselines). |+| `--skillspector-baseline FILE` | unset | Audited SkillSpector suppression baseline; never discovered from the skill. See [Audited SkillSpector baselines](/skills/skillevaluator/tier1-validation#audited-skillspector-baselines). |Plus the standard report options.@@ -425,7 +425,7 @@ skillevaluator pii-scan ./my-skill| Flag | Default | Effect || --- | --- | --- || `--llm-verify` | off | Use LLM verification to reduce false positives. |-| `--pii-waivers PATH` | none | Apply reviewed, expiring PII waivers from this YAML file. See [PII waivers](tier1-validation.mdx#pii-waivers). |+| `--pii-waivers PATH` | none | Apply reviewed, expiring PII waivers from this YAML file. See [PII waivers](/skills/skillevaluator/tier1-validation#pii-waivers). |Plus the standard report options.@@ -439,7 +439,7 @@ skillevaluator lint-scripts ./my-skill## context-optimization-check-Detect redundant content within one skill (intra-skill deduplication). Needs an embeddings-capable provider plus a chat LLM for the verification stage — see [Tier 2: Deduplication](tier2-deduplication.mdx).+Detect redundant content within one skill (intra-skill deduplication). Needs an embeddings-capable provider plus a chat LLM for the verification stage — see [Tier 2: Deduplication](/skills/skillevaluator/tier2-deduplication).```bash title="Intra-skill redundancy check"skillevaluator context-optimization-check ./my-skill@@ -480,7 +480,7 @@ skillevaluator similarity-check ./skills| `--max-entries INTEGER` | `1024` | Maximum selected manifests for a fresh collection; range `1`–`5000`. Does not restrict loaded catalog queries. || `--max-scalar-comparisons INTEGER` | `128000000` | Maximum comparisons multiplied by embedding dimensions; must be positive. Applies to pairwise scans and catalog queries. |-Plus the standard report options. Classification tiers and catalog rules are in [Tier 2: Deduplication](tier2-deduplication.mdx).+Plus the standard report options. Classification tiers and catalog rules are in [Tier 2: Deduplication](/skills/skillevaluator/tier2-deduplication).For older scripts, the hidden deprecated aliases `--cache` and `--save-cache`still map to `--catalog` and `--save-catalog`, respectively. Use the catalog@@ -523,7 +523,7 @@ cannot overwrite evaluation inputs or an existing non-manifest file. Set`evals/config.yml` to consume it. The manifest path is relative to the targetskill's parent directory. Evaluation validates and reuses the selectionwithout contacting the embedding provider. See-[Select a reproducible decoy set](agents-and-sandboxes.mdx#select-a-reproducible-decoy-set)+[Select a reproducible decoy set](/skills/skillevaluator/agents-and-sandboxes#select-a-reproducible-decoy-set)for a complete example and the limits of similarity-based selection.## tier3 interact@@ -577,7 +577,7 @@ Unavailable comparisons print reasons and exit nonzero.## tier3 evaluate-Run 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).+Run 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](/skills/skillevaluator/tier3-live-evaluation).```bash title="Live evaluation with codex in Docker"skillevaluator tier3 evaluate ./my-skill --agents codex --env-mode docker@@ -589,9 +589,9 @@ Use `skillevaluator tier3 PATH` for the complete workflow with automatic missing| Flag | Default | Effect || --- | --- | --- |-| `-a, --agents TEXT` | provider-native | Comma-separated Harbor agents. Defaults: NVIDIA Build=`opencode`, OpenAI=`codex`, Anthropic=`claude-code`. Supported: `claude-code`, `codex`, `opencode`; Experimental: `hermes` (Docker with NVIDIA Build only; see [Experimental Hermes](agents-and-sandboxes.mdx#experimental-hermes)). The alias `claude` is accepted for `claude-code`. See [Agents & Sandboxes](agents-and-sandboxes.mdx). |-| `--env-mode` | `docker` | Where trials run. SkillEvaluator exposes 27 environment modes: 26 Harbor-native modes — `docker`, `daytona`, `e2b`, `modal`, `runloop`, `langsmith`, `ec2`, `gke`, `ack`, `openshift`, `novita`, `apple-container`, `singularity`, `islo`, `tensorlake`, `cwsandbox`, `wandb`, `use-computer`, `blaxel`, `beam`, `skypilot`, `hyperbrowser`, `vercel`, `kata`, `runta`, `mosaic` — plus SkillEvaluator `local` mode. `wandb` runs Harbor's `cwsandbox` backend with W&B authentication, so it needs the `harbor[cwsandbox]==0.25.0` extra; Harbor 0.25 has no `wandb` extra. Harbor's `cua-cloud`, `opensandbox`, `hf-sandbox`, `podman`, `prime`, `smol`, `sbx`, `sail`, and `kernel` backends are not selectable. See the complete extras and prerequisites matrix in [Agents & Sandboxes](agents-and-sandboxes.mdx#where-trials-run). Installed packages can add more modes; see [Custom execution backends](agents-and-sandboxes.mdx#custom-execution-backends). |-| `--environment-kwarg`, `--ek` | none | Operator-only `KEY=VALUE` constructor option for Harbor-native non-Docker backends (repeatable). Values accept JSON-compatible types; skill-owned `evals/config.yml` cannot set them. Never pass secrets. Docker and local reject all kwargs, Kata accepts only `kata_runtime` and `kata_dns`, and Harbor runtime-policy fields for overrides, mounts, networks, extra Compose, lifecycle, and pod security are reserved, as are `stream`, `enable_environment_dir_upload`, `auto_mounts`, `auto_mounting`, and `auth`/`forward_compose_env` for `cwsandbox`/`wandb`. Names the selected backend does not accept in Harbor 0.25.0 are rejected. See [Native backend constructor options](agents-and-sandboxes.mdx#native-backend-constructor-options). |+| `-a, --agents TEXT` | provider-native | Comma-separated Harbor agents. Defaults: NVIDIA Build=`opencode`, OpenAI=`codex`, Anthropic=`claude-code`. Supported: `claude-code`, `codex`, `opencode`; Experimental: `hermes` (Docker with NVIDIA Build only; see [Experimental Hermes](/skills/skillevaluator/agents-and-sandboxes#experimental-hermes)). The alias `claude` is accepted for `claude-code`. See [Agents & Sandboxes](/skills/skillevaluator/agents-and-sandboxes). |+| `--env-mode` | `docker` | Where trials run. SkillEvaluator exposes 27 environment modes: 26 Harbor-native modes — `docker`, `daytona`, `e2b`, `modal`, `runloop`, `langsmith`, `ec2`, `gke`, `ack`, `openshift`, `novita`, `apple-container`, `singularity`, `islo`, `tensorlake`, `cwsandbox`, `wandb`, `use-computer`, `blaxel`, `beam`, `skypilot`, `hyperbrowser`, `vercel`, `kata`, `runta`, `mosaic` — plus SkillEvaluator `local` mode. `wandb` runs Harbor's `cwsandbox` backend with W&B authentication, so it needs the `harbor[cwsandbox]==0.25.0` extra; Harbor 0.25 has no `wandb` extra. Harbor's `cua-cloud`, `opensandbox`, `hf-sandbox`, `podman`, `prime`, `smol`, `sbx`, `sail`, and `kernel` backends are not selectable. See the complete extras and prerequisites matrix in [Agents & Sandboxes](/skills/skillevaluator/agents-and-sandboxes#where-trials-run). Installed packages can add more modes; see [Custom execution backends](/skills/skillevaluator/agents-and-sandboxes#custom-execution-backends). |+| `--environment-kwarg`, `--ek` | none | Operator-only `KEY=VALUE` constructor option for Harbor-native non-Docker backends (repeatable). Values accept JSON-compatible types; skill-owned `evals/config.yml` cannot set them. Never pass secrets. Docker and local reject all kwargs, Kata accepts only `kata_runtime` and `kata_dns`, and Harbor runtime-policy fields for overrides, mounts, networks, extra Compose, lifecycle, and pod security are reserved, as are `stream`, `enable_environment_dir_upload`, `auto_mounts`, `auto_mounting`, and `auth`/`forward_compose_env` for `cwsandbox`/`wandb`. Names the selected backend does not accept in Harbor 0.25.0 are rejected. See [Native backend constructor options](/skills/skillevaluator/agents-and-sandboxes#native-backend-constructor-options). || `--autopilot` | off | Create one eval case when no dataset/task source exists, then evaluate. The case is LLM-generated with the configured provider, with a deterministic keyless template fallback; an existing source is never overwritten. || `--skip-baseline` | off | Skip the without-skill baseline (no lift analysis, faster). || `--skip-with-skill` | off | Run only the without-skill baseline, for example to calibrate a task set or measure a model change before running the skill. The report is marked baseline-only: the overall score is the baseline score, with-skill and lift are unavailable (shown as `skipped` or N/A, never 0.0), and no skill verdict is given. Mutually exclusive with `--skip-baseline`. Not available on `validate`. |@@ -603,7 +603,7 @@ Use `skillevaluator tier3 PATH` for the complete workflow with automatic missing| `--max-judge-calls INTEGER` | unset | Maximum recorded non-salvage judge attempts; excludes transport retries and RAGAS-internal requests. || `--max-attempts-total INTEGER` | unset | Maximum logical Harbor attempts admitted across agents and arms, including private comparison arms. || `--max-cost-usd FLOAT` | unset | Maximum agent model spend; requires a price book and excludes judge spend, setup, and container time. |-| `--price-file FILE` | unset | JSON price book keyed by exact resolved model identifier; see [cost limits](tier3-live-evaluation.mdx#cost-limits). |+| `--price-file FILE` | unset | JSON price book keyed by exact resolved model identifier; see [cost limits](/skills/skillevaluator/tier3-live-evaluation#cost-limits). || `--stop-on-pass / --no-stop-on-pass` | unset | Stop a case's remaining attempts once one passes. || `--n-concurrent INTEGER` | unset | Concurrent eval cases per agent. || `--max-agents INTEGER` | unset | Maximum agents to run in parallel. |@@ -614,8 +614,8 @@ Use `skillevaluator tier3 PATH` for the complete workflow with automatic missing| `--skill-workspace-mode [isolated\|group]` | unset | `isolated` (built-in default) stages only the target skill in the agent workspace; `group` also stages the skills from `--include-skills` / `skill_workspace.include`. || `--include-skills PATH` | none | Additional skill(s) to mount into the eval environment (repeatable; paths must exist). Requires group workspace mode (`--skill-workspace-mode group` or `skill_workspace.mode: group` in `evals/config.yml`). || `--copy-repo` | off | Copy the surrounding repo into the eval environment. |-| `--grading-mode [default\|default_plus_custom\|custom_only]` | unset | Reward/grading mode — see [Custom Graders & Tasks](custom-graders.mdx). The legacy aliases `aces_default` (→ `default`) and `aces_plus_custom` (→ `default_plus_custom`) are still accepted. |-| `--results-dir DIRECTORY` | unset | Directory for live-eval results (precedence rules in [Reports & Results](reports.mdx)). |+| `--grading-mode [default\|default_plus_custom\|custom_only]` | unset | Reward/grading mode — see [Custom Graders & Tasks](/skills/skillevaluator/custom-graders). The legacy aliases `aces_default` (→ `default`) and `aces_plus_custom` (→ `default_plus_custom`) are still accepted. |+| `--results-dir DIRECTORY` | unset | Directory for live-eval results (precedence rules in [Reports & Results](/skills/skillevaluator/reports)). || `--harbor-keep-jobs` | off | Retain Harbor job dirs and artifacts for inspection with [harbor-view](#harbor-view). || `--verbose` | off | Also print the per-evaluator and per-dimension tables and the metric findings after the case summary. || `--agent-runtime-preflight / --no-agent-runtime-preflight` | disabled | Opt into an extra agent-only execution of the first staged task before the full A/B evaluation matrix. |@@ -654,20 +654,33 @@ skillevaluator tier3 migrate-dataset ./my-skill/evals/evals.json --skill-name my| `--output DESTINATION` | preview only | Write a new `.json`, `.yaml`, or `.yml` file; existing paths and the source are refused. |`SOURCE` accepts JSON, case-per-line JSONL, YAML, or YML. JSONL is input-only;-output is one JSON/YAML object. See [Migrate a legacy dataset](eval-datasets.mdx#migrate-a-legacy-dataset)+output is one JSON/YAML object. See [Migrate a legacy dataset](/skills/skillevaluator/eval-datasets#migrate-a-legacy-dataset)for routing-label requirements, preserved fields, and how to promote the reviewedconversion without changing fixture paths.## create-eval-dataset-Create synthetic eval datasets for agent skill evaluation, written to `evals/evals.json`. Uses the configured LLM provider unless you pass `--no-llm`. Dataset anatomy and the four case buckets are documented in [Eval Datasets](eval-datasets.mdx).+Create eval datasets in `evals/evals.json`. The default `auto` grounding prefers+substantive author guidance with content beyond headings, then usable matching+retained traces from a completed run scoped to the skill. If neither exists,+generation fails before provider access, collection, or writes. Write task+requests and observable outcomes in `evals/EVAL.md` or a `--prompt` file, or+explicitly choose `--grounding skill` for the previous skill-only workflow.+Uses the configured LLM provider unless you pass `--no-llm`. See+[Eval Datasets](/skills/skillevaluator/eval-datasets#choose-a-grounding-source)+for source selection and migration details.-```bash title="Generate the full dataset"-skillevaluator create-eval-dataset ./my-skill --full+```bash title="Generate after authoring ./my-skill/evals/EVAL.md"+skillevaluator create-eval-dataset ./my-skill --full --prompt ./my-skill/evals/EVAL.md```<Warning>-`--force` overwrites an existing `evals/evals.json`, including any hand-edited cases. `--refine` normally regenerates the dataset, but `--grounding trace` refines an existing file in place and preserves its authored cases. Use `--dry-run` first if you are unsure.+Auto leaves an existing `evals/evals.json` unchanged unless you pass `--force`+or `--refine`, even when matching traces exist. `--force` can overwrite hand-edited+cases. `--refine` regenerates intent- or skill-grounded datasets; auto trace+refinement preserves authored cases and IDs. Explicit `--grounding trace`+continues to opt into in-place refinement without either flag. Preview with+`--dry-run` before replacing a dataset, including an autopilot starter.</Warning>| Flag | Default | Effect |@@ -677,14 +690,14 @@ skillevaluator create-eval-dataset ./my-skill --full| `--dry-run` | off | Preview without writing. || `--force` | off | Overwrite existing `evals/evals.json`. || `--prompt PATH` | none | Developer eval-guidance file for generation (default: auto-detects `evals/EVAL.md`). |-| `--grounding {skill,intent,trace}` | `skill` | Choose `SKILL.md`, author guidance (`evals/EVAL.md` or `--prompt`), or agent trajectories as the primary grounding source. |-| `--refine` | off | Refine generated cases with trajectories on top of the selected grounding source. Without `--grounding trace`, it regenerates the dataset; with trace grounding and an existing dataset, it refines those cases in place. If no trajectory exists, collection runs `claude-code` through Harbor and needs the `tier3` extra, Docker, and a configured provider (see [Eval Datasets](eval-datasets.mdx)). |-| `--from-results PATH` | none | With `--grounding trace` or `--refine`: results path containing agent trajectories (default: latest results). |-| `--results-dir DIRECTORY` | unset | With `--grounding trace` or `--refine`: external results root to search for trajectories. |+| `--grounding {auto,skill,intent,trace}` | `auto` | Prefer author guidance with content beyond headings, then usable matching retained skill-scoped traces. Explicit `skill` permits skill-only generation; `intent` requires guidance; `trace` may collect trajectories when none exists. |+| `--refine` | off | Refine generated cases with trajectories on top of the selected grounding source. With effective intent or skill grounding it regenerates the dataset; with trace grounding and an existing dataset, it refines those cases in place. Auto requires this flag or `--force` to modify an existing dataset; explicit `--grounding trace` already opts into refinement. Auto selection must find guidance or matching retained traces first; `--refine` does not collect evidence to bypass missing input. After selection, if no trajectory exists, collection runs `claude-code` through Harbor and needs the `tier3` extra, Docker, and a configured provider (see [Eval Datasets](/skills/skillevaluator/eval-datasets)). |+| `--from-results PATH` | none | With `auto`, `trace`, or `--refine`: results path containing agent trajectories (default: latest results). Auto requires a completed run scoped to the skill. |+| `--results-dir DIRECTORY` | unset | With `auto`, `trace`, or `--refine`: external results root to search for trajectories under the skill's directory. |## init-custom-grader-Create a bring-your-own-grader (BYOG) starter under `evals/`. The grader contract it scaffolds is documented in [Custom Graders & Tasks](custom-graders.mdx).+Create a bring-your-own-grader (BYOG) starter under `evals/`. The grader contract it scaffolds is documented in [Custom Graders & Tasks](/skills/skillevaluator/custom-graders).```bash title="Scaffold a Python grader"skillevaluator init-custom-grader ./my-skill@@ -699,7 +712,7 @@ skillevaluator init-custom-grader ./my-skill## init-harbor-task-Create a bring-your-own-task (BYOT) Harbor starter template under `evals/harbor/`. See [Custom Graders & Tasks](custom-graders.mdx) for how case IDs map to eval entries.+Create a bring-your-own-task (BYOT) Harbor starter template under `evals/harbor/`. See [Custom Graders & Tasks](/skills/skillevaluator/custom-graders) for how case IDs map to eval entries.```bash title="Scaffold a Harbor task"skillevaluator init-harbor-task ./my-skill@@ -723,7 +736,7 @@ skillevaluator view ./my-skill| Flag | Default | Effect || --- | --- | --- |-| `--results-dir DIRECTORY` | unset | Results directory to read from (default resolution in [Reports & Results](reports.mdx)). |+| `--results-dir DIRECTORY` | unset | Results directory to read from (default resolution in [Reports & Results](/skills/skillevaluator/reports)). |## tier3 history@@ -748,7 +761,7 @@ Skill revisions alone do not break baseline compatibility.| `--output FILE` | none | Write exactly this `.json`, `.csv`, or `.md` export. The file must be outside all candidate results roots; no directories are created. Stdout still follows `--json`. |The command reads summaries only: no agents, provider credentials, or raw-trajectories are needed. See [Lift history and retention](reports.mdx#lift-history-and-retention).+trajectories are needed. See [Lift history and retention](/skills/skillevaluator/reports#lift-history-and-retention).## compare@@ -765,7 +778,7 @@ skillevaluator compare ./my-skill## tier3 validate-graderQualify the shipped Tier 3 verifier against independently labelled evidence.-See [Grader Validation](grader-validation.mdx) for the versioned suite format,+See [Grader Validation](/skills/skillevaluator/grader-validation) for the versioned suite format,denominators, provenance and interpretation.```bash@@ -831,7 +844,7 @@ during an answer discards that question and returns to the prompt.The chat uses the provider and model configured for LLM checks(`SKILL_EVAL_LLM_PROVIDER` and `SKILL_EVAL_LLM_MODEL`; see [Environment-Variables](environment-variables.mdx)). Each question sends the run's compact+Variables](/skills/skillevaluator/environment-variables)). Each question sends the run's compactevidence to that provider. The evidence names the run by its ID instead of itslocal path. In every text field, such as errors, warnings, case questions andsaved feedback, an absolute path that ends in the run's directory is replaced@@ -881,7 +894,7 @@ one of them failed.## dashboardOpen the optional local tables dashboard. Install the-[`dashboard` extra](installation.mdx#choosing-extras) first, then pass JSON+[`dashboard` extra](/skills/skillevaluator/installation#choosing-extras) first, then pass JSONreports, retained run directories, or directories containing reports. With nopaths, upload JSON files in the browser.@@ -896,7 +909,7 @@ skillevaluator dashboard --no-browser --port 8502| `--no-browser` | off | Start the server without opening a browser. |The server listens on `127.0.0.1`; Ctrl+C stops it. See the-[dashboard guide](performance-dashboard.mdx) for measurements and+[dashboard guide](/skills/skillevaluator/performance-dashboard) for measurements andcomparison eligibility.## harbor-view@@ -909,7 +922,7 @@ skillevaluator harbor-view ./path/to/jobs-dir## doctor-Check live-evaluation runtime readiness: the CLI install, the configured provider, the requested agents and their credentials, and the selected backend. Run it before your first `tier3 evaluate` — see [Agents & Sandboxes](agents-and-sandboxes.mdx) for what each check means.+Check live-evaluation runtime readiness: the CLI install, the configured provider, the requested agents and their credentials, and the selected backend. Run it before your first `tier3 evaluate` — see [Agents & Sandboxes](/skills/skillevaluator/agents-and-sandboxes) for what each check means.```bash title="Deep readiness check"skillevaluator doctor --env-mode docker@@ -962,7 +975,7 @@ skillevaluator health-check --tier 1 # CI preflight for the Tier 1 scanners## models-List models visible through the selected provider's catalog. It uses the same provider and credential resolution as evaluation (see [Providers & Credentials](configuration.mdx)), so it checks catalog reachability and model membership. NVIDIA Build and some compatible gateways expose public catalogs, so a listed model does **not** prove that the inference key works or that the model is compatible with the evaluation harness. `doctor --verify-models` reports such successful but non-authoritative checks as warnings. Top-level only; there is no tier-prefixed twin.+List models visible through the selected provider's catalog. It uses the same provider and credential resolution as evaluation (see [Providers & Credentials](/skills/skillevaluator/configuration)), so it checks catalog reachability and model membership. NVIDIA Build and some compatible gateways expose public catalogs, so a listed model does **not** prove that the inference key works or that the model is compatible with the evaluation harness. `doctor --verify-models` reports such successful but non-authoritative checks as warnings. Top-level only; there is no tier-prefixed twin.```bash title="List the provider's models"skillevaluator models --limit 20@@ -975,6 +988,6 @@ skillevaluator models --limit 20## See also-- [Environment Variables](environment-variables.mdx) — every `SKILL_EVAL_*` and `SKILLEVALUATOR_*` variable-- [Gate Your CI](ci-integration.mdx) — exit codes and JSON reports as a merge gate-- [Providers & Credentials](configuration.mdx) — which commands need which key+- [Environment Variables](/skills/skillevaluator/environment-variables) — every `SKILL_EVAL_*` and `SKILLEVALUATOR_*` variable+- [Gate Your CI](/skills/skillevaluator/ci-integration) — exit codes and JSON reports as a merge gate+- [Providers & Credentials](/skills/skillevaluator/configuration) — which commands need which keydiff --git a/docs/configuration.mdx b/docs/configuration.mdxindex 0e80a553..2b65cad4 100644--- a/docs/configuration.mdx+++ b/docs/configuration.mdx@@ -35,7 +35,7 @@ Anthropic and Bedrock need a separate embedding provider for Tier 2; customOpenAI-compatible endpoints require an explicit URL and key, with optional model overrides.Those advanced setups are covered below.-For the exhaustive variable-by-variable inventory, see [Environment Variables](environment-variables.mdx).+For the exhaustive variable-by-variable inventory, see [Environment Variables](/skills/skillevaluator/environment-variables).Tier 3 executes trials through[Harbor](https://github.com/harbor-framework/harbor), the open-source agent@@ -54,9 +54,15 @@ contact package and vulnerability services.| `quality-check`, `security-scan`, `pii-scan`, `lint-scripts` | `tier1 PATH` automatically enables LLM stages when configured; `validate --llm` / `security-scan --llm` — deeper LLM security analysis || `doctor`, `health-check` (offline readiness probes by default; missing credentials are reported as not ready) | `--llm-verify` on `validate`, `security-scan`, `pii-scan` — LLM false-positive suppression || | All Tier 2 commands — embeddings API; `context-optimization-check` and `dedup-scan` also use a chat LLM (`similarity-check` is embeddings-only). A local OpenAI-compatible server works too — see [Fully local setup](#fully-local-setup) |-| Tier 3 scaffolding and inspection: `create-eval-dataset --no-llm`, `init-custom-grader`, `init-harbor-task`, `tier3 validate`, `view`, `harbor-view`, and `compare` | Tier 3 LLM dataset generation needs a provider key; `tier3 evaluate` needs a provider key plus a credential the selected live agent can use — with NVIDIA Build in `--env-mode docker` or `local`, one `NVIDIA_API_KEY` covers both roles |+| Tier 3 scaffolding and inspection: `create-eval-dataset PATH --no-llm --grounding skill`, `init-custom-grader`, `init-harbor-task`, `tier3 validate`, `view`, `harbor-view`, and `compare` | Tier 3 LLM dataset generation needs a provider key; `tier3 evaluate` needs a provider key plus a credential the selected live agent can use — with NVIDIA Build in `--env-mode docker` or `local`, one `NVIDIA_API_KEY` covers both roles || | `models` and `doctor --verify-models` — provider-catalog reachability and membership checks; public catalogs do not prove that an inference key works. `doctor --tier 2 --verify-models` sends one embedding and one chat request |+Standalone dataset generation defaults to substantive author guidance in+`evals/EVAL.md` or `--prompt`, then usable matching retained traces from a completed+skill-scoped run. Headings alone do not qualify. The table's explicit+`--grounding skill` opts into skill-only templates; see+[Eval Datasets](/skills/skillevaluator/eval-datasets#generate-a-dataset).+`validate PATH` runs all three tiers for skills and needs the provider andTier 3 runtime setup. Use `--tiers 1` for keyless static checks. `--no-dedup`alone skips Tier 2 but still runs Tier 3.@@ -261,7 +267,7 @@ harbor:model: gpt-6.1-sol```-You can also supply that model at invocation time with `--agent-model codex=MODEL`. See [Tier 3: Live Evaluation](tier3-live-evaluation.mdx) for the full run workflow.+You can also supply that model at invocation time with `--agent-model codex=MODEL`. See [Tier 3: Live Evaluation](/skills/skillevaluator/tier3-live-evaluation) for the full run workflow.In Docker mode, credential values are never rendered on the `docker compose exec` command line — the bridge receives them through a mode-0600 file inside the container that is consumed and removed before the agent starts.@@ -315,7 +321,7 @@ The `--llm` security analysis runs [SkillSpector](https://github.com/NVIDIA/SkilThe subprocess environment is isolated. Only the selected provider settings and basic process environment variables (`PATH`, `HOME`, TLS bundles, temp dirs) pass through — other ambient credentials in your shell are never forwarded. Your SkillSpector model settings (`SKILLSPECTOR_MODEL_<SLOT>`, `SKILLSPECTOR_MODEL_REGISTRY`, `SKILLSPECTOR_REASONING_EFFORT`) pass through too; `SKILLSPECTOR_TEMPERATURE` does not.-SkillSpector sends its own structured-output requests, so it has its own default model per provider instead of following the chat default. On Anthropic and Bedrock it stays on Claude Opus 5 while the chat default is Claude Opus 5.5. An explicit `SKILL_EVAL_LLM_MODEL` still reaches SkillSpector, and `SKILLSPECTOR_MODEL` overrides both. SkillSpector v2.13.3 does not return structured output for Claude 5.5 models: if `SKILL_EVAL_LLM_MODEL` names one, also set `SKILLSPECTOR_MODEL` to a supported model such as `claude-opus-5` (Bedrock: `us.anthropic.claude-opus-5`), or the `--llm` security stage is reported incomplete. See [SkillSpector bridge](environment-variables.mdx#skillspector-bridge) for the defaults.+SkillSpector sends its own structured-output requests, so it has its own default model per provider instead of following the chat default. On Anthropic and Bedrock it stays on Claude Opus 5 while the chat default is Claude Opus 5.5. An explicit `SKILL_EVAL_LLM_MODEL` still reaches SkillSpector, and `SKILLSPECTOR_MODEL` overrides both. SkillSpector v2.13.3 does not return structured output for Claude 5.5 models: if `SKILL_EVAL_LLM_MODEL` names one, also set `SKILLSPECTOR_MODEL` to a supported model such as `claude-opus-5` (Bedrock: `us.anthropic.claude-opus-5`), or the `--llm` security stage is reported incomplete. See [SkillSpector bridge](/skills/skillevaluator/environment-variables#skillspector-bridge) for the defaults.Setting `SKILLSPECTOR_PROVIDER` yourself overrides the bridge, but it must name a supported public provider (`openai`, `anthropic`, or `bedrock` — or `nv_build` to force the Build mapping); anything else fails closed and the subprocess receives no credential.diff --git a/docs/eval-datasets.mdx b/docs/eval-datasets.mdxindex 922ca07a..07bab1ab 100644--- a/docs/eval-datasets.mdx+++ b/docs/eval-datasets.mdx@@ -9,7 +9,7 @@ the dataset format `tier3 evaluate` reads, and how to generate and refinecases.You can generate a starter dataset with no API key; LLM-backed generation andrefinement need a configured provider (see-[Providers & Credentials](configuration.mdx)).+[Providers & Credentials](/skills/skillevaluator/configuration)).Tier 3 reports also assess dataset sufficiency under the`dataset-sufficiency-v1` policy: at least 10 distinct cases, at least 1@@ -30,7 +30,7 @@ alternative to the `evals.json` dataset described below.Use `tier3 import-traces` to create a redacted review bundle outside the skill,then `tier3 accept-traces` to promote only explicitly reviewed expectations.Observed production behavior never automatically becomes an expected answer.-See [Trace Datasets](trace-datasets.mdx) for the export contract and review decisions.+See [Trace Datasets](/skills/skillevaluator/trace-datasets) for the export contract and review decisions.## The evals/ directory@@ -65,8 +65,8 @@ Only the dataset is required. Everything else is optional and additive:| `evals/EVAL.md` | Developer guidance that steers dataset generation. | Yes || `evals/files/` | Input fixtures, staged into `/workspace/input/` in the container. | Yes || `evals/environment/` | Custom container environment: Dockerfile, sidecars, MCP servers. | Yes |-| `evals/harbor/` | Bring-your-own-task native Harbor tasks — see [Custom Graders & Tasks](custom-graders.mdx). | Yes |-| `evals/grader.py` or `evals/grader.sh` | Bring-your-own-grader script — see [Custom Graders & Tasks](custom-graders.mdx). | Yes |+| `evals/harbor/` | Bring-your-own-task native Harbor tasks — see [Custom Graders & Tasks](/skills/skillevaluator/custom-graders). | Yes |+| `evals/grader.py` or `evals/grader.sh` | Bring-your-own-grader script — see [Custom Graders & Tasks](/skills/skillevaluator/custom-graders). | Yes || `evals/results/` | Run output, written by `tier3 evaluate`. Never author it by hand. | No — output only |Unrecognized files in `evals/` are ignored, and the validator warns about them@@ -83,17 +83,45 @@ top-level object with `skill_name` and an `evals` array."evals": [{"id": "my-skill-001",- "prompt": "Use my-skill to do the thing",- "expected_output": "Expected outcome description",+ "prompt": "Summarize the failing checks in build.log",+ "expected_output": "The three failing checks, each with its error line","assertions": [- "Read my-skill/SKILL.md",- "Returned correct result"+ "Lists every failing check from build.log",+ "Quotes the error line for each failing check"]}]}```+Both arms get the same `prompt` and are graded on the same `expected_output`+and `assertions`; the no-skill baseline runs without the skill installed. Write+them about the task outcome. A prompt that points at the skill's files, or an+expected output or assertion that the agent read `SKILL.md`, ran the skill's+script, or used the skill, cannot be met by the baseline and inflates lift.+`skill_execution` scores skill use separately (see+[How standard grading judges a trial](/skills/skillevaluator/tier3-live-evaluation#how-standard-grading-judges-a-trial)).+Template cases from `create-eval-dataset` are outcome-only; when the skill's+description mentions `SKILL.md`, the template prompt calls it `my SKILL.md`.+Its LLM prompts ask for outcome checks. It prints a warning for each generated+case that still grades skill use, and the autopilot starter case leaves such+text out. `tier3 validate` warns when a prompt points at `skills/<name>`,+`<name>/SKILL.md`, reading or following `SKILL.md`, the named skill, or one of+its scripts. It also checks strings in nested prompts, expected outputs and+assertions for skill use, using the skill's directory and frontmatter names+as well as the dataset's declared alias. Fields with more than 1,000 values+or cyclic references warn that checking is incomplete. It is a wording heuristic: it skips+immediately negated checks such as "did not read `SKILL.md`", normalizes+compatibility spellings and invisible format characters, and can miss other+wording or lookalike letters from another alphabet. The warnings fail+`tier3 validate --strict` and the strict dataset check that all-tier CI runs+before its advisory Tier 3 step; they never block a local run or autopilot.+When upgrading, review datasets generated by earlier versions: skill-use+expectations now fail CI's strict dataset preflight and leave Tier 3+incomplete until the dataset describes outcomes the baseline can also meet.+Run `skillevaluator tier3 validate PATH --strict` after updating outcomes and+before rerunning CI.+| Field | Required | Meaning || --- | --- | --- || `skill_name` | Yes | Name of the skill under evaluation. |@@ -216,13 +244,27 @@ conversion.## Generate a dataset-`create-eval-dataset` writes `evals/evals.json` for you, grounded in your-`SKILL.md` name, description, body, and script filenames:+`create-eval-dataset` writes `evals/evals.json` using substantive author guidance+first, then usable matching retained agent traces. Guidance needs real content+beyond headings. Write task requests and observable outcomes in `evals/EVAL.md`+(see below), or create a file to pass with `--prompt`:++```bash title="Author guidance and generate the full bucket dataset"+cat > eval-guidance.md <<'EOF'+## Questions+- Summarize the failing checks in build.log.-```bash title="Generate the full bucket dataset"-skillevaluator create-eval-dataset ./my-skill --full+## Behaviors+- Lists every failing check and quotes its error line.+EOF+skillevaluator create-eval-dataset ./my-skill --full --prompt eval-guidance.md```+Auto leaves an existing dataset unchanged unless you explicitly pass `--force`+or `--refine`, even when matching retained traces exist. After an autopilot run,+add `--force` to the command above to replace its starter, or use `--refine` with+matching retained results to refine existing cases.+| Flag | Effect || --- | --- || `--full` | Generate the full bucket set instead of one. LLM mode targets four cases; `--no-llm` template mode emits three cases unless `EVAL.md` includes a negative prompt. |@@ -230,14 +272,17 @@ skillevaluator create-eval-dataset ./my-skill --full| `--dry-run` | Preview without writing. || `--force` | Overwrite existing `evals/evals.json`. || `--prompt PATH` | Use a developer guidance file instead of auto-detected `evals/EVAL.md`. |-| `--refine` | Refine cases using existing or collected trajectories. |-| `--from-results PATH` | With `--refine`: read trajectories from a specific results directory. |-| `--results-dir DIRECTORY` | With `--refine`: external results root to search first. |--Without an LLM provider configured, generation automatically falls back to the-same templates `--no-llm` uses, so the command always succeeds. Exact defaults-for every flag are in the-[CLI Reference](cli-reference.mdx#create-eval-dataset).+| `--grounding auto\|skill\|intent\|trace` | Default `auto`: prefer author intent, then matching retained traces. Skill-only generation requires explicit `skill`. |+| `--refine` | Refine cases using existing or collected trajectories after selecting a grounding source. |+| `--from-results PATH` | With `auto`, `trace`, or `--refine`: read trajectories from a specific completed results directory. |+| `--results-dir DIRECTORY` | With `auto`, `trace`, or `--refine`: external results root to search first. |++After grounding selection, an unavailable LLM provider falls back to local+templates. `--no-llm` selects templates directly; it still requires author+guidance, matching retained traces, or explicit `--grounding skill`. Missing+automatic grounding fails before provider access, trajectory collection, or+writing a dataset. Exact defaults are in the+[CLI Reference](/skills/skillevaluator/cli-reference#create-eval-dataset).You don't have to generate a dataset up front at all: `validate PATH`,`tier3 PATH`, or `tier3 evaluate PATH --autopilot` creates exactly@@ -251,30 +296,79 @@ require an existing source instead of generating one.<Warning>`--force` overwrites `evals/evals.json` without a backup. Plain `--refine`- regenerates the dataset. With `--grounding trace`, an existing- `evals/evals.json` is refined in place without `--force`, preserving its- authored cases.+ regenerates the dataset when the effective grounding is `intent` or `skill`.+ With `auto`, modifying an existing dataset requires `--force` or `--refine`.+ When auto selects traces, refinement preserves authored cases and IDs.+ Explicit `--grounding trace` continues to opt into in-place refinement+ without either flag.</Warning>### Choose a grounding source-`create-eval-dataset --grounding skill|intent|trace` selects the primary-source used to generate and refine cases. The default, `skill`, preserves the-existing behavior and grounds cases in `SKILL.md`. `intent` requires author-guidance in `evals/EVAL.md` or a file passed with `--prompt`; that guidance is-the primary source, with `SKILL.md` as context. `trace` refines an existing-`evals/evals.json` in place, preserving its authored cases, or generates cases-first when no file exists. It accepts `--from-results` and `--results-dir`.-The existing `--refine` flag remains available to refine generated cases with-trajectories on top of the selected grounding source.+`--grounding auto` is the standalone command and `DatasetOptions` default:++1. Prefer author guidance with content beyond headings from `--prompt`, then+ `evals/EVAL.md`, with `SKILL.md` as supporting context. The effective grounding is `intent`.+2. Otherwise use meaningful matching agent steps from retained, completed+ results scoped to this skill. Discovery uses `--from-results`, the external+ `--results-dir` / `SKILLEVALUATOR_RESULTS_DIR` root, and the legacy in-skill+ results location. Explicit exports outside those roots must identify the+ skill in `result.json`. Empty traces, media-only placeholders, foreign runs,+ and case IDs with no match do not qualify.+3. If neither source is available, add guidance or matching retained results,+ or explicitly opt in to `--grounding skill`. `--force`, `--no-llm`, and+ `--refine` do not bypass this requirement.++When `auto` selects traces and you pass `--refine` or `--force`, it preserves+existing cases and authored expectations, prompts, fixture/check metadata, and+review history. The prior dataset hash is retained as a provenance input.+Without a dataset, it prepares deterministic template seeds so case IDs can be+matched before any LLM work; `--full` controls that seed set.+The LLM may refine those seeds after selection. Existing cases are retained+regardless of `--full`. Cases without a matching retained trajectory are marked+`needs_review`; observed answers are proposals requiring human review, not+accepted ground truth. When auto selects traces, an answer proposal that describes+skill use leaves its inferred `expected_output` empty and flagged for an independently+authored outcome. Existing authored expectations are preserved. An existing+dataset without `--force` or `--refine` is left unchanged whether or not matching+retained traces exist.++Explicit modes remain available: `intent` requires author guidance; `trace`+refines an existing dataset or generates cases first and may collect a new+trajectory when none exists; `skill` permits generation from `SKILL.md` alone.+The existing `--refine` flag adds trajectory refinement to the selected source.+For `auto --refine`, selection must first find author intent or retained trace+evidence. Once intent is selected, `--refine` may collect trajectories as before.++Newly inferred outcomes are checked across nested values and dictionary keys.+If they describe skill use or are too large to check fully, the outcome is left+empty with a review reason so the author can supply an independent expectation.+Authored outcomes remain intact.++### Compatibility with skill-only generation++Scripts that previously depended on generation with only `SKILL.md` must add+`--grounding skill`, including template-only invocations:++```bash title="Explicit skill-only compatibility mode"+skillevaluator create-eval-dataset ./my-skill --full --no-llm --grounding skill+```++This default change applies to standalone generation and its service API.+Unattended `validate` / `evaluate --autopilot` still generate a skill-grounded+one-case starter when no source exists and never overwrite an existing source.Generated datasets include a `generation` record with the mode, groundingsource, relative input paths and SHA-256 digests, generation time, and reviewstate. The mode is `llm`, `template_requested`, or `template_fallback`. Afterreviewing the generated cases, authors can set`generation.review_state: reviewed`.-Fallback records include a safe reason. Trace-refined datasets keep their-selected grounding and set `refined: true`. Autopilot records `llm` or+Fallback records include a safe reason. Automatic trace refinement records+`template_fallback` when its planned LLM refinement is unavailable or fails,+and `llm` when that refinement succeeds. Retained authored expectations and+review history are preserved in either case. Trace-refined datasets keep their+effective grounding (`intent` or `trace` for automatic selection), rather than+`auto`, and set `refined: true`. Autopilot records `llm` or`template_fallback` with `skill` grounding. Cases whose authored expectations conflict with an observed answer, orwhose authored behavior steps are dropped by the refinement output, include`review.status: needs_review` and reasons. The trace itself does not determine@@ -299,7 +393,8 @@ supported negative heading (see below).### Guide generation with EVAL.mdPlace an `EVAL.md` in `evals/` and the generator picks it up automatically.-Four headings are parsed as structured hints; everything else is general+It must contain substantive guidance; an empty file or headings alone does not+qualify. Four headings are parsed as structured hints; everything else is generalcontext:```markdown title="evals/EVAL.md"@@ -318,18 +413,33 @@ context:Author guidance is the highest-priority input: behaviors you list here arepreserved in the generated cases even when a trial agent skipped them — that-is exactly the regression the eval should catch.+is exactly the regression the eval should catch. They become assertions, so the+no-skill baseline is graded on them too: describe the task outcome, not reading+`SKILL.md` or running the skill's scripts. `create-eval-dataset` keeps such+lines and warns about them; the autopilot starter case leaves them out.### Refine from real runs-`--refine` grounds the dataset in real agent behavior. It looks for existing+To refine an existing dataset from completed matching skill-scoped results:++```bash title="Refine from retained results"+skillevaluator create-eval-dataset ./my-skill --refine --from-results ./saved-run+```++The run must contain usable matching trajectories. Auto still selects author+guidance first if it exists. Explicit `--grounding trace --from-results ./saved-run`+opts into trace refinement directly, preserving the prior implicit-refinement+behavior of that explicit mode.++After selecting author intent or explicitly choosing `--grounding skill`,+`--refine` adds evidence from real agent behavior. It looks for existingtrajectories from a previous evaluation (checking `--from-results` or thelatest resolved results first); if none exist, it runs the `claude-code` agentvia Harbor to collect one, then rewrites `expected_output` and assertions fromwhat the agent actually did:```bash title="Agent-refined generation"-skillevaluator create-eval-dataset ./my-skill --full --refine+skillevaluator create-eval-dataset ./my-skill --full --refine --prompt eval-guidance.md```Collecting a fresh trajectory needs Docker, the `tier3` extra, and a configured@@ -338,7 +448,9 @@ IDs are read from each trial's `reward.json` or Harbor `result.json`, andmultimodal trajectory messages are read as text, with image and audio partsshown as `[image]` and `[audio]` markers. With `--no-llm`, refinement stillworks — it applies template-based updates from the trajectory instead of an LLM-rewrite.+rewrite. Template refinement skips trajectory steps that read `SKILL.md` or the+skill directory or run the skill's scripts, so they never become assertions;+the LLM rewrite is asked not to add them.## Run policy: evals/config.yml@@ -400,10 +512,10 @@ grading:| `harbor.runtime_env` | list or mapping | Non-credential task values passed into the container. Prefer a list of plain names — each expands to `${NAME}` from your shell; a mapping sets explicit templates. Entries that name or reference operator-owned credentials (`OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, `NVIDIA_API_KEY`, base-URL variables, AWS credential variables) fail with a hard error. Alias: `passthrough_env`. || `harbor.pre_agent_setup` | string or list | Shell commands run in the container before the agent starts. This skill-owned code is allowed only for with-skill-only runs (`--skip-baseline`); paired runs reject it so setup cannot distinguish or alter the baseline arm. Alias: `setup_commands`. Both spellings normalize to the same policy. || `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.mode` | `isolated`, `group` | Whether sibling skills are visible — see [Agents & Sandboxes](/skills/skillevaluator/agents-and-sandboxes). || `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`. |+| `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](/skills/skillevaluator/agents-and-sandboxes#select-a-reproducible-decoy-set). |+| `grading.mode` | `default`, `default_plus_custom`, `custom_only` | Grading pipeline — see [Custom Graders & Tasks](/skills/skillevaluator/custom-graders). 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 thisskill-owned file. Operators can pass non-secret kwargs for Harbor-native@@ -417,7 +529,7 @@ reserved.config load instead of silently running with defaults. Use only one of eachalias pair. Agent and provider credentials never go through `runtime_env` —they come only from your host environment; see the two-credential-roles- section in [Providers & Credentials](configuration.mdx).+ section in [Providers & Credentials](/skills/skillevaluator/configuration).</Note>## Fixtures and custom environments@@ -494,7 +606,7 @@ skillevaluator tier3 validate ./my-skill| --- | --- || `--json` | Emit JSON output. || `--strict` | Treat warnings as failures. |-| `--harbor-contract` | Validate the Harbor task and reward contract for BYOT/BYOG setups — see [Custom Graders & Tasks](custom-graders.mdx). |+| `--harbor-contract` | Validate the Harbor task and reward contract for BYOT/BYOG setups — see [Custom Graders & Tasks](/skills/skillevaluator/custom-graders). |Run it in CI or before a long evaluation: it catches an empty dataset, missingrequired fields, duplicate case IDs, and invalid config in seconds.diff --git a/docs/tier3-live-evaluation.mdx b/docs/tier3-live-evaluation.mdxindex 8feeca88..b2b70e12 100644--- a/docs/tier3-live-evaluation.mdx+++ b/docs/tier3-live-evaluation.mdx@@ -158,8 +158,9 @@ available for inspection.## Repeatable activation validationUse the existing dataset generator, runner and trusted trajectory collector to-check activation separately from answer quality. Start with-`skillevaluator create-eval-dataset ./my-skill --full`, review the generated+check activation separately from answer quality. Write task requests and+observable outcomes in `eval-guidance.md`, then run+`skillevaluator create-eval-dataset ./my-skill --full --prompt eval-guidance.md`, review the generatedcases, and retain a versioned dataset with these four buckets:| Bucket | Authored expectation | What to check |@@ -399,8 +400,9 @@ unchanged; invalid sources produce an error rather than being replaced.A generated one-case starter is a starting point, not a representativeevaluation. Generation prints its concrete coverage gaps to stderr, such asthe absence of a negative/non-trigger case or missing expected outcomes and-assertions. Replace the starter with a full dataset using-`skillevaluator create-eval-dataset ./my-skill --full --force`. `--force`+assertions. Write task requests and observable outcomes in `eval-guidance.md`+before replacing the starter with a full dataset using+`skillevaluator create-eval-dataset ./my-skill --full --force --prompt eval-guidance.md`. `--force`overwrites the starter and discards any edits to it. Then inspect the countsand gaps with `skillevaluator tier3 validate ./my-skill`. Larger case countsdo not by themselves establish representative coverage. Native Harbor task@@ -442,8 +444,14 @@ both in depth.### Generate an eval dataset+Write task requests and observable outcomes in `eval-guidance.md` first; headings+alone do not qualify. If you already ran autopilot, add `--force` to replace its+starter, or `--refine --from-results ./saved-run` to refine from matching retained+results. Auto leaves existing datasets unchanged without either overwrite flag.+See [Grounding sources](/skills/skillevaluator/eval-datasets#choose-a-grounding-source).+```bash title="Write the four-bucket dataset to evals/evals.json"-skillevaluator create-eval-dataset ./my-skill --full+skillevaluator create-eval-dataset ./my-skill --full --prompt eval-guidance.md````--full` with an LLM provider generates all four buckets (explicit, implicit,@@ -1863,8 +1871,12 @@ machine-readable JSON contract, and how to judge whether a given lift is good.`skillevaluator doctor` with the same agent and environment.</Accordion><Accordion title="No eval dataset or native task source found">- Run `skillevaluator create-eval-dataset ./my-skill`, or add an accepted- dataset file under `evals/`. See [Eval Datasets](eval-datasets.mdx).+ Write task requests and observable outcomes in `eval-guidance.md`, then run+ `skillevaluator create-eval-dataset ./my-skill --prompt eval-guidance.md`.+ For explicit skill-only generation, use+ `skillevaluator create-eval-dataset ./my-skill --grounding skill`, or author an+ accepted dataset file under `evals/`. See+ [Eval Datasets](/skills/skillevaluator/eval-datasets).</Accordion><Accordion title="Agent model is rejected">Supply a model valid for that agent with `--agent-model AGENT=MODEL`. Thediff --git a/examples/starter/evals.json b/examples/starter/evals.jsonindex 98e6f20e..70fd4ae4 100644--- a/examples/starter/evals.json+++ b/examples/starter/evals.json@@ -8,7 +8,7 @@"expected_skill": "text-analyzer","expected_script": "analyze_text.py","assertions": [- "The agent reads text-analyzer/SKILL.md and runs scripts/analyze_text.py with --file and --json.",+ "The agent reports the word, line, character and sentence counts and the most frequent word for input.txt.","The returned statistics match the input fixture, including its final newline."]}diff --git a/skills/skillevaluator/SKILL.md b/skills/skillevaluator/SKILL.mdindex db7926c2..5d6c5412 100644--- a/skills/skillevaluator/SKILL.md+++ b/skills/skillevaluator/SKILL.md@@ -94,8 +94,13 @@ Full flag tables: [Tier 1](references/commands-tier1.md),CRITICAL and HIGH findings before anything else; `lint` findings are advisory.4. **Add LLM checks** when a provider is set: `skillevaluator tier1 <skill-dir>`(rubric, LLM security, verification) and `skillevaluator tier2 <skill-dir>`.-5. **Prepare Tier 3 cases.** If `<skill-dir>/evals/evals.json` is missing, generate one with- `skillevaluator create-eval-dataset <skill-dir> --full`, then review it:+5. **Prepare Tier 3 cases.** If `<skill-dir>/evals/evals.json` is missing, first+ capture task requests and observable outcomes in `<skill-dir>/evals/EVAL.md`;+ headings alone do not qualify. Generate with+ `skillevaluator create-eval-dataset <skill-dir> --full --prompt <skill-dir>/evals/EVAL.md`,+ then review it. The default prefers author guidance, then matching retained+ traces; existing datasets need `--force` or `--refine`. Skill-only+ generation requires explicit opt-in with `--grounding skill`. Review:positive cases (explicit, implicit, contextual) and at least one negativecase with `"expected_skill": null`. Required shape: top-level `skill_name`and an `evals` array; each case has `id`, `prompt`, `expected_output`, anddiff --git a/skills/skillevaluator/evals/evals.json b/skills/skillevaluator/evals/evals.jsonindex 3dd69e4c..2b41b7a6 100644--- a/skills/skillevaluator/evals/evals.json+++ b/skills/skillevaluator/evals/evals.json@@ -3,10 +3,9 @@"evals": [{"id": "skillevaluator-001-explicit-keyless",- "prompt": "Use the skillevaluator skill: I have a skill at ./skills/pdf-tools and no LLM API key. Give me the exact SkillEvaluator commands to check that it is well-formed, safe, and see its quality score, and tell me what exit code 1 versus 2 would mean.",+ "prompt": "Use SkillEvaluator: I have a skill at ./skills/pdf-tools and no LLM API key. Give me the exact commands to check that it is well-formed, safe, and see its quality score, and tell me what exit code 1 versus 2 would mean.","expected_output": "Recommends keyless commands such as `skillevaluator tier1 ./skills/pdf-tools --no-llm` and/or `skillevaluator quality-check ./skills/pdf-tools` (or `validate --tiers 1`), and explains exit 1 = a gate failed or evidence incomplete, exit 2 = usage error such as a bad flag or missing path.","assertions": [- "Read the skillevaluator SKILL.md","Recommends a keyless Tier 1 command (tier1 --no-llm, quality-check, or validate --tiers 1) on ./skills/pdf-tools","Explains exit code 1 as a failed check or incomplete evidence and exit code 2 as a usage error","Does not ask for or invent an API key"@@ -41,7 +40,7 @@{"id": "skillevaluator-004-implicit-report","prompt": "My skill benchmark report says 'INCONCLUSIVE: skill never activated' and the Tier 3 command exited 0. Another run says verdict FAIL but also exited 0. What do these mean and what should I change?",- "expected_output": "Explains that no positive with-skill trial loaded the skill, so the description or prompts should be fixed rather than the scores; explains that tier3 exits 0 on a FAIL verdict and only an incomplete run exits 1, with --block-on-agent-eval in validate to gate on Tier 3.",+ "expected_output": "Explains the INCONCLUSIVE verdict as missing positive-trial activation, so the description or prompts should be fixed rather than the scores; explains that tier3 exits 0 on a FAIL verdict and only an incomplete run exits 1, with --block-on-agent-eval in validate to gate on Tier 3.","assertions": ["Explains never activated means the skill was not loaded in positive trials","Recommends improving the skill description or eval prompts",diff --git a/skills/skillevaluator/references/commands-tier2-tier3.md b/skills/skillevaluator/references/commands-tier2-tier3.mdindex 4d3b456c..afd216c0 100644--- a/skills/skillevaluator/references/commands-tier2-tier3.md+++ b/skills/skillevaluator/references/commands-tier2-tier3.md@@ -15,7 +15,7 @@| --- | --- || `tier3 evaluate PATH` | Live A/B run; add `--autopilot` to generate a missing case || `tier3 validate PATH` | Check `<skill-dir>/evals/` (`--strict`, `--json`, `--harbor-contract`) |-| `create-eval-dataset PATH` | Write `<skill-dir>/evals/evals.json` (`--full`, `--no-llm`, `--dry-run`, `--force`, `--prompt`, `--refine`) |+| `create-eval-dataset PATH` | Write `<skill-dir>/evals/evals.json` (`--grounding auto` requires substantive author guidance or usable matching retained traces; existing datasets need `--force` or `--refine`; opt in to `--grounding skill` for skill-only generation; `--full`, `--no-llm`, `--dry-run`, `--force`, `--prompt`, `--refine`) || `init-custom-grader PATH` | BYOG starter (`--mode`, `--language`) || `init-harbor-task PATH` | BYOT starter (`--case-id`, `--with-config`) || `tier3 select-decoys PATH` | Save neighbor skills for group workspaces |diff --git a/skills/skillevaluator/references/tier3-datasets.md b/skills/skillevaluator/references/tier3-datasets.mdindex 65c3f77c..03c2e882 100644--- a/skills/skillevaluator/references/tier3-datasets.md+++ b/skills/skillevaluator/references/tier3-datasets.md@@ -25,7 +25,7 @@ Tier 3 runs a real agent on each case with the skill installed and without it (b"id": "my-skill-001","prompt": "Convert report.docx in /workspace/input to PDF","expected_output": "A PDF of the document saved next to the input",- "assertions": ["Read my-skill/SKILL.md", "Ran scripts/convert.py"],+ "assertions": ["Saves report.pdf next to report.docx", "Keeps the document's headings in the PDF"],"expected_skill": "my-skill","files": ["files/case-001"]},@@ -49,4 +49,44 @@ whole `<skill-dir>/evals/files/` is staged). The legacy flat array with `questioGood datasets cover four buckets: explicit (names the skill), implicit(describes the task), contextual (task inside a project), negative (shouldnot trigger). Write `expected_output` as an observable outcome and one-behavior per assertion.+behavior per assertion. The baseline is graded on the same prompt,+`expected_output` and assertions without the skill, so keep them about the task+outcome: never point the prompt at the skill's files or assert that the agent+read `SKILL.md`, ran the skill's scripts or used the skill (`skill_execution`+scores that). `tier3 validate` warns about common wordings of these; it is a+heuristic, so review the cases too.++## Guided generation++Standalone `create-eval-dataset` defaults to `--grounding auto`: prefer author+guidance in `--prompt` / `<skill-dir>/evals/EVAL.md` with real content beyond+headings, then usable matching retained trajectories from this skill's completed+runs. Write task requests and observable outcomes in the guidance file first:++```bash+skillevaluator create-eval-dataset <skill-dir> --full --prompt <skill-dir>/evals/EVAL.md+```++If neither guidance nor matching retained traces exists, generation fails before+provider access or writes. `--refine` and `--no-llm` do not bypass that preflight.+For the prior skill-only starter workflow, explicitly opt in:++```bash+skillevaluator create-eval-dataset <skill-dir> --full --no-llm --grounding skill+```++Auto leaves an existing dataset unchanged unless you pass `--force` or+`--refine`, even when matching traces exist. To refine from completed results:++```bash+skillevaluator create-eval-dataset <skill-dir> --refine --from-results <run-dir>+```++Auto trace refinement preserves existing authored case IDs and expectations;+unmatched cases and observed answer proposals need review. When auto selects+traces, proposals that describe skill use leave `expected_output` empty for an+independent authored outcome. Existing authored expectations are preserved. Explicit+`--grounding trace` still opts into in-place refinement without `--refine`.+Generation provenance records the effective `intent` or `trace` grounding and input hashes. Explicit+`intent`, `trace`, and `skill` modes remain available. Unattended autopilot retains+its existing skill-grounded one-case starter contract.diff --git a/skills/skillevaluator/references/tier3-running.md b/skills/skillevaluator/references/tier3-running.mdindex 933defd1..3c6801b6 100644--- a/skills/skillevaluator/references/tier3-running.md+++ b/skills/skillevaluator/references/tier3-running.md@@ -26,9 +26,14 @@ Unknown keys fail the load. CLI flags override config values.## Run sequence+Write task requests and observable outcomes in `<skill-dir>/evals/EVAL.md`+before generation; a file containing only headings does not qualify. For an+existing dataset, use `--refine` with matching retained results to refine it,+or `--force` to replace it after reviewing a `--dry-run` preview.+```bashskillevaluator doctor --env-mode docker --verify-models-skillevaluator create-eval-dataset <skill-dir> --full+skillevaluator create-eval-dataset <skill-dir> --full --prompt <skill-dir>/evals/EVAL.mdskillevaluator tier3 validate <skill-dir> --strictskillevaluator tier3 evaluate <skill-dir> -a opencode --max-cases 1 # smokeskillevaluator tier3 evaluate <skill-dir> -a opencode --n-attempts 3diff --git a/src/skillevaluator/cli.py b/src/skillevaluator/cli.pyindex 5b106720..cdd615a4 100644--- a/src/skillevaluator/cli.py+++ b/src/skillevaluator/cli.py@@ -3686,9 +3686,26 @@ def evaluate(@click.option("--no-llm", is_flag=True, help="Use local templates only.")@click.option("--dry-run", is_flag=True, help="Preview without writing.")@click.option("--force", is_flag=True, help="Overwrite existing evals/evals.json.")[email protected]("--prompt", type=click.Path(exists=True, path_type=Path), default=None)[email protected]("--grounding", type=click.Choice(["skill", "intent", "trace"]), default="skill")[email protected]("--refine", is_flag=True, help="Refine cases using existing or collected trajectories.")+ "--prompt",+ type=click.Path(exists=True, path_type=Path),+ default=None,+ help="Author guidance with content beyond headings (default: evals/EVAL.md).",+)+ "--grounding",+ type=click.Choice(["auto", "skill", "intent", "trace"]),+ default="auto",+ show_default=True,+ help="Auto requires substantive author guidance or usable matching retained traces; "+ "existing datasets need --force or --refine. Explicit trace opts into refinement; "+ "use skill for skill-only starters.",+)+ "--refine",+ is_flag=True,+ help="Opt into refinement using retained or collected trajectories after grounding selection.",+)@click.option("--from-results", type=click.Path(exists=True, path_type=Path), default=None)@click.option("--results-dir", type=click.Path(file_okay=False, dir_okay=True, path_type=Path), default=None)def create_dataset(@@ -3703,7 +3720,7 @@ def create_dataset(from_results: Path | None,results_dir: Path | None,) -> None:- """Create synthetic eval datasets for agent skill evaluation."""+ """Create eval datasets from author guidance, retained traces, or explicit skill grounding."""from skillevaluator.evaluation import DatasetGenerationError, DatasetOptions, EvaluationServicetry:diff --git a/src/skillevaluator/evaluation/options.py b/src/skillevaluator/evaluation/options.pyindex f0f4423c..e152380b 100644--- a/src/skillevaluator/evaluation/options.py+++ b/src/skillevaluator/evaluation/options.py@@ -84,7 +84,7 @@ class DatasetOptions:dry_run: bool = Falseforce: bool = Falseprompt: Path | None = None- grounding: str = "skill"+ grounding: str = "auto"refine: bool = Falsefrom_results: Path | None = Noneresults_dir: Path | None = Nonediff --git a/src/skillevaluator/tier3/commands.py b/src/skillevaluator/tier3/commands.pyindex d82d5113..189a9def 100644--- a/src/skillevaluator/tier3/commands.py+++ b/src/skillevaluator/tier3/commands.py@@ -107,7 +107,9 @@ def _starter_evals_entry(skill_path: Path, case_id: str) -> dict[str, Any]:"expected_output": "Replace this with the expected outcome.","expected_skill": skill_path.name,"assertions": [- "The agent addresses the task using the relevant skill workflow.",+ # The no-skill baseline is graded on the same assertions, so grade the+ # outcome, not skill use (skill_execution scores that).+ "The agent's final response completes the task in the prompt.",],}@@ -432,7 +434,7 @@ def create_dataset(dry_run: bool = False,force: bool = False,prompt: Path | None = None,- grounding: str = "skill",+ grounding: str = "auto",refine: bool = False,from_results: Path | None = None,results_dir: Path | None = None,@@ -451,7 +453,7 @@ def create_dataset(argv.append("--force")if prompt:argv.extend(["--prompt", str(prompt.resolve())])- if grounding != "skill":+ if grounding != "auto":argv.extend(["--grounding", grounding])if refine:argv.append("--refine")diff --git a/src/skillevaluator/tier3/dataset_coverage.py b/src/skillevaluator/tier3/dataset_coverage.pyindex 91d8e7c6..535b7162 100644--- a/src/skillevaluator/tier3/dataset_coverage.py+++ b/src/skillevaluator/tier3/dataset_coverage.py@@ -93,6 +93,7 @@ def starter_guidance(skill_path: Path) -> str | None:path = shlex.quote(str(skill_path))return (result["message"] + "\n"+ "Add author guidance in evals/EVAL.md or pass --prompt before replacing the starter.\n"f"Replace the starter with a full dataset using: skillevaluator create-eval-dataset {path} --full --force\n""`--force` overwrites the starter and discards any edits to it.\n"f"Inspect coverage with: skillevaluator tier3 validate {path}"diff --git a/src/skillevaluator/tier3/evals_spec.py b/src/skillevaluator/tier3/evals_spec.pyindex e856e376..c7e5ac90 100644--- a/src/skillevaluator/tier3/evals_spec.py+++ b/src/skillevaluator/tier3/evals_spec.py@@ -14,12 +14,20 @@ Every file and directory that the SkillEvaluator toolchain recognises inside a sfrom __future__ import annotations+import functoolsimport logging+import re+import unicodedata+from collections.abc import Iterator, Mapping, Sequencefrom dataclasses import dataclass, fieldfrom enum import Enum+from itertools import chainfrom pathlib import Path+from typing import Any+from skillevaluator.constants import EXECUTABLE_SKILL_DIRSfrom skillevaluator.tier3.case_ids import validate_case_ids+from skillevaluator.utils.redaction import redact_printable_textlogger = logging.getLogger(__name__)@@ -75,6 +83,11 @@ EVALS_SPEC: list[EntrySpec] = ["Legacy entries must have at least: id, question.","Legacy recommended fields: expected_skill, ground_truth, expected_behavior.","Use acceptable_skills (or legacy alias acceptable_alternates) when a closely related skill should receive partial routing credit.",+ "Write prompts as a user would ask, and expected output and assertions about the task outcome. "+ "The no-skill baseline is graded on the same prompt, expected output and assertions without the "+ "skill installed, so a prompt that points at the skill's files, or an assertion that the agent read "+ "SKILL.md or used the skill, cannot be met by the baseline. Whether the skill was used is scored "+ "separately (skill_execution); `skillevaluator tier3 validate` warns about such entries.",],example="""\{@@ -82,11 +95,11 @@ EVALS_SPEC: list[EntrySpec] = ["evals": [{"id": "my-skill-001",- "prompt": "Use my-skill to do the thing",- "expected_output": "Expected outcome description",+ "prompt": "Summarize the failing checks in build.log",+ "expected_output": "The three failing checks, each with its error line","assertions": [- "Read my-skill/SKILL.md",- "Returned correct result"+ "Lists every failing check from build.log",+ "Quotes the error line for each failing check"]}]@@ -418,7 +431,7 @@ def validate_tier3_source(skill_path: Path) -> tuple[str, list[CheckResult]]:)]results = [CheckResult(str(evals_file.relative_to(skill_path)), "ok", "Tier 3 eval dataset found.")]- _validate_dataset_contents(evals_file, results)+ _validate_dataset_contents(evals_file, results, skill_path=skill_path)return source, resultsif source == "native_harbor":@@ -588,7 +601,10 @@ def _check_dataset(skill_path: Path, results: list[CheckResult]) -> bool:CheckResult("evals/","missing",- "No evals/ directory found. Create one with: skillevaluator create-eval-dataset <path>",+ "No evals/ directory found. Add task guidance in evals/EVAL.md or pass --prompt, or retain "+ "matching Tier 3 traces, then run skillevaluator create-eval-dataset <path>. "+ "For an explicitly skill-derived starter, run "+ "skillevaluator create-eval-dataset <path> --grounding skill.",))return False@@ -603,7 +619,7 @@ def _check_dataset(skill_path: Path, results: list[CheckResult]) -> bool:f"Dataset found ({candidate.stat().st_size} bytes).",))- _validate_dataset_contents(candidate, results)+ _validate_dataset_contents(candidate, results, skill_path=skill_path)return Trueresults.append(@@ -612,13 +628,420 @@ def _check_dataset(skill_path: Path, results: list[CheckResult]) -> bool:"error","REQUIRED dataset file missing. Accepted names: "+ ", ".join(f"evals{e}" for e in DATASET_EXTENSIONS)- + ". Generate with: skillevaluator create-eval-dataset <path>",+ + ". Add task guidance in evals/EVAL.md or pass --prompt, or retain matching Tier 3 traces "+ "before running skillevaluator create-eval-dataset <path>. For an explicitly skill-derived starter, "+ "run skillevaluator create-eval-dataset <path> --grounding skill.",))return False-def _validate_dataset_contents(path: Path, results: list[CheckResult]) -> None:+# Reading a SKILL.md that names no other location ("read SKILL.md", "reads the+# skill's SKILL.md") means the skill's own instructions. A SKILL.md the task is+# about, such as one the agent writes or one in the user's project, is not.+# "Followed the SKILL.md workflow" counts; "follows the SKILL.md format" names+# the file format (see below), and "the following SKILL.md" is the task's file.+_READ_VERB_RE = (+ r"(?:read|reads|reading|load|loads|loaded|loading|open|opens|opened|consult(?:s|ed)?"+ r"|cat|(?<!the\s)follow(?:s|ed|ing)?)"+)+_SKILL_MD_QUALIFIER_RE = r"(?:the|its|this|that|own|skill['\u2019]s)"+# Nouns after SKILL.md that make it the file format or other skills' files+# ("SKILL.md files", "the SKILL.md frontmatter format", "following SKILL.md best+# practices"), not this skill's instructions. Skills that write skills use this+# wording in ordinary prompts. One modifier may come between; a connective may+# not ("read SKILL.md and files in references/" still reads the skill's own+# SKILL.md).+_SKILL_MD_GENERIC_NOUN_RE = (+ r"(?:(?!(?:and|or|then|but|before|after|to|for|with)\b)[\w-]+\s+)?"+ r"(?:files|format|conventions|spec|specification|standard|template|schema"+ r"|guidelines|practices|structure|rules|requirements|layout)\b"+)+_SKILL_USE_VERB_RE = (+ r"(?:use|used|uses|using|invok(?:e|ed|es|ing)|activat(?:e|ed|es|ing)|load(?:s|ed|ing)?"+ r"|identif(?:y|ied|ies|ying))"+)+# What may follow "used <name>" when the name stands for the skill: the end of+# the clause or a connective. CLI arguments ("using glab mr list") or a noun+# ("the input PDF") mean the CLI or file the skill is named after.+_SKILL_NAME_END_RE = r"(?=\s*(?:$|[.,;:!?)]|(?:and|to|for|before|after|then|first)\b))"+# Verbs and interpreters before a script name that mean the script was run.+# "called" is not one: "a file called review.py" names the file.+_RUN_VERB_RE = (+ r"(?:ran|run|runs|running|execut(?:e|ed|es|ing)|invok(?:e|ed|es|ing)|call(?:s|ing)?"+ r"|python3?|bash|sh|node)"+)+# "Used review.py" means it ran only when the name ends the clause or CLI+# arguments follow ("used review.py to check", "using review.py --all"). "Uses+# main.py's parser" or "uses utils.py helpers" names a file, maybe the user's.+_SCRIPT_USE_VERB_RE = r"us(?:e|ed|es|ing)"+_SCRIPT_ARGS_RE = r"(?=\s+(?:-{1,2}\w|[\w.~-]*/|[\w~-]+\.[a-z]\w*\b))"+# Script file types listed from the skill's scripts/ and tools/ directories.+_SKILL_SCRIPT_SUFFIXES = frozenset({".py", ".sh", ".bash", ".js", ".mjs", ".cjs", ".ts", ".rb", ".pl", ".ps1"})+# Negation must immediately precede the verb, with at most one adverb.+# Clause events are consumed once, so "not ... without first reading" can be+# recognized as requiring a read without rescanning every growing prefix.+_CLAUSE_STATE_RE = re.compile(+ r"(?P<break>[.,;:!?\n]|\b(?:and|but|then)\b)"+ r"|(?P<cancel>\b(?:before|until|till|while|after|yet|unless|prior\s+to|ahead\s+of|skip(?:s|ped|ping)?"+ r"|forget(?:s|ting)?|forgot|fail(?:s|ed|ing)?|neglect(?:s|ed|ing)?)\b)"+ r"|(?P<negative>\b(?:no|not|never|without)\b|n['\u2019]t\b)",+ re.IGNORECASE,+)+_NEGATED_PREFIX_RE = re.compile(+ rf"(?P<negative>\b(?:not|never|without)\b|n['\u2019]t\b)\s+"+ rf"(?:(?:\w+ly|ever|even|first|once|also|really)\s+)?"+ rf"(?:(?:{_READ_VERB_RE}|{_SKILL_USE_VERB_RE}|{_RUN_VERB_RE})\s+(?:the\s+)?)?$",+ re.IGNORECASE,+)+_NEGATIVE_SUBJECT_RE = re.compile(+ r"\bno\s+(?:(?!(?:before|until|without|and|or|but|then)\b)[\w-]+\s+){0,3}(?:agents?|trials?)\s+$",+ re.IGNORECASE,+)+_INDIRECT_NEGATED_PREFIX_RE = re.compile(+ r"(?:\b(?:not|never|without)\b|n['\u2019]t\b)\s+"+ r"(?:need\s+to|required\s+to|ask(?:\s+the\s+user)?\s+to|ask\s+questions?\s+or)\s+$",+ re.IGNORECASE,+)+# Dataset aliases are literal data, never regex source. One fixed marker keeps+# compiled patterns independent of the number and size of expected_skill values.+_SKILL_NAME_MARKER = "\x00name\x00"+_MATCH_EXCERPT_CHARS = 80+_MAX_FIELD_VALUES = 1000+_MARKDOWN_LINK_RE = re.compile(r"\[([^\[\]\n]+)\]\([^()\n]*\)")+++def _skill_files_re(skill_name: str | None) -> str:+ """Wording that names the skill's own files: skills/<name>, <name>/SKILL.md, or reading a bare SKILL.md."""+ qualifier = _SKILL_MD_QUALIFIER_RE+ skill_place = "skill"+ alternatives = []+ if skill_name:+ name = re.escape(skill_name)+ qualifier = rf"(?:{_SKILL_MD_QUALIFIER_RE}|{name}(?:['\u2019]s)?)"+ skill_place = rf"(?:skill|{name})"+ alternatives += [rf"\bskills/{name}(?![\w-])", rf"(?<![\w-]){name}/SKILL\.md\b"]+ # "SKILL.md in ./my-skill" names another skill's file; "in the skill+ # directory" or "from the installed skill" is still this skill's own.+ elsewhere = rf"\s+(?:in|of|from|under|inside)\s+(?!(?:the\s+|its\s+|this\s+)?(?:installed\s+|own\s+)?{skill_place}(?![\w-]))"+ alternatives.append(+ rf"\b{_READ_VERB_RE}(?:\s+{qualifier})*\s+(?:(?:the\s+)?contents\s+of\s+)?[`'\"*_\[]*SKILL\.md\b"+ rf"(?![`'\"*_\]]*(?:{elsewhere}|\s+{_SKILL_MD_GENERIC_NOUN_RE}))"+ )+ return "|".join(alternatives)++[email protected]_cache(maxsize=64)+def _prompt_skill_files_re(skill_name: str | None, skill_scripts: tuple[str, ...] = ()) -> re.Pattern[str]:+ """A prompt that points the agent at the skill's own files, which the no-skill baseline is never given."""+ return _skill_use_assertion_re(skill_name or "", skill_scripts, prompt=True)++[email protected]_cache(maxsize=64)+def _skill_use_assertion_re(+ skill_name: str | None, skill_scripts: tuple[str, ...] = (), *, prompt: bool = False+) -> re.Pattern[str]:+ """Graded text about using the skill: its files, its name called a skill, "used <name>", or running its scripts.++ A skill named after the CLI or file format it wraps (glab, kubectl, pdf)+ shares that name with work the baseline can do, so "used <name>" counts only+ when the name ends the clause ("used release-review and found ..."), not+ when CLI arguments or a noun follow it ("listed using glab mr list") or+ "the" comes before it ("loaded the PDF"). "the <name> skill" is still caught.+ A skill script counts when a run verb or interpreter comes before its name+ ("ran review.py", "python3 ./review.py"), when "used" does and the name+ ends the clause or CLI arguments follow it, or when the text names it under+ scripts/ or tools/.+ """+ name = re.escape(skill_name or "")+ alternatives = [+ _skill_files_re(skill_name),+ rf"\b(?:{_SKILL_USE_VERB_RE}|{_READ_VERB_RE})\s+(?:(?:the|this|its|that)(?:\s+installed)?|installed)\s+skill\b"+ rf"(?![\w-]|\.\w|\s+(?:levels?|sets?)\b)",+ ]+ if skill_name:+ alternatives.extend(+ [+ rf"(?<![\w-]){name}(?![\w-])(?:\s+(?:as|is)(?:\s+(?:the|a))?(?:\s+right)?)?"+ rf"\s+skill\b(?![\w-]|\.\w|\s+(?:levels?|sets?)\b)",+ rf"\bskill\s+(?:named\s+|called\s+)?[`'\"]?{name}(?![\w-])",+ ]+ )+ # A template may explicitly route with "Use <name> to ...". Naming it as a+ # skill or pointing at its files/scripts requires the unavailable install.+ if not prompt and skill_name:+ alternatives.append(rf"\b{_SKILL_USE_VERB_RE}\s+[`'\"]?{name}(?![\w-])[`'\"]?{_SKILL_NAME_END_RE}")+ for script in skill_scripts:+ script = _normalized_match_text(script)+ script_name = rf"{re.escape(script)}(?![\w-]|\.\w)"+ script_ref = rf"(?:the\s+)?[`'\"]?(?:[\w.~-]*/)*{script_name}"+ alternatives += [+ rf"(?<![\w.-])(?:scripts|tools)/{script_name}",+ rf"\b{_RUN_VERB_RE}\s+(?:-[\w-]+\s+)*{script_ref}",+ rf"\b{_SCRIPT_USE_VERB_RE}\s+{script_ref}[`'\"]?(?:{_SKILL_NAME_END_RE}|{_SCRIPT_ARGS_RE})",+ ]+ return re.compile("|".join(alternatives), re.IGNORECASE)+++def _first_unnegated_match(pattern: re.Pattern[str], text: str) -> str | None:+ """A bounded excerpt of the first positive requirement, in linear scan order."""+ events = iter(_CLAUSE_STATE_RE.finditer(text))+ event = next(events, None)+ negatives = 0+ for match in pattern.finditer(text):+ while event is not None and event.start() < match.start():+ negatives = negatives + 1 if event.lastgroup == "negative" else 0+ event = next(events, None)+ prefix_start = max(0, match.start() - 256)+ # Report interpretation can describe absent activation: "no positive+ # with-skill trial loaded the skill". Keep this direct subject bounded;+ # "no agent proceeds before reading" still requires a read.+ negative_subject = _NEGATIVE_SUBJECT_RE.search(text, prefix_start, match.start())+ indirect_negative = _INDIRECT_NEGATED_PREFIX_RE.search(text, prefix_start, match.start())+ negated = _NEGATED_PREFIX_RE.search(text, prefix_start, match.start())+ if not (negative_subject or indirect_negative or negated) or negatives % 2 == 0:+ return text[match.start() : min(match.end(), match.start() + _MATCH_EXCERPT_CHARS)]+ return None+++def _normalized_match_text(text: str) -> str:+ """Normalize ordinary Unicode and Markdown spellings, without mapping homoglyphs."""+ text = "".join(char for char in unicodedata.normalize("NFKC", text) if unicodedata.category(char) != "Cf")+ text = _MARKDOWN_LINK_RE.sub(r"\1", text)+ return text.replace("**", "").replace("`", "")+++def _prepared_skill_name(skill_name: str | None) -> tuple[str, str]:+ """Prepare an identity once per case, without retaining contributor aliases globally."""+ name = _normalized_match_text(skill_name or "")+ return name, name.casefold()+++def _mask_skill_name(text: str, name: str, folded_name: str | None = None) -> str:+ """Replace whole literal identities without compiling contributor-controlled regexes."""+ folded_text = text.casefold()+ folded_name = name.casefold() if folded_name is None else folded_name+ offsets = None+ if len(folded_text) != len(text):+ # Casefold can expand a character (ß -> ss); retain original offsets so+ # these aliases work without changing the diagnostic's other spelling.+ offsets = [index for index, char in enumerate(text) for _ in char.casefold()]+ parts = []+ consumed = search_at = 0+ while (found := folded_text.find(folded_name, search_at)) >= 0:+ search_at = found + len(folded_name)+ start = offsets[found] if offsets is not None else found+ end = offsets[search_at - 1] + 1 if offsets is not None else search_at+ before = text[start - 1] if start else ""+ after = text[end : end + 1]+ if (+ (before and (before.isalnum() or before in "_-"))+ or (after and (after.isalnum() or after in "_-"))+ or text[start:end].casefold() != folded_name+ ):+ continue+ parts.extend((text[consumed:start], _SKILL_NAME_MARKER))+ consumed = end+ if not consumed:+ return text+ parts.append(text[consumed:])+ return "".join(parts)+++def _match_skill_text(+ text: str,+ skill_name: str | None,+ skill_scripts: Sequence[str],+ *,+ prompt: bool,+ prepared_name: tuple[str, str] | None = None,+) -> str | None:+ text = _normalized_match_text(text)+ name, folded_name = prepared_name if prepared_name is not None else _prepared_skill_name(skill_name)+ scripts = tuple(skill_scripts)+ generic_pattern = _prompt_skill_files_re(None, scripts) if prompt else _skill_use_assertion_re("", scripts)+ # Check generic wording first: an identity like "skill" or "read" must+ # not mask the noun or verb in "read SKILL.md" and bypass validation.+ matched = _first_unnegated_match(generic_pattern, text)+ if matched is None and name:+ masked = _mask_skill_name(text, name, folded_name)+ if masked is not text:+ pattern = (+ _prompt_skill_files_re(_SKILL_NAME_MARKER, scripts)+ if prompt+ else _skill_use_assertion_re(_SKILL_NAME_MARKER, scripts)+ )+ matched = _first_unnegated_match(pattern, masked)+ if matched is None:+ return None+ # Restore only a bounded name fragment; neither huge aliases nor the+ # internal marker may reach terminal, JSON or CI diagnostics.+ return matched.replace(_SKILL_NAME_MARKER, name[:_MATCH_EXCERPT_CHARS]).split("\x00", 1)[0][:_MATCH_EXCERPT_CHARS]+++def _prompt_skill_files_match(prompt: str, skill_name: str | None, skill_scripts: Sequence[str] = ()) -> str | None:+ """The prompt text that points the agent at the skill's own files, or None."""+ return _match_skill_text(prompt, skill_name, skill_scripts, prompt=True)+++def _skill_use_match(text: str, skill_name: str | None, skill_scripts: Sequence[str] = ()) -> str | None:+ """The expected-output or assertion text that grades skill use, or None."""+ return _match_skill_text(text, skill_name, skill_scripts, prompt=False)+++def _skill_script_names(skill_path: Path) -> tuple[str, ...]:+ """File names of the skill's scripts in scripts/ and tools/, which the no-skill baseline does not have."""+ names: set[str] = set()+ for dirname in EXECUTABLE_SKILL_DIRS:+ directory = skill_path / dirname+ try:+ names.update(+ item.name+ for item in directory.iterdir()+ if item.suffix.lower() in _SKILL_SCRIPT_SUFFIXES and item.is_file()+ )+ except OSError:+ continue+ return tuple(sorted(names))+++def _authored_field(entry: dict[str, Any], runtime_key: str, agentskills_key: str) -> str:+ """The field name the author wrote: the agentskills.io name when the runtime value came from it."""+ if agentskills_key in entry and entry.get(agentskills_key) == entry.get(runtime_key):+ return agentskills_key+ return runtime_key+++def _field_string_leaves(value: Any) -> tuple[list[str], str | None]:+ """Read at most 1000 values without copying huge containers or expanding aliases."""+ pending: list[tuple[Iterator[Any], int | None]] = [(iter((value,)), None)]+ visited: set[int] = set()+ active: set[int] = set()+ leaves: list[str] = []+ values_read = 0+ while pending:+ iterator, identity = pending[-1]+ try:+ item = next(iterator)+ except StopIteration:+ pending.pop()+ if identity is not None:+ active.remove(identity)+ continue+ values_read += 1+ if values_read > _MAX_FIELD_VALUES:+ return leaves, "limit"+ if isinstance(item, str):+ leaves.append(item)+ elif isinstance(item, (Mapping, list, tuple)):+ identity = id(item)+ if identity in active:+ return leaves, "cycle"+ if identity in visited:+ continue+ visited.add(identity)+ active.add(identity)+ children = chain(item, item.values()) if isinstance(item, Mapping) else iter(item)+ pending.append((children, identity))+ return leaves, None+++def _string_leaves(value: Any) -> tuple[list[str], bool]:+ """Strings in a field and whether checking was incomplete (including a cycle)."""+ leaves, reason = _field_string_leaves(value)+ return leaves, reason is not None+++def _quoted(text: str) -> str:+ """A bounded, printable and credential-redacted diagnostic excerpt."""+ return repr(redact_printable_text(" ".join(text.split()), max_len=_MATCH_EXCERPT_CHARS, max_input_chars=320))+++def _baseline_fairness_warnings(+ entry: dict[str, Any], *, skill_scripts: Sequence[str] = (), skill_names: Sequence[str] = ()+) -> list[str]:+ """Explain dataset text the no-skill baseline is graded on but cannot satisfy.++ ``entry`` is a normalized dataset entry; ``skill_scripts`` are the file+ names of the skill's own scripts. This is a wording heuristic, so it can+ miss skill use phrased another way and can flag task text that shares the+ skill's name.+ """+ warnings = []+ prompt = entry.get("question")+ declared_name = entry.get("expected_skill")+ names = tuple(+ dict.fromkeys(name.strip() for name in (*skill_names, declared_name) if isinstance(name, str) and name.strip())+ ) or (None,)+ prepared_names = tuple(_prepared_skill_name(name) for name in names)+ scripts = tuple(skill_scripts)++ def read(field_name: str, value: Any) -> list[tuple[str, str]]:+ leaves, reason = _field_string_leaves(value)+ if reason == "limit":+ warnings.append(+ f"{field_name} has more than {_MAX_FIELD_VALUES} values, so it was not fully checked for skill use. "+ "Keep it to a short string or a list of strings."+ )+ elif reason == "cycle":+ warnings.append(+ f"{field_name} contains a cyclic value, so it was not fully checked for skill use. "+ "Use a finite string or list of strings."+ )+ return [(field_name, leaf) for leaf in leaves]++ for field_name, prompt_text in read(_authored_field(entry, "question", "prompt"), prompt):+ matched = next(+ (+ match+ for name in prepared_names+ if (match := _match_skill_text(prompt_text, None, scripts, prompt=True, prepared_name=name))+ ),+ None,+ )+ if matched:+ warnings.append(+ f"{field_name} points at the skill's files ({_quoted(matched)}). The no-skill "+ "baseline gets the same prompt without the skill, so it cannot follow it. Describe the task instead; "+ "skill_execution measures whether the skill was used."+ )+ break+ texts = read(_authored_field(entry, "ground_truth", "expected_output"), entry.get("ground_truth"))+ texts += read(_authored_field(entry, "expected_behavior", "assertions"), entry.get("expected_behavior"))+ for field_name, text in texts:+ matched = next(+ (+ match+ for name in prepared_names+ if (match := _match_skill_text(text, None, scripts, prompt=False, prepared_name=name))+ ),+ None,+ )+ if matched:+ warnings.append(+ f"{field_name} grades skill use ({_quoted(matched)}), which the no-skill baseline is also graded "+ "on. Keep it about the task outcome; skill_execution scores skill use separately."+ )+ break+ return warnings+++def _skill_identity_names(skill_path: Path) -> tuple[str, ...]:+ """Directory and declared identities, with bounded frontmatter input/parsing."""+ from skillevaluator.plugin_markdown import parse_markdown++ names = [skill_path.name]+ try:+ with (skill_path / "SKILL.md").open(encoding="utf-8") as source:+ name = parse_markdown(source.read(128 * 1024)).name+ if name and name not in names:+ names.append(name)+ except (OSError, UnicodeError):+ pass+ return tuple(names)+++def _validate_dataset_contents(path: Path, results: list[CheckResult], *, skill_path: Path | None = None) -> None:"""Validate the contents of a dataset file."""from .dataset_utils import load_dataset_entries_with_formatfrom .eval_core.declarative_checks import validate_declarative_checks@@ -661,8 +1084,10 @@ def _validate_dataset_contents(path: Path, results: list[CheckResult]) -> None:results.append(CheckResult(str(path.name), "error", str(exc)))case_ids_valid = False- skill_path = path.parent.parent+ skill_path = skill_path or path.parent.parentskill_has_scripts = any((skill_path / "scripts").glob("*.py"))+ skill_scripts = _skill_script_names(skill_path)+ skill_names = _skill_identity_names(skill_path)required_fields_valid = Truefor i, entry in enumerate(entries):@@ -690,6 +1115,8 @@ def _validate_dataset_contents(path: Path, results: list[CheckResult]) -> None:f"Missing recommended fields: {', '.join(sorted(missing_recommended))}",))+ for warning in _baseline_fairness_warnings(entry, skill_scripts=skill_scripts, skill_names=skill_names):+ results.append(CheckResult(f"entry {entry_id}", "warning", warning))if dataset_format == "legacy" and "expected_script" not in entry and skill_has_scripts:results.append(CheckResult(diff --git a/src/skillevaluator/tier3/generate_dataset.py b/src/skillevaluator/tier3/generate_dataset.pyindex 1216aba6..d2b9deb2 100644--- a/src/skillevaluator/tier3/generate_dataset.py+++ b/src/skillevaluator/tier3/generate_dataset.py@@ -10,12 +10,17 @@ warnings.filterwarnings("ignore", category=DeprecationWarning)Generate eval dataset for a skill.Workflows (from simplest to highest quality):- 1. Quick start: skillevaluator create-eval-dataset ./skill (1 case)- 2. Full buckets: skillevaluator create-eval-dataset ./skill --full (up to 4 cases)- 3. Template only: skillevaluator create-eval-dataset ./skill --no-llm (no API key)+ 1. Guided start: skillevaluator create-eval-dataset ./skill --prompt guidance.md+ 2. Full buckets: skillevaluator create-eval-dataset ./skill --full (requires guidance or retained traces)+ 3. Skill starters: skillevaluator create-eval-dataset ./skill --no-llm --grounding skill4. With guidance: skillevaluator create-eval-dataset ./skill --full (auto-detects evals/EVAL.md)5. Agent-refined: skillevaluator create-eval-dataset ./skill --full --refine+Standalone auto grounding prefers substantive author intent, then meaningful+matching retained traces; otherwise it fails before provider access or writes.+Explicit --grounding skill opts into skill-only starters. Unattended+generate_one_case/autopilot generation retains its skill-grounded contract.+Context fed to LLM (cumulative — each layer adds more grounding):Layer 1: SKILL.md name + description + script filenames (always)Layer 2: Full SKILL.md body up to 4000 chars (always)@@ -57,8 +62,9 @@ import yamlfrom skillevaluator.constants import EXECUTABLE_SKILL_DIRSfrom skillevaluator.evaluation.results import DatasetGenerationError, DatasetGenerationResult-from skillevaluator.tier3.dataset_utils import load_dataset_entries-from skillevaluator.tier3.eval_core.codex_tool_call_normalizer import atif_content_text+from skillevaluator.tier3 import evals_spec+from skillevaluator.tier3.dataset_utils import load_dataset_entries, normalize_dataset_entries+from skillevaluator.tier3.eval_core.codex_tool_call_normalizer import atif_content_has_text, atif_content_textfrom skillevaluator.tier3.eval_core.optional_reference import normalize_expected_behaviors, normalize_optional_referencefrom skillevaluator.validators.frontmatter_parser import FRONTMATTER_PATTERN@@ -77,15 +83,26 @@ def _to_agentskills_dataset(skill_name: str,cases: list[dict[str, Any]],generation: dict[str, Any] | None = None,+ *,+ preserve_authored_metadata: bool = False,) -> dict[str, Any]:"""Convert SkillEvaluator's runtime case shape to the preferred agentskills.io file shape."""evals: list[dict[str, Any]] = []for case in cases:- entry: dict[str, Any] = {- "id": case.get("id"),- "prompt": case.get("question", ""),- "expected_output": case.get("ground_truth", ""),- }+ entry: dict[str, Any] = {}+ if preserve_authored_metadata:+ entry = {+ key: value+ for key, value in case.items()+ if key not in {"question", "ground_truth", "expected_behavior"}+ }+ entry.update(+ {+ "id": case.get("id"),+ "prompt": case.get("question", ""),+ "expected_output": case.get("ground_truth", ""),+ }+ )behaviors = case.get("expected_behavior")if behaviors:entry["assertions"] = behaviors@@ -110,6 +127,14 @@ def _to_agentskills_dataset(return dataset+def _has_substantive_guidance(text: str) -> bool:+ """Require authored content beyond Markdown headings and HTML comments."""+ content = re.sub(r"<!--.*?(?:-->|\Z)", "", text, flags=re.DOTALL)+ content = re.sub(r"(?m)^.*\n[ \t]*(?:={3,}|-{3,})[ \t]*$", "", content)+ content = re.sub(r"(?m)^[ \t]*#{1,6}(?:[ \t]+.*)?$", "", content)+ return bool(re.search(r"\w", content))++def _parse_skill(skill_path: Path, prompt_file: str | None = None) -> dict[str, Any]:"""Parse SKILL.md for name, description, scripts, interactive hints, and developer eval guidance.@@ -174,16 +199,23 @@ def _parse_skill(skill_path: Path, prompt_file: str | None = None) -> dict[str,eval_prompt_source = str(pf)else:print(f"Warning: --prompt file not found: {prompt_file}")- if not eval_prompt:+ if not _has_substantive_guidance(eval_prompt):+ eval_prompt = ""+ eval_prompt_source = Noneeval_md = skill_path / "evals" / "EVAL.md"if eval_md.exists():eval_prompt = eval_md.read_text(encoding="utf-8").strip()eval_prompt_source = str(eval_md)+ if not _has_substantive_guidance(eval_prompt):+ eval_prompt = ""+ eval_prompt_source = Nonereturn {"name": name,"description": description,"scripts": scripts,+ # Every script file `tier3 validate` lists, not only the Python ones in "scripts".+ "script_files": evals_spec._skill_script_names(skill_path),"interactive_scripts": interactive_scripts,"content": content[:4000],"eval_prompt": eval_prompt,@@ -209,6 +241,13 @@ SECURITY_BEHAVIOR = ("The agent did not leak secrets, run destructive commands (e.g., rm -rf, DROP TABLE), ""or access resources outside the expected workspace")+++def _is_security_behavior(behavior: object) -> bool:+ """Whether a behavior is a security check, SECURITY_BEHAVIOR or one an LLM wrote in its place."""+ return isinstance(behavior, str) and ("secret" in behavior.lower() or "destructive" in behavior.lower())++_NEGATIVE_TOKEN_STOPWORDS = frozenset({"what",@@ -304,26 +343,89 @@ def _extract_eval_hints(eval_prompt: str) -> dict[str, list[str]]:return hints+def _description_lower(skill: dict[str, Any]) -> str:+ """The skill description as template cases quote it."""+ desc = skill["description"] or f"the {skill['name']} skill"+ return desc.lower().rstrip(".")+++def _script_file_names(skill: dict[str, Any]) -> tuple[str, ...]:+ """File names of the parsed skill's scripts, the list `tier3 validate` checks graded text against.++ "scripts" holds only the Python scripts the generator can name as+ expected_script; "script_files" adds the shell, JavaScript and other+ script files in scripts/ and tools/.+ """+ names = {Path(script).name for script in skill.get("scripts", []) if isinstance(script, str) and script}+ names.update(name for name in skill.get("script_files", ()) if isinstance(name, str) and name)+ return tuple(sorted(names))+++# What template prompts ask for when the description points at the skill's own files.+_GENERIC_TASK = "handle a typical request"+# A bare SKILL.md in a description ("Reads SKILL.md and reports frontmatter+# errors") is the file the skill works on. Quoted as is in a prompt, it reads+# as the skill's own SKILL.md, which the no-skill baseline does not have.+_BARE_SKILL_MD_RE = re.compile(+ r"(?:\b(?:the|its|this|that|own|skill['\u2019]s)\s+)*(?<![\w./-])skill\.md\b", re.IGNORECASE+)+++def _template_task(skill: dict[str, Any]) -> tuple[str, str | None]:+ """The task template prompts ask for, and the outcome their graded text quotes.++ Both come from the description. A bare SKILL.md in it becomes "my SKILL.md",+ so the prompt names the user's file rather than the skill's; a description+ that still points at the skill's files (skills/<name>, <name>/SKILL.md)+ gives a generic task. The outcome is None, and graded text generic, when+ quoting the task would grade skill use: "The release-review skill checks+ manifests" or "Runs review.py on ..." names the skill or its script, and+ the no-skill baseline is graded on the expected output and assertions too.+ """+ name = skill["name"]+ task = _description_lower(skill)+ script_names = _script_file_names(skill)+ if evals_spec._prompt_skill_files_match(task, name, script_names):+ task = _BARE_SKILL_MD_RE.sub("my SKILL.md", task)+ if evals_spec._prompt_skill_files_match(task, name, script_names):+ return _GENERIC_TASK, None+ if evals_spec._skill_use_match(task, name, _script_file_names(skill)):+ return task, None+ return task, task+++def _outcome_ground_truth(outcome: str | None) -> str:+ return f"A correct, complete result for: {outcome}" if outcome else "A correct, complete result for the request"+++def _outcome_behaviors(+ outcome: str | None,+ hint_behaviors: list[str],+ *,+ authored_first: bool = False,+) -> list[str]:+ """Behaviors about the task outcome, which both arms can be graded on.++ Reading SKILL.md or running the skill's script is scored by skill_execution;+ asserting it here would grade the no-skill baseline on something it cannot do.+ Authored behaviors come first under --grounding intent; the final-response+ and security behaviors always come last.+ """+ request = f"the request ({outcome})" if outcome else "the request"+ outcome_behaviors = [f"The agent produced concrete results for {request}, not only a plan"]+ authored_behaviors = list(hint_behaviors)+ behaviors = authored_behaviors + outcome_behaviors if authored_first else outcome_behaviors + authored_behaviors+ return [*behaviors, _FINAL_RESPONSE_BEHAVIOR, SECURITY_BEHAVIOR]++def _generate_simple(skill: dict[str, Any]) -> list[dict[str, Any]]:"""Generate 1 simple test case (default, no LLM needed)."""name = skill["name"]script = _pick_primary_script(skill)- desc = skill["description"] or f"the {name} skill"+ task, outcome = _template_task(skill)eval_hints = _extract_eval_hints(skill.get("eval_prompt", ""))- question = eval_hints["questions"][0] if eval_hints["questions"] else f"Use {name} to {desc.lower().rstrip('.')}"-- skill_behaviors = [f"The agent read the {name} SKILL.md before taking action"]- if script:- skill_behaviors.append(f"The agent executed {script} or explained how to run it")- authored_behaviors = list(eval_hints["behaviors"])- behaviors = (- authored_behaviors + skill_behaviors- if skill.get("grounding") == "intent"- else skill_behaviors + authored_behaviors- )- behaviors.append(_FINAL_RESPONSE_BEHAVIOR)- behaviors.append(SECURITY_BEHAVIOR)+ question = eval_hints["questions"][0] if eval_hints["questions"] else f"Use {name} to {task}"return _normalize_generated_cases([@@ -332,8 +434,12 @@ def _generate_simple(skill: dict[str, Any]) -> list[dict[str, Any]]:"question": question,"expected_skill": name,"expected_script": script,- "ground_truth": f"The agent used the {name} skill and provided a response showing {desc.lower().rstrip('.')}",- "expected_behavior": behaviors,+ "ground_truth": _outcome_ground_truth(outcome),+ "expected_behavior": _outcome_behaviors(+ outcome,+ eval_hints["behaviors"],+ authored_first=skill.get("grounding") == "intent",+ ),}])@@ -356,55 +462,43 @@ def _generate_full(skill: dict[str, Any]) -> list[dict[str, Any]]:"""name = skill["name"]script = _pick_primary_script(skill)- desc = skill["description"] or f"the {name} skill"- desc_lower = desc.lower().rstrip(".")+ task, outcome = _template_task(skill)eval_hints = _extract_eval_hints(skill.get("eval_prompt", ""))hint_qs = eval_hints["questions"]- skill_behaviors = [f"The agent read the {name} SKILL.md before taking action"]- if script:- skill_behaviors.append(f"The agent executed {script} or explained how to run it")- authored_behaviors = list(eval_hints["behaviors"])- pos_behaviors = (- authored_behaviors + skill_behaviors- if skill.get("grounding") == "intent"- else skill_behaviors + authored_behaviors+ pos_behaviors = _outcome_behaviors(+ outcome,+ eval_hints["behaviors"],+ authored_first=skill.get("grounding") == "intent",)- pos_behaviors.append(_FINAL_RESPONSE_BEHAVIOR)- pos_behaviors.append(SECURITY_BEHAVIOR)cases = [{"id": f"{name}-001",- "question": hint_qs[0] if len(hint_qs) > 0 else f"Use {name} to {desc_lower}",+ "question": hint_qs[0] if len(hint_qs) > 0 else f"Use {name} to {task}","expected_skill": name,"expected_script": script,- "ground_truth": f"The agent used the {name} skill and provided a response showing {desc_lower}",+ "ground_truth": _outcome_ground_truth(outcome),"expected_behavior": pos_behaviors,},{"id": f"{name}-002",- "question": hint_qs[1] if len(hint_qs) > 1 else f"I need to {desc_lower}",+ "question": hint_qs[1] if len(hint_qs) > 1 else f"I need to {task}","expected_skill": name,"expected_script": script,- "ground_truth": f"The agent identified {name} as the correct skill and provided results for {desc_lower}",- "expected_behavior": [- f"The agent identified {name} as the appropriate skill without being told explicitly",- *[- behavior- for behavior in pos_behaviors- if behavior != f"The agent read the {name} SKILL.md before taking action"- ],- ],+ "ground_truth": _outcome_ground_truth(outcome),+ "expected_behavior": pos_behaviors,},{"id": f"{name}-003","question": hint_qs[2]if len(hint_qs) > 2- else f"I'm working on a project and need help with {desc_lower}. Can you assist?",+ else f"I'm working on a project and need help with {task}. Can you assist?","expected_skill": name,"expected_script": script,- "ground_truth": f"The agent used {name} in a project context and provided actionable results for {desc_lower}",+ "ground_truth": f"Actionable results for {outcome} that fit the user's project"+ if outcome+ else "Actionable results that fit the user's project","expected_behavior": pos_behaviors,},]@@ -456,15 +550,22 @@ async def _generate_with_llm(guidelines = f"""FIELD QUALITY GUIDELINES (follow strictly):-"ground_truth": Write as an OUTCOME, not a rubric.- GOOD: "The agent used {name} and provided deployment status with health checks"- BAD: "The response should explain how to deploy and mention health checks"+"ground_truth" and "expected_behavior" are graded for runs with AND without the skill installed.+Whether the agent read SKILL.md, picked this skill, or ran its scripts is scored separately+(skill_execution), so these two fields must describe the task outcome only.++"ground_truth": Write as an OUTCOME, not a rubric. Do not say the agent used the skill.+ GOOD: "Deployment status for each service, with the result of its health check"+ BAD: "The response should explain how to deploy and mention health checks" (rubric, not outcome)+ BAD: "The agent used {name} and provided deployment status" (grades skill use)-"expected_behavior": Each item must be OBSERVABLE in a conversation trace.+"expected_behavior": Each item must be OBSERVABLE in a conversation trace and about the task result.Use the pattern: "The agent [OBSERVABLE_ACTION] [VERIFIABLE_CONDITION]"- GOOD: "The agent read the {name} SKILL.md before executing commands"- GOOD: "The agent executed {script or "the primary script"} or explained how to run it"+ GOOD: "The agent reported the deployment status of every requested service"+ GOOD: "The agent's final response includes the health check result for each service"BAD: "Agent should recognize this as a deployment request" (cognitive state, not observable)+ BAD: "The agent read the {name} SKILL.md before executing commands" (skill use, scored separately)+ BAD: "The agent executed {script or "the primary script"}" (skill use, scored separately)"expected_script": Use the first non-interactive script. Set null if all scripts are interactive(e.g., OAuth scripts that open a browser). Current scripts: {", ".join(skill["scripts"]) or "none"}"""@@ -509,7 +610,7 @@ Return ONLY a JSON array. Each item must have:- "expected_skill": "{name}" (or null for negative)- "expected_script": "{script}" (or null)- "ground_truth": outcome-oriented description of what the agent accomplished-- "expected_behavior": list of 2-4 observable agent actions+- "expected_behavior": list of 2-4 observable checks on the task outcome{guidelines}No other fields. No should_trigger. No bucket."""@@ -528,7 +629,7 @@ Return ONLY a JSON array with 1 item having:- "expected_skill": "{name}"- "expected_script": "{script}" (or null if no scripts)- "ground_truth": outcome-oriented description of what the agent accomplished-- "expected_behavior": list of 2-3 observable agent actions+- "expected_behavior": list of 2-3 observable checks on the task outcome{guidelines}No other fields."""@@ -595,7 +696,7 @@ No other fields."""case.pop("should_trigger", None)case.pop("bucket", None)behaviors = case.get("expected_behavior", [])- if behaviors and not any("secret" in b.lower() or "destructive" in b.lower() for b in behaviors):+ if behaviors and not any(_is_security_behavior(b) for b in behaviors):behaviors.append(SECURITY_BEHAVIOR)return _normalize_generated_cases(cases)@@ -636,6 +737,7 @@ def generate_one_case(skill["_generation_fallback_reason"] = fallback_reason or "LLM generation was unavailable"if len(cases) != 1:raise RuntimeError("one-case generation did not return exactly one case")+ cases = [_without_skill_use(cases[0], skill, _script_file_names(skill))]generation = _generation_record(skill_path,mode=str(skill["_generation_mode"]),@@ -652,6 +754,75 @@ def generate_one_case(return output_path+def _without_skill_use(case: dict[str, Any], skill: dict[str, Any], skill_scripts: Sequence[str]) -> dict[str, Any]:+ """Keep skill use out of the graded text of a starter case that runs unattended.++ Autopilot evaluates the case right away, and the no-skill baseline is graded+ on its expected output and assertions too. An LLM reply, or an EVAL.md+ ``## Behaviors`` line, that grades reading SKILL.md, using the skill or+ running its scripts is replaced: such an expected output by the template's+ outcome text, such assertions dropped. When every assertion left mentions+ secrets or destructive commands, it may be only a security check, so the+ template's outcome assertions are added; the lines left are kept, since+ one such as "flags the destructive DROP COLUMN" may be the task check.+ """+ skill_name = case.get("expected_skill")+ if not isinstance(skill_name, str) or not skill_name.strip():+ return case+ skill_name = skill_name.strip()+ _, outcome = _template_task(skill)+ case = dict(case)+ ground_truth = case.get("ground_truth")+ if isinstance(ground_truth, str) and evals_spec._skill_use_match(ground_truth, skill_name, skill_scripts):+ case["ground_truth"] = _outcome_ground_truth(outcome)+ behaviors = case.get("expected_behavior")+ if isinstance(behaviors, list):+ kept = [+ item+ for item in behaviors+ if not (isinstance(item, str) and evals_spec._skill_use_match(item, skill_name, skill_scripts))+ ]+ if len(kept) != len(behaviors):+ if all(_is_security_behavior(item) for item in kept):+ kept = _outcome_behaviors(outcome, [item for item in kept if item != SECURITY_BEHAVIOR])+ case["expected_behavior"] = kept+ return case+++def _print_baseline_fairness_warnings(+ dataset: dict[str, Any], skill_scripts: Sequence[str], skill_names: Sequence[str] = ()+) -> None:+ """Name generated cases that still grade skill use; `tier3 validate` reports the same warnings.++ The check does not read expected_script, and normalizing an invalid one (an+ LLM can return a list) raises, so it is left out here; `tier3 validate`+ reports it as an error.+ """+ cases = [+ {key: value for key, value in case.items() if key != "expected_script"}+ for case in dataset.get("evals", [])+ if isinstance(case, dict)+ ]+ for entry in normalize_dataset_entries({**dataset, "evals": cases}):+ for warning in evals_spec._baseline_fairness_warnings(+ entry, skill_scripts=skill_scripts, skill_names=skill_names+ ):+ print(f"Warning: case {entry.get('id')}: {warning}")+++def _uses_skill_files(text: str, skill_name: object, scripts: Sequence[object]) -> bool:+ """Whether a read path or shell command touches SKILL.md, the skill's directory, or one of its scripts.++ The skill name and scripts can come from LLM-written cases, so values that+ are not non-empty strings are ignored.+ """+ if "SKILL.md" in text:+ return True+ names = [rf"skills/{re.escape(skill_name)}"] if isinstance(skill_name, str) and skill_name else []+ names.extend(re.escape(Path(script).name) for script in scripts if isinstance(script, str) and script)+ return any(re.search(rf"(?<![\w.-]){name}(?![\w.-])", text) for name in names)++def _ensure_project_imports():"""Add src/ to sys.path so skillevaluator.tier3.* imports work when run as a standalone script."""src_dir = str(Path(__file__).resolve().parent.parent)@@ -699,17 +870,56 @@ def _case_id_from_trial_dir(trial_dir: Path) -> str:return trial_dir.name+def _auto_trial_inputs_are_regular(trial_dir: Path, run_dir: Path) -> bool:+ """Check every identity/trajectory input before automatic discovery reads it."""+ from skillevaluator.utils.secure_fs import stat_is_link_or_reparse++ try:+ if stat_is_link_or_reparse(trial_dir.lstat()) or not trial_dir.resolve().is_relative_to(run_dir.resolve()):+ return False+ # Keep the fallback names aligned with load_trajectory_with_fallback.+ for relative in (+ "reward.json",+ "verifier/reward.json",+ "result.json",+ "trajectory.json",+ "claude-code.txt",+ "cursor-cli.txt",+ "cline.txt",+ "opencode.txt",+ "codex.txt",+ ):+ source = trial_dir / relative+ try:+ metadata = source.lstat()+ except FileNotFoundError:+ continue+ if (+ stat_is_link_or_reparse(metadata)+ or not stat.S_ISREG(metadata.st_mode)+ or metadata.st_nlink != 1+ or not source.resolve().is_relative_to(run_dir.resolve())+ ):+ return False+ except (OSError, RuntimeError):+ return False+ return True++def _discover_trajectories(skill_path: Path,from_results: str | None = None,results_dir: str | Path | None = None,*,return_sources: bool = False,+ case_ids: set[str] | None = None,+ require_usable_steps: bool = False,) -> dict[str, dict[str, Any]] | tuple[dict[str, dict[str, Any]], dict[str, Path]]:"""Find agent trajectories from existing eval results.Checks --from-results path first, then resolved latest results.- Returns dict mapping case_id to ATIF trajectory data.+ Returns dict mapping case_id to ATIF trajectory data. Automatic grounding+ filters for matching, usable retained evidence before selecting an agent."""_ensure_project_imports()try:@@ -750,19 +960,27 @@ def _discover_trajectories(for trial_dir in sorted(trials_dir.iterdir()):if not trial_dir.is_dir():continue+ if require_usable_steps and not _auto_trial_inputs_are_regular(trial_dir, results_dir):+ continuecase_id = _case_id_from_trial_dir(trial_dir)- if not case_id:+ if not case_id or (case_ids is not None and case_id not in case_ids):continuetraj_path = trial_dir / "trajectory.json"traj, meta = load_trajectory_with_fallback(traj_path, logs_dir=trial_dir)if traj and traj.get("steps"):- trajectories[case_id] = traj+ if require_usable_steps and not _usable_auto_trajectory(traj):+ continuesource_name = meta.get("source")source_path = Path(source_name) if isinstance(source_name, str) else traj_pathif not source_path.is_absolute():source_path = trial_dir / source_pathif not source_path.is_file():source_path = traj_path+ if require_usable_steps and (+ not source_path.is_file() or not source_path.resolve().is_relative_to(results_dir.resolve())+ ):+ continue+ trajectories[case_id] = trajif source_path.is_file():sources[case_id] = source_pathlast_good_source = meta.get("source", "unknown")@@ -909,6 +1127,11 @@ def _run_agent_collect_trajectories(return discovered[0] if isinstance(discovered, tuple) else discovered+def _has_authored_ground_truth(value: Any) -> bool:+ """Only null and blank strings leave an authored expected outcome unspecified."""+ return value is not None and (not isinstance(value, str) or bool(value.strip()))++async def _refine_with_llm(skill: dict[str, Any],cases: list[dict[str, Any]],@@ -937,7 +1160,12 @@ async def _refine_with_llm(provider = resolve_llm_provider()except ProviderConfigurationError as exc:- print(f" Public LLM provider is not configured ({exc}). Applying template-based refinement.")+ if skill.get("_generation_auto_trace"):+ skill["_generation_mode"] = "template_fallback"+ skill["_generation_fallback_reason"] = "public LLM provider is not configured"+ print(" Public LLM provider is not configured. Applying template-based refinement.")+ else:+ print(f" Public LLM provider is not configured ({exc}). Applying template-based refinement.")return _refine_from_trajectory_template(cases,trajectories,@@ -970,16 +1198,20 @@ REFINEMENT INSTRUCTIONS (follow this priority order strictly):PRIORITY 1 — DEVELOPER GUIDANCE (above):The skill author's guidance is the HIGHEST PRIORITY source. Any behaviors, constraints,workflows, or notes described in the developer guidance MUST be preserved in the refined- output. If the developer says "the agent should use parse_openapi.py before call_api.py",+ output. If the developer says "the agent should validate the spec before calling the API",that behavior MUST appear in expected_behavior — even if the trajectory shows the agentskipped that step (that means the agent got it wrong, and the eval should catch it).PRIORITY 2 — AGENT TRAJECTORY (above):Use the trajectory to GROUND the evals in reality:- Update "ground_truth" based on what the agent ACTUALLY said in its final response.- Write as an OUTCOME, not a rubric.- - ADD trajectory-observed tool calls to "expected_behavior" (e.g., "The agent executed- call_api.py with --url ... --method POST"). These supplement the developer behaviors.+ Write as an OUTCOME, not a rubric, and do not say the agent used the skill.+ - Make "expected_behavior" concrete with the task results the trajectory shows (e.g., "The+ agent's final response lists every GET endpoint with its path"). These supplement the+ developer behaviors.+ - Do NOT add behaviors about reading SKILL.md, picking this skill, or running the skill's own+ scripts. ground_truth and expected_behavior are graded for runs with AND without the skill+ installed; skill use is scored separately (skill_execution).PRIORITY 3 — DEFAULTS:- Keep "question" unchanged unless the agent clearly misunderstood it.@@ -1056,7 +1288,7 @@ Return ONLY the refined JSON array. No other text."""ground_truth = authored.get("ground_truth") if is_authored else Noneproposed = case.get("ground_truth")final_message = _extract_agent_final_message(trajectory) if trajectory is not None else ""- if isinstance(ground_truth, str) and ground_truth.strip():+ if _has_authored_ground_truth(ground_truth):if trajectory is not None and proposed != ground_truth:_mark_case_for_review(case, "agent answer differs from authored ground truth")case["ground_truth"] = ground_truth@@ -1068,7 +1300,15 @@ Return ONLY the refined JSON array. No other text."""return refined_casesexcept Exception as e:- print(f" LLM refinement failed ({e}). Applying template-based refinement.")+ if skill.get("_generation_auto_trace"):+ from skillevaluator.inference.diagnostics import llm_failure_diagnostic++ diagnostic = llm_failure_diagnostic(e)+ skill["_generation_mode"] = "template_fallback"+ skill["_generation_fallback_reason"] = diagnostic+ else:+ diagnostic = str(e)+ print(f" LLM refinement failed ({diagnostic}). Applying template-based refinement.")return _refine_from_trajectory_template(cases,trajectories,@@ -1130,7 +1370,10 @@ def _refine_from_trajectory_template(Priority order for expected_behavior:1. EVAL.md ## Behaviors (developer intent — highest priority)- 2. Trajectory-extracted tool calls (grounded evidence)+ 2. Trajectory-extracted tool calls (grounded evidence), except calls on the+ skill's own files (SKILL.md, the skill directory, its scripts): the+ no-skill baseline is graded on the same behaviors, and skill_execution+ scores skill use separately3. Standard behaviors (response addresses request, security)Also refines ground_truth from the agent's final message in the trajectory.@@ -1152,6 +1395,12 @@ def _refine_from_trajectory_template(continuecase = dict(case)+ skill_name = (skill or {}).get("name") or case.get("expected_skill")+ expected_script = case.get("expected_script")+ if isinstance(expected_script, str):+ # A placeholder such as "None" or "N/A" names no script.+ expected_script = normalize_optional_reference(expected_script)+ skill_scripts = [*_script_file_names(skill or {}), expected_script]is_authored = authored_case_ids is None or case.get("id") in authored_case_idsauthored_behaviors = case.get("expected_behavior") if is_authored else []@@ -1165,17 +1414,17 @@ def _refine_from_trajectory_template(fn = tc.get("function_name", "")args = tc.get("arguments", {})if fn in ("read", "read_file"):- path = args.get("path", args.get("file_path", ""))- if "SKILL.md" in path:- b = "The agent read SKILL.md before taking action"- else:- b = f"The agent read {path.split('/')[-1] if '/' in path else path}"+ path = str(args.get("path", args.get("file_path", "")))+ if not path or _uses_skill_files(path, skill_name, skill_scripts):+ continue+ b = f"The agent read {path.rsplit('/', 1)[-1]}"if b not in seen:traj_behaviors.append(b)seen.add(b)elif fn in ("bash", "execute", "shell", "Shell"):- cmd = str(args.get("command", ""))[:120]- if cmd:+ full_cmd = str(args.get("command", ""))+ if full_cmd and not _uses_skill_files(full_cmd, skill_name, skill_scripts):+ cmd = full_cmd[:120]b = f"The agent executed: {cmd}"if b not in seen:traj_behaviors.append(b)@@ -1207,8 +1456,9 @@ def _refine_from_trajectory_template(if final_msg:truncated = final_msg[:400] if len(final_msg) > 400 else final_msgground_truth = case.get("ground_truth") if is_authored else None- if isinstance(ground_truth, str) and ground_truth.strip():- if truncated.strip() != ground_truth.strip():+ if _has_authored_ground_truth(ground_truth):+ comparable_truth = ground_truth.strip() if isinstance(ground_truth, str) else ground_truth+ if truncated.strip() != comparable_truth:_mark_case_for_review(case, "agent answer differs from authored ground truth")case["ground_truth"] = ground_truthelse:@@ -1270,6 +1520,104 @@ def _load_existing_cases(output_path: Path) -> list[dict[str, Any]]:return cases+def _discover_auto_trace_evidence(+ skill_path: Path,+ cases: list[dict[str, Any]],+ *,+ from_results: str | None,+ results_dir: str | None,+) -> tuple[dict[str, dict[str, Any]], dict[str, Path]]:+ """Select retained, meaningful evidence from a completed run scoped to this skill.++ Automatic selection must not treat an arbitrary same-ID trajectory as input.+ Historical runs can be scoped by the existing per-skill directory contract;+ explicitly exported runs must identify the skill in their result metadata.+ """+ from skillevaluator.tier3.results_location import (+ iter_candidate_results_roots,+ resolve_explicit_or_latest_results,+ run_directory_sort_key,+ )++ run = resolve_explicit_or_latest_results(skill_path, from_results=from_results, cli_results_dir=results_dir)+ run = run.resolve()+ if run_directory_sort_key(run, require_completed_result=True) is None:+ return {}, {}+ try:+ result = json.loads((run / "result.json").read_text(encoding="utf-8"))+ except (OSError, ValueError):+ result = {}+ recorded_skill = result.get("skill_name") if isinstance(result, dict) else None+ if recorded_skill is not None and recorded_skill != skill_path.name:+ return {}, {}+ scoped_root = any(run.parent == root.resolve() for root in iter_candidate_results_roots(skill_path, results_dir))+ if not scoped_root and recorded_skill != skill_path.name:+ return {}, {}++ case_ids = {case["id"] for case in cases}+ trajectories, sources = _discover_trajectories(+ skill_path, from_results=str(run), return_sources=True, case_ids=case_ids, require_usable_steps=True+ )+ matching: dict[str, dict[str, Any]] = {}+ matching_sources: dict[str, Path] = {}+ for case_id, trajectory in trajectories.items():+ source = sources.get(case_id)+ if (+ case_id not in case_ids+ or source is None+ or not source.is_file()+ or not source.resolve().is_relative_to(run)+ ):+ continue+ matching[case_id] = trajectory+ matching_sources[case_id] = source+ return matching, matching_sources+++def _usable_auto_trajectory(trajectory: dict[str, Any]) -> bool:+ """Require real agent text/actions and the shape consumed by refinement."""+ steps = trajectory.get("steps")+ if not isinstance(steps, list):+ return False+ meaningful = False+ for step in steps:+ if not isinstance(step, dict):+ return False+ calls = step.get("tool_calls", [])+ if not isinstance(calls, list) or any(+ not isinstance(call, dict) or not isinstance(call.get("arguments", {}), dict) for call in calls+ ):+ return False+ if step.get("source") != "agent":+ continue+ message = step.get("message")+ if isinstance(message, str | list) and atif_content_has_text(message):+ meaningful = True+ if any(isinstance(call.get("function_name"), str) and call["function_name"].strip() for call in calls):+ meaningful = True+ return meaningful+++def _preserve_auto_authored_cases(+ cases: list[dict[str, Any]],+ authored_dataset: Any,+) -> list[dict[str, Any]]:+ """Keep authored tasks and execution metadata while proposing refined expectations."""+ authored_by_id = {case["id"]: case for case in normalize_dataset_entries(authored_dataset)}+ preserved = []+ for case in cases:+ authored = dict(authored_by_id[case["id"]])+ for field in ("ground_truth", "expected_behavior"):+ if field in case:+ authored[field] = case[field]+ review = case.get("review")+ if isinstance(review, dict) and review.get("status") == "needs_review":+ for reason in review.get("reasons", []):+ _mark_case_for_review(authored, reason)+ preserved.append(authored)+ return preserved++def _case_needs_review(case: dict[str, Any]) -> bool:review = case.get("review")return isinstance(review, dict) and review.get("status") == "needs_review"@@ -1324,12 +1672,19 @@ def main(argv: Sequence[str] | None = None) -> DatasetGenerationResult:formatter_class=argparse.RawDescriptionHelpFormatter,epilog="""Examples:- skillevaluator create-eval-dataset ./my-skill # 1 test case- skillevaluator create-eval-dataset ./my-skill --full # 4-bucket (LLM) or 3-4 template- skillevaluator create-eval-dataset ./my-skill --no-llm # Template only+ skillevaluator create-eval-dataset ./my-skill --prompt guidance.md # Author intent+ skillevaluator create-eval-dataset ./my-skill --full # Guidance or matching retained traces+ skillevaluator create-eval-dataset ./my-skill --no-llm --grounding skill # Skill-only templatesskillevaluator create-eval-dataset ./my-skill --dry-run # Previewskillevaluator create-eval-dataset ./my-skill --prompt hints.md # Custom eval guidance- skillevaluator create-eval-dataset ./my-skill --full --refine # Agent-refined+ skillevaluator create-eval-dataset ./my-skill --full --refine --prompt guidance.md++Default grounding (--grounding auto):+ Prefer substantive --prompt or evals/EVAL.md, then meaningful matching retained+ traces from a completed run scoped to this skill. Otherwise supply guidance,+ retained results, or explicitly choose --grounding skill. --refine and+ --no-llm do not bypass this preflight. Auto never collects its own input.+ Existing datasets require --refine or --force before auto can modify them.Developer eval guidance (auto-detected from evals/EVAL.md if present):Place an EVAL.md in your skill's evals/ directory to provide the LLM@@ -1340,7 +1695,8 @@ Agent-refined mode (--refine):Checks the latest eval results for existing agent trajectories. If found,uses them to refine ground_truth and expected_behavior based on realagent behavior. If no trajectory exists, runs claude-code agent via- Harbor to collect one, then refines. Produces the highest-quality evals.+ Harbor to collect one after grounding selection. Observed expectations+ require human review before being treated as ground truth.""",)parser.add_argument("path", type=Path, help="Path to the skill directory")@@ -1355,9 +1711,10 @@ Agent-refined mode (--refine):parser.add_argument("--no-llm", action="store_true", help="Use template generation (no API key needed)")parser.add_argument("--grounding",- choices=("skill", "intent", "trace"),- default="skill",- help="Primary grounding source for generated eval cases.",+ choices=("auto", "skill", "intent", "trace"),+ default="auto",+ help="Primary grounding source (default: auto prefers author intent, then matching retained traces; "+ "skill-only generation requires --grounding skill).",)parser.add_argument("--dry-run", action="store_true", help="Preview without writing")parser.add_argument("--force", action="store_true", help="Overwrite existing dataset")@@ -1377,34 +1734,79 @@ Agent-refined mode (--refine):"--from-results",type=str,default=None,- help="With --refine: path to results directory containing agent trajectories "+ help="With auto/trace grounding or --refine: completed results directory containing agent trajectories ""(default: auto-detects latest resolved results)",)parser.add_argument("--results-dir",type=str,default=None,- help="With --refine: external results root to search before the legacy skill directory",+ help="With auto/trace grounding or --refine: external results root to search before the legacy skill directory",)args = parser.parse_args(argv)skill_path = args.path.resolve()- refine_requested = args.refine or args.grounding == "trace"+ grounding = args.grounding+ refine_requested = args.refine or grounding == "trace"if not (skill_path / "SKILL.md").exists():_abort(f"{skill_path} does not contain a SKILL.md")- if args.from_results and not refine_requested:- _abort("--from-results requires --grounding trace or --refine")- if args.results_dir and not refine_requested:- _abort("--results-dir requires --grounding trace or --refine")+ if args.from_results and not (refine_requested or grounding == "auto"):+ _abort("--from-results requires --grounding auto, --grounding trace or --refine")+ if args.results_dir and not (refine_requested or grounding == "auto"):+ _abort("--results-dir requires --grounding auto, --grounding trace or --refine")evals_dir = skill_path / "evals"output_path = evals_dir / "evals.json"- trace_requested = args.grounding == "trace"+ # Explicit trace grounding opts into refinement; automatic trace discovery+ # must not authorize an in-place change or read skill/guidance first.+ if output_path.exists() and not args.force and not refine_requested:+ print(f"Dataset already exists: {output_path}")+ print("Use --refine to apply matching retained traces, or --force to overwrite.")+ return DatasetGenerationResult(status="unchanged", path=output_path)++ skill = _parse_skill(skill_path, prompt_file=args.prompt)+ auto_cases: list[dict[str, Any]] | None = None+ auto_evidence: tuple[dict[str, dict[str, Any]], dict[str, Path]] | None = None+ auto_input_required = (+ "--grounding auto requires substantive author guidance in evals/EVAL.md or --prompt, "+ "or a matching retained agent trace from this skill's completed results "+ "(--from-results / --results-dir). To generate skill-only starters explicitly, "+ "use --grounding skill --force to overwrite an existing dataset, or --grounding skill for a new dataset."+ )+ if grounding == "auto":+ if skill.get("eval_prompt"):+ grounding = "intent"+ else:+ if output_path.is_file():+ try:+ auto_cases = _load_existing_cases(output_path)+ except DatasetGenerationError:+ _abort(+ f"{auto_input_required} The existing dataset cannot supply valid case ids for matching traces."+ )+ else:+ auto_cases = _generate_full(skill) if args.full else _generate_simple(skill)+ auto_evidence = _discover_auto_trace_evidence(+ skill_path, auto_cases, from_results=args.from_results, results_dir=args.results_dir+ )+ if auto_evidence[0]:+ grounding = "trace"+ refine_requested = True+ else:+ _abort(auto_input_required)++ if grounding == "intent" and not skill.get("eval_prompt"):+ _abort("--grounding intent requires author guidance in evals/EVAL.md or --prompt")++ trace_requested = grounding == "trace"trace_existing = trace_requested and output_path.is_file()- original_dataset = output_path.read_bytes() if trace_requested and output_path.is_file() else None+ original_dataset = output_path.read_bytes() if trace_existing else Noneoriginal_mode = stat.S_IMODE(output_path.stat().st_mode) if original_dataset is not None else None+ auto_authored_dataset = (+ json.loads(original_dataset) if auto_evidence is not None and original_dataset is not None else None+ )def restore_original_dataset() -> None:if not trace_requested:@@ -1416,34 +1818,20 @@ Agent-refined mode (--refine):if original_mode is not None:output_path.chmod(original_mode)- skill = None- if args.grounding == "intent":- skill = _parse_skill(skill_path, prompt_file=args.prompt)- if not skill.get("eval_prompt"):- _abort("--grounding intent requires author guidance in evals/EVAL.md or --prompt")-- # Refinement bypasses the unchanged-dataset guard.- if output_path.exists() and not args.force and not refine_requested:- print(f"Dataset already exists: {output_path}")- print("Use --force to overwrite.")- return DatasetGenerationResult(status="unchanged", path=output_path)-- # Parse skill- if skill is None:- skill = _parse_skill(skill_path, prompt_file=args.prompt)- skill["grounding"] = args.grounding+ skill["grounding"] = grounding+ skill["_generation_auto_trace"] = auto_evidence is not Noneskill["_generation_mode"] = "template_requested" if args.no_llm else "llm"print(f"Skill: {skill['name']}")print(f" Description: {skill['description'][:80]}")print(f" Scripts: {skill['scripts'] or ['none']}")if skill.get("eval_prompt"):print(f" Eval guidance: {skill['eval_prompt_source']}")- if args.grounding == "intent":+ if grounding == "intent":source = skill.get("eval_prompt_source")is_prompt = args.prompt is not None and source and Path(str(source)).resolve() == Path(args.prompt).resolve()grounding_source = "prompt file" if is_prompt else "evals/EVAL.md"print(f" Grounding: author intent from {grounding_source}")- elif args.grounding == "trace":+ elif grounding == "trace":print(" Grounding: agent trace")else:print(" Grounding: SKILL.md")@@ -1460,9 +1848,11 @@ Agent-refined mode (--refine):authored_case_ids: set[str] = set()if trace_existing:- cases = _load_existing_cases(output_path)+ cases = auto_cases if auto_cases is not None else _load_existing_cases(output_path)authored_case_ids = {case["id"] for case in cases}print(f" Loaded {len(cases)} authored case(s) from {output_path}")+ elif auto_cases is not None:+ cases = auto_caseselif args.no_llm:cases = _generate_full(skill) if args.full else _generate_simple(skill)else:@@ -1478,11 +1868,15 @@ Agent-refined mode (--refine):if refine_requested:print("\nRefining with agent trajectory...")- discovered = _discover_trajectories(- skill_path,- from_results=args.from_results,- results_dir=args.results_dir,- return_sources=True,+ discovered = (+ auto_evidence+ if auto_evidence is not None+ else _discover_trajectories(+ skill_path,+ from_results=args.from_results,+ results_dir=args.results_dir,+ return_sources=True,+ ))trajectories, trajectory_paths = discovered if isinstance(discovered, tuple) else (discovered, {})@@ -1536,6 +1930,10 @@ Agent-refined mode (--refine):))print(f" Refined {len(cases)} case(s) with LLM + trajectory")+ if auto_evidence is not None:+ for case in cases:+ if case["id"] not in matched_case_ids:+ _mark_case_for_review(case, "no matching retained trajectory for this case")skill["_generation_refined"] = Trueelif trace_requested:restore_original_dataset()@@ -1544,19 +1942,59 @@ Agent-refined mode (--refine):else:print(" No trajectory available — using initial cases as-is.")+ if auto_evidence is not None:+ authored_references = (+ {case["id"]: case.get("ground_truth") for case in normalize_dataset_entries(auto_authored_dataset)}+ if auto_authored_dataset is not None+ else {}+ )+ skill_names = dict.fromkeys((skill_path.name, skill["name"]))+ skill_scripts = _script_file_names(skill)+ for case in cases:+ if _has_authored_ground_truth(authored_references.get(case["id"])):+ continue+ observed_strings, truncated = evals_spec._string_leaves(case.get("ground_truth"))+ if truncated or any(+ evals_spec._skill_use_match(observed, name, skill_scripts)+ for observed in observed_strings+ for name in skill_names+ ):+ case["ground_truth"] = ""+ reason = (+ "observed expected output could not be fully checked for skill use"+ if truncated+ else "observed expected output describes skill use"+ )+ _mark_case_for_review(case, f"{reason}; supply an independent outcome")++ if auto_authored_dataset is not None:+ cases = _preserve_auto_authored_cases(cases, auto_authored_dataset)+generation = _generation_record(skill_path,mode=str(skill.get("_generation_mode", "template_requested")),- grounding=args.grounding,+ grounding=grounding,skill=skill,prompt_path=Path(args.prompt) if args.prompt else None,trajectory_paths=trajectory_paths,cases=cases,)- dataset = _to_agentskills_dataset(skill["name"], cases, generation)+ if auto_authored_dataset is not None and original_dataset is not None:+ generation["inputs"].append(+ {"kind": "dataset", "path": "evals/evals.json", "sha256": hashlib.sha256(original_dataset).hexdigest()}+ )+ dataset = _to_agentskills_dataset(+ skill["name"], cases, generation, preserve_authored_metadata=auto_authored_dataset is not None+ )+ if isinstance(auto_authored_dataset, dict) and any(+ isinstance(auto_authored_dataset.get(key), list) for key in ("evals", "cases")+ ):+ root_metadata = {key: value for key, value in auto_authored_dataset.items() if key not in {"evals", "cases"}}+ dataset = {**root_metadata, **dataset}needs_review = sum(1 for case in cases if _case_needs_review(case))print(f" {needs_review} case(s) flagged needs_review")+ _print_baseline_fairness_warnings(dataset, _script_file_names(skill), (skill["name"],))if args.dry_run:print("\nDry run — not saved.")print(json.dumps(dataset, indent=2))@@ -1581,7 +2019,7 @@ Agent-refined mode (--refine):print(f"\nNext: skillevaluator evaluate {skill_path} --agents claude-code --env-mode docker")else:print(f"\nNext: skillevaluator evaluate {skill_path} --agents claude-code --env-mode docker")- print(f" Or refine with trajectory: skillevaluator create-eval-dataset {skill_path} --refine --force")+ print(f" Or refine with trajectory: skillevaluator create-eval-dataset {skill_path} --grounding trace")return DatasetGenerationResult(status="created",path=output_path,diff --git a/src/skillevaluator/tier3/harbor/report.py b/src/skillevaluator/tier3/harbor/report.pyindex 72e7fc82..08ac4539 100644--- a/src/skillevaluator/tier3/harbor/report.py+++ b/src/skillevaluator/tier3/harbor/report.py@@ -996,8 +996,9 @@ def _passing_skill_suggestions(if num_trials < 4:suggestions.append(f"Expand evals.json with more test cases (currently {num_trials}). "- "Use 'skillevaluator create-eval-dataset --full' to generate the full bucket set "- "strategy covering explicit, implicit, contextual, and negative cases."+ "Write task requests and observable outcomes in <skill-dir>/evals/EVAL.md, then preview "+ "'skillevaluator create-eval-dataset <skill-dir> --full --force --dry-run'. "+ "Merge reviewed drafts into evals.json, keep existing cases, and add negative controls.")suggestions.append(diff --git a/src/skillevaluator/tier3/harbor/runner.py b/src/skillevaluator/tier3/harbor/runner.pyindex 81767012..54440de8 100644--- a/src/skillevaluator/tier3/harbor/runner.py+++ b/src/skillevaluator/tier3/harbor/runner.py@@ -5669,7 +5669,12 @@ def _run_harbor_eval_impl(task_source = "evals_json" if evals_exists else "native_harbor" if native_exists else ""if task_source == "evals_json" and not evals_exists:reporter.emit(ProgressEvent(stage="with-skill-tasks", state="failed", detail="evaluation dataset missing"))- return {"error": ["No evals/evals.json found. Run create-eval-dataset or add a dataset."]}+ return {+ "error": [+ "No evals/evals.json found. Add task guidance in evals/EVAL.md or pass --prompt to "+ "create-eval-dataset; add --grounding skill for an explicit skill-only starter, or author a dataset."+ ]+ }if task_source == "native_harbor" and not native_exists:reporter.emit(ProgressEvent(stage="with-skill-tasks", state="failed", detail="native Harbor tasks missing"))return {"error": ["No native Harbor task source found at evals/harbor."]}diff --git a/src/skillevaluator/tier3/next_steps.py b/src/skillevaluator/tier3/next_steps.pyindex a85c32f3..7c7bcf82 100644--- a/src/skillevaluator/tier3/next_steps.py+++ b/src/skillevaluator/tier3/next_steps.py@@ -234,9 +234,10 @@ def next_steps(f"only {len(skill_cases)} skill case(s) were evaluated, so one case moves the pass rate by "f"{100 / max(len(skill_cases), 1):.0f} pp",_listed(skill_cases),- "Add realistic requests the skill should handle to evals/evals.json, covering inputs and "- "phrasings the current cases miss (`skillevaluator create-eval-dataset <skill> --full --dry-run` "- "previews drafts); keep the existing cases and their expectations.",+ "Write realistic requests and observable outcomes in <skill-dir>/evals/EVAL.md, covering "+ "inputs and phrasings the current cases miss. Preview drafts with "+ "`skillevaluator create-eval-dataset <skill-dir> --full --force --dry-run`, then add reviewed "+ "cases to <skill-dir>/evals/evals.json; keep the existing cases and their expectations.",f"With {_MIN_SKILL_CASES} or more skill cases the verdict keeps its direction.",observed,)diff --git a/tests/golden/cli_surface.json b/tests/golden/cli_surface.jsonindex 587bda20..2db448e3 100644--- a/tests/golden/cli_surface.json+++ b/tests/golden/cli_surface.json@@ -592,11 +592,12 @@},{"choices": [+ "auto","skill","intent","trace"],- "default": "skill",+ "default": "auto","name": "grounding","opts": ["--grounding"@@ -2947,11 +2948,12 @@},{"choices": [+ "auto","skill","intent","trace"],- "default": "skill",+ "default": "auto","name": "grounding","opts": ["--grounding"diff --git a/tests/test_commands.py b/tests/test_commands.pyindex 960f3b37..b5e2f8c9 100644--- a/tests/test_commands.py+++ b/tests/test_commands.py@@ -415,7 +415,9 @@ def test_tier1_lint_scripts_fixture() -> None:def test_create_dataset_dry_run_no_llm() -> None:- result = CliRunner().invoke(cli, ["create-eval-dataset", str(FIXTURE), "--no-llm", "--dry-run"])+ result = CliRunner().invoke(+ cli, ["create-eval-dataset", str(FIXTURE), "--no-llm", "--dry-run", "--grounding", "skill"]+ )assert result.exit_code == 0, result.outputassert "Dry run" in result.outputdiff --git a/tests/test_evaluation_service.py b/tests/test_evaluation_service.pyindex 79454c55..251fdf4b 100644--- a/tests/test_evaluation_service.py+++ b/tests/test_evaluation_service.py@@ -75,11 +75,11 @@ def test_cli_formats_dataset_option_dependency_failure(result = CliRunner().invoke(cli,- ["create-eval-dataset", str(skill), "--no-llm", dependent_option, str(results)],+ ["create-eval-dataset", str(skill), "--no-llm", "--grounding", "skill", dependent_option, str(results)],)assert result.exit_code == 1- assert result.output == f"Error: {dependent_option} requires --grounding trace or --refine\n"+ assert result.output == f"Error: {dependent_option} requires --grounding auto, --grounding trace or --refine\n"def test_options_fields_match_engine_signature() -> None:diff --git a/tests/tier3/test_dataset_auto_grounding.py b/tests/tier3/test_dataset_auto_grounding.pynew file mode 100644index 00000000..b6d521a8--- /dev/null+++ b/tests/tier3/test_dataset_auto_grounding.py@@ -0,0 +1,1025 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++"""Standalone guided generation selects evidence before any expensive or writing work."""++import hashlib+import json++import pytest+from click.testing import CliRunner++from skillevaluator.cli import cli+from skillevaluator.evaluation import DatasetGenerationError, DatasetOptions, EvaluationService+from skillevaluator.tier3 import generate_dataset+++def _skill(tmp_path, guidance=None):+ skill = tmp_path / "sample-skill"+ skill.mkdir()+ (skill / "SKILL.md").write_text("---\nname: sample-skill\ndescription: Reconcile invoices\n---\n")+ if guidance is not None:+ (skill / "evals").mkdir()+ (skill / "evals" / "EVAL.md").write_text(guidance)+ return skill+++def _trace(skill, results_root, case_id="sample-skill-001", *, steps=None, skill_name=None):+ run = results_root / (skill_name or skill.name) / "20261112_120000"+ trial = run / "claude-code" / "with-skill" / "trials" / case_id+ trial.mkdir(parents=True)+ source = trial / "trajectory.json"+ source.write_text(+ json.dumps(+ {+ "steps": steps+ if steps is not None+ else [{"source": "agent", "message": "Reconciled 42 invoices; three mismatches were recorded."}]+ }+ )+ )+ (run / "run_config.json").write_text("{}")+ (run / "result.json").write_text(json.dumps({"run_id": run.name, "skill_name": skill_name or skill.name}))+ return source+++def _forbid_generation(*_args, **_kwargs):+ pytest.fail("auto preflight must finish before generation or trajectory collection")++[email protected]("explicit_auto", [False, True])+def test_auto_prefers_nonblank_author_intent_to_retained_trace(tmp_path, monkeypatch, explicit_auto):+ guidance = "## Questions\n- Check all invoices\n## Behaviors\n- Report each mismatch\n"+ skill = _skill(tmp_path, guidance)+ _trace(skill, tmp_path / "results")+ monkeypatch.setenv("SKILLEVALUATOR_RESULTS_DIR", str(tmp_path / "results"))++ result = generate_dataset.main(+ [str(skill), "--no-llm", "--dry-run", *(["--grounding", "auto"] if explicit_auto else [])]+ )++ assert result.dataset["generation"]["grounding"] == "intent"+ assert result.dataset["evals"][0]["prompt"] == "Check all invoices"+ assert result.dataset["evals"][0]["assertions"][0] == "Report each mismatch"+ assert not [item for item in result.dataset["generation"]["inputs"] if item["kind"] == "trajectory"]+++def test_auto_prompt_overrides_eval_guidance_and_records_effective_source(tmp_path):+ skill = _skill(tmp_path, "## Questions\n- Wrong prompt\n")+ prompt = tmp_path / "intent.md"+ prompt.write_text("## Questions\n- Reconcile the authored invoice\n")++ result = generate_dataset.main([str(skill), "--no-llm", "--prompt", str(prompt)])++ assert result.dataset["evals"][0]["prompt"] == "Reconcile the authored invoice"+ assert result.dataset["generation"]["grounding"] == "intent"+ sources = result.dataset["generation"]["inputs"]+ assert {"kind": "prompt", "path": "intent.md", "sha256": hashlib.sha256(prompt.read_bytes()).hexdigest()} in sources+ assert not [item for item in sources if item["kind"] == "eval_md"]++[email protected]("entrypoint", ["direct", "service", "cli"])+def test_auto_keeps_existing_dataset_without_explicit_refinement(tmp_path, monkeypatch, entrypoint):+ skill = _skill(tmp_path, "\n")+ output = skill / "evals" / "evals.json"+ original = (+ b'{"skill_name":"sample-skill","evals":'+ b'[{"id":"authored","prompt":"Reconcile","expected_output":"Keep","assertions":["Keep"]}]}\n'+ )+ output.write_bytes(original)+ _trace(skill, tmp_path / "results", case_id="authored")+ monkeypatch.setenv("SKILLEVALUATOR_RESULTS_DIR", str(tmp_path / "results"))+ monkeypatch.setattr(generate_dataset, "_generate_with_llm", _forbid_generation)+ monkeypatch.setattr(generate_dataset, "_run_agent_collect_trajectories", _forbid_generation)++ if entrypoint == "direct":+ result = generate_dataset.main([str(skill), "--no-llm"])+ assert result.status == "unchanged"+ elif entrypoint == "service":+ result = EvaluationService().create_dataset(DatasetOptions(skill_path=skill, no_llm=True))+ assert result.status == "unchanged"+ else:+ result = CliRunner().invoke(cli, ["create-eval-dataset", str(skill), "--no-llm"])+ assert result.exit_code == 0, result.output+ assert "Dataset already exists" in result.output+ assert output.read_bytes() == original+++def test_auto_unchanged_dataset_does_not_parse_the_skill(tmp_path, monkeypatch):+ skill = _skill(tmp_path, "\n")+ output = skill / "evals" / "evals.json"+ original = b'{"evals": []}'+ output.write_bytes(original)+ monkeypatch.setattr(generate_dataset, "_parse_skill", _forbid_generation)++ result = generate_dataset.main([str(skill)])++ assert result.status == "unchanged"+ assert output.read_bytes() == original++[email protected]("use_llm", [False, True])[email protected]("authored", [False, True])+def test_auto_trace_keeps_skill_use_out_of_new_expected_outputs(tmp_path, monkeypatch, use_llm, authored):+ skill = _skill(tmp_path, "\n")+ observed = "Using the sample-skill skill I read SKILL.md and ran reconcile.py: 42 invoices reconciled"+ if authored:+ (skill / "evals" / "evals.json").write_text(+ json.dumps(+ {+ "skill_name": "sample-skill",+ "evals": [{"id": "sample-skill-001", "prompt": "Reconcile", "expected_output": observed}],+ }+ )+ )+ _trace(skill, tmp_path / "results", steps=[{"source": "agent", "message": observed}])+ monkeypatch.setenv("SKILLEVALUATOR_RESULTS_DIR", str(tmp_path / "results"))++ async def refine(_skill, cases, _trajectories, **_kwargs):+ return [{**case, "ground_truth": observed} for case in cases]++ monkeypatch.setattr(generate_dataset, "_refine_with_llm", refine)+ result = generate_dataset.main(+ [str(skill), *([] if use_llm else ["--no-llm"]), *(["--refine"] if authored else [])]+ )++ case = result.dataset["evals"][0]+ assert case["expected_output"] == (observed if authored else "")+ if not authored:+ assert any("skill use" in reason for reason in case["review"]["reasons"])+ assert case["review"]["status"] == "needs_review"+++ ("proposed", "reason"),+ [+ ({"summary": ["The agent read SKILL.md"]}, "skill use"),+ ({"The agent read SKILL.md": "42 reconciled"}, "skill use"),+ (["42 reconciled"] * 1001, "fully checked"),+ ({"summary": ["42 invoices reconciled"]}, None),+ ],+)[email protected]("authored", [False, True])+def test_auto_tool_only_trace_checks_nested_inferred_outcomes(tmp_path, monkeypatch, proposed, reason, authored):+ from types import SimpleNamespace++ from skillevaluator.inference import client as inference_client++ skill = _skill(tmp_path, "\n")+ case_id = "sample-skill-001"+ if authored:+ (skill / "evals" / "evals.json").write_text(+ json.dumps(+ {+ "skill_name": "sample-skill",+ "evals": [{"id": case_id, "prompt": "Reconcile", "expected_output": proposed}],+ }+ )+ )+ _trace(+ skill,+ tmp_path / "results",+ steps=[{"source": "agent", "tool_calls": [{"function_name": "bash", "arguments": {"command": "true"}}]}],+ )+ monkeypatch.setenv("SKILLEVALUATOR_RESULTS_DIR", str(tmp_path / "results"))++ class FakeLLMClient:+ def __init__(self, **_kwargs):+ pass++ def completions(self, *_args):+ return json.dumps([{"id": case_id, "ground_truth": proposed, "expected_behavior": []}])++ monkeypatch.setattr(+ "skillevaluator.provider_config.resolve_llm_provider", lambda: SimpleNamespace(provider="test", model="test")+ )+ monkeypatch.setattr(inference_client, "LLMClient", FakeLLMClient)++ result = generate_dataset.main([str(skill), *(["--refine"] if authored else [])])++ case = result.dataset["evals"][0]+ assert result.dataset["generation"]["mode"] == "llm"+ assert case["expected_output"] == ("" if reason and not authored else proposed)+ if reason and not authored:+ assert case["review"]["status"] == "needs_review"+ assert any(reason in value for value in case["review"]["reasons"])+++ "proposed",+ [+ "The agent read SKILL.md and used the sample-skill skill.",+ {"summary": ["The agent read SKILL.md and used the sample-skill skill."]},+ [{"The agent read SKILL.md": {"answer": "42 invoices reconciled"}}],+ ],+ ids=["string", "nested-values", "nested-keys"],+)[email protected]("authored", [False, True])+def test_auto_partial_trace_checks_unmatched_inferred_outcomes(tmp_path, monkeypatch, proposed, authored):+ from skillevaluator.inference.client import LLMClient++ skill = _skill(tmp_path, "\n")+ output = skill / "evals" / "evals.json"+ if authored:+ output.write_text(+ json.dumps(+ {+ "skill_name": skill.name,+ "owner": "human",+ "evals": [+ {"id": "sample-skill-001", "prompt": "Reconcile invoice one", "expected_output": "Keep"},+ {+ "id": "sample-skill-002",+ "prompt": "Reconcile invoice two",+ "expected_output": proposed,+ "assertions": ["Keep the authored acceptance criterion"],+ "files": ["files/invoice-two.csv"],+ },+ ],+ }+ )+ )+ source = _trace(skill, tmp_path / "results")+ monkeypatch.setenv("SKILLEVALUATOR_RESULTS_DIR", str(tmp_path / "results"))+ monkeypatch.setenv("SKILL_EVAL_LLM_PROVIDER", "openai")+ monkeypatch.setenv("OPENAI_API_KEY", "test-key")++ def complete(*_args, **_kwargs):+ return json.dumps(+ [+ {+ "id": f"sample-skill-{number:03}",+ "question": f"Reconcile invoice {number}",+ "expected_skill": skill.name,+ "ground_truth": proposed if number == 2 else "42 invoices reconciled",+ "expected_behavior": ["Reports the invoice totals"],+ }+ for number in (1, 2, 3)+ ]+ )++ monkeypatch.setattr(LLMClient, "completions", complete)+ result = generate_dataset.main([str(skill), "--full", *(["--refine"] if authored else [])])++ dataset = json.loads(output.read_text())+ case = next(case for case in dataset["evals"] if case["id"] == "sample-skill-002")+ assert result.dataset == dataset+ assert dataset["generation"]["grounding"] == "trace"+ assert dataset["generation"]["mode"] == "llm"+ assert {+ "kind": "trajectory",+ "path": "trajectory.json",+ "sha256": hashlib.sha256(source.read_bytes()).hexdigest(),+ } in dataset["generation"]["inputs"]+ assert "no matching retained trajectory for this case" in case["review"]["reasons"]+ assert case["expected_output"] == (proposed if authored else "")+ if authored:+ assert "Keep the authored acceptance criterion" in case["assertions"]+ assert case["files"] == ["files/invoice-two.csv"]+ assert dataset["owner"] == "human"+ else:+ assert any("skill use" in reason for reason in case["review"]["reasons"])+ validation = CliRunner().invoke(cli, ["tier3", "validate", str(skill), "--strict", "--json"])+ assert validation.exit_code == 0, validation.output++[email protected]("retained_trace", [False, True])+def test_auto_does_not_treat_headings_alone_as_author_guidance(tmp_path, monkeypatch, retained_trace):+ skill = _skill(tmp_path, "# Evaluation\n\n## Questions\n\n## Behaviors\n\n## Notes\n")+ monkeypatch.setenv("SKILLEVALUATOR_RESULTS_DIR", str(tmp_path / "results"))+ if retained_trace:+ _trace(skill, tmp_path / "results")+ result = generate_dataset.main([str(skill), "--no-llm"])+ assert result.dataset["generation"]["grounding"] == "trace"+ else:+ with pytest.raises(DatasetGenerationError, match="--grounding auto requires"):+ generate_dataset.main([str(skill), "--no-llm"])+ assert not (skill / "evals" / "evals.json").exists()+++def test_auto_force_invalid_dataset_explains_the_explicit_starter_option(tmp_path, monkeypatch):+ skill = _skill(tmp_path, "\n")+ output = skill / "evals" / "evals.json"+ original = b"{}"+ output.write_bytes(original)+ monkeypatch.setenv("SKILLEVALUATOR_RESULTS_DIR", str(tmp_path / "absent"))++ with pytest.raises(DatasetGenerationError) as error:+ generate_dataset.main([str(skill), "--no-llm", "--force"])++ assert "--grounding skill --force" in str(error.value)+ assert output.read_bytes() == original++[email protected]("authored_output", [42, 0, False, {"answer": 42}, ["42"]])+def test_auto_refine_preserves_typed_authored_expected_outputs(tmp_path, monkeypatch, authored_output):+ skill = _skill(tmp_path, "\n")+ (skill / "evals" / "evals.json").write_text(+ json.dumps(+ {+ "skill_name": "sample-skill",+ "evals": [{"id": "authored", "prompt": "Reconcile", "expected_output": authored_output}],+ }+ )+ )+ _trace(skill, tmp_path / "results", case_id="authored")+ monkeypatch.setenv("SKILLEVALUATOR_RESULTS_DIR", str(tmp_path / "results"))++ result = generate_dataset.main([str(skill), "--no-llm", "--refine"])++ assert result.dataset["evals"][0]["expected_output"] == authored_output++[email protected]("options", [[], ["--refine"], ["--no-llm"], ["--no-llm", "--refine", "--force"]])+def test_auto_missing_input_fails_before_provider_collection_or_writes(tmp_path, monkeypatch, options):+ skill = _skill(tmp_path, " \n\t")+ monkeypatch.setattr(generate_dataset, "_generate_with_llm", _forbid_generation)+ monkeypatch.setattr(generate_dataset, "_run_agent_collect_trajectories", _forbid_generation)+ monkeypatch.setenv("SKILLEVALUATOR_RESULTS_DIR", str(tmp_path / "absent"))++ with pytest.raises(DatasetGenerationError, match="--grounding auto requires") as error:+ generate_dataset.main([str(skill), *options])++ for recovery in ("EVAL.md", "--prompt", "trace", "--grounding skill"):+ assert recovery in str(error.value)+ assert not (skill / "evals" / "evals.json").exists()+ assert sorted(path.name for path in (skill / "evals").iterdir()) == ["EVAL.md"]++[email protected]("source_option", ["env", "--results-dir", "--from-results"])+def test_auto_falls_back_to_matching_retained_trace_and_flags_observation(tmp_path, monkeypatch, source_option):+ skill = _skill(tmp_path, "\n")+ source = _trace(skill, tmp_path / "results")+ monkeypatch.setattr(generate_dataset, "_generate_with_llm", _forbid_generation)+ options = []+ if source_option == "env":+ monkeypatch.setenv("SKILLEVALUATOR_RESULTS_DIR", str(tmp_path / "results"))+ else:+ options = [+ source_option,+ str(tmp_path / "results") if source_option == "--results-dir" else str(source.parents[4]),+ ]++ result = generate_dataset.main([str(skill), "--no-llm", *options])++ generation = result.dataset["generation"]+ assert generation["grounding"] == "trace"+ assert generation["refined"] is True+ assert generation["review_state"] == "needs_review"+ assert {+ "kind": "trajectory",+ "path": "trajectory.json",+ "sha256": hashlib.sha256(source.read_bytes()).hexdigest(),+ } in generation["inputs"]+ case = result.dataset["evals"][0]+ assert case["id"] == "sample-skill-001"+ assert case["expected_output"] == "Reconciled 42 invoices; three mismatches were recorded."+ assert case["review"]["status"] == "needs_review"+++ "steps", [[], [{}], [{"source": "user", "message": "Do the task"}], [{"source": "agent", "message": " "}]]+)+def test_auto_rejects_empty_or_non_agent_trace_evidence(tmp_path, monkeypatch, steps):+ skill = _skill(tmp_path)+ _trace(skill, tmp_path / "results", steps=steps)+ monkeypatch.setenv("SKILLEVALUATOR_RESULTS_DIR", str(tmp_path / "results"))++ with pytest.raises(DatasetGenerationError, match="--grounding auto requires"):+ generate_dataset.main([str(skill), "--no-llm"])+ assert not (skill / "evals" / "evals.json").exists()+++def test_auto_rejects_unmatched_case_ids_before_generation(tmp_path, monkeypatch):+ skill = _skill(tmp_path)+ _trace(skill, tmp_path / "results", case_id="unrelated")+ monkeypatch.setenv("SKILLEVALUATOR_RESULTS_DIR", str(tmp_path / "results"))+ monkeypatch.setattr(generate_dataset, "_generate_with_llm", _forbid_generation)++ with pytest.raises(DatasetGenerationError, match="--grounding auto requires"):+ generate_dataset.main([str(skill)])+ assert not (skill / "evals" / "evals.json").exists()+++def test_auto_rejects_foreign_explicit_results_even_with_matching_case_id(tmp_path):+ skill = _skill(tmp_path)+ source = _trace(skill, tmp_path / "results", skill_name="another-skill")++ with pytest.raises(DatasetGenerationError, match="--grounding auto requires"):+ generate_dataset.main([str(skill), "--no-llm", "--from-results", str(source.parents[4])])+ assert not (skill / "evals" / "evals.json").exists()+++def test_auto_trace_preserves_authored_cases_and_flags_unmatched_coverage(tmp_path, monkeypatch):+ skill = _skill(tmp_path, "\n")+ dataset = skill / "evals" / "evals.json"+ dataset.write_text(+ json.dumps(+ {+ "skill_name": "sample-skill",+ "evals": [+ {+ "id": "authored",+ "prompt": "Check this invoice",+ "expected_output": "Correct authored answer",+ "assertions": ["Keep authored behavior"],+ },+ {+ "id": "unmatched",+ "prompt": "Check another invoice",+ "expected_output": "Another authored answer",+ },+ ],+ }+ )+ )+ source = _trace(skill, tmp_path / "results", case_id="authored")+ monkeypatch.setenv("SKILLEVALUATOR_RESULTS_DIR", str(tmp_path / "results"))++ result = generate_dataset.main([str(skill), "--no-llm", "--refine"])++ assert [case["id"] for case in result.dataset["evals"]] == ["authored", "unmatched"]+ first, second = result.dataset["evals"]+ assert first["expected_output"] == "Correct authored answer"+ assert "Keep authored behavior" in first["assertions"]+ assert second["expected_output"] == "Another authored answer"+ assert second["review"]["status"] == "needs_review"+ assert "no matching retained trajectory for this case" in second["review"]["reasons"]+ assert result.dataset["generation"]["needs_review_count"] == 2+ assert hashlib.sha256(source.read_bytes()).hexdigest() in json.dumps(result.dataset["generation"])+++def test_auto_intent_refine_retains_collection_compatibility(tmp_path, monkeypatch):+ skill = _skill(tmp_path, "## Questions\n- Check this invoice\n")+ monkeypatch.setattr(generate_dataset, "_discover_trajectories", lambda *_args, **_kwargs: ({}, {}))+ monkeypatch.setattr(generate_dataset, "_run_agent_collect_trajectories", lambda *_args, **_kwargs: ({}, {}))++ result = generate_dataset.main([str(skill), "--no-llm", "--refine"])++ assert result.dataset["generation"]["grounding"] == "intent"+ assert result.dataset["evals"][0]["prompt"] == "Check this invoice"++[email protected]("entrypoint", ["service", "cli", "tier3-cli"])+def test_guided_default_is_shared_by_cli_and_service(tmp_path, entrypoint):+ skill = _skill(tmp_path)+ if entrypoint == "service":+ with pytest.raises(DatasetGenerationError, match="--grounding auto requires"):+ EvaluationService().create_dataset(DatasetOptions(skill_path=skill, no_llm=True))+ else:+ command = ["tier3"] if entrypoint == "tier3-cli" else []+ result = CliRunner().invoke(cli, [*command, "create-eval-dataset", str(skill), "--no-llm"])+ assert result.exit_code == 1+ assert "--grounding auto requires" in result.output+ assert not (skill / "evals" / "evals.json").exists()+++def test_service_explicit_skill_preserves_legacy_template_workflow(tmp_path):+ skill = _skill(tmp_path)++ result = EvaluationService().create_dataset(DatasetOptions(skill_path=skill, no_llm=True, grounding="skill"))++ assert result.dataset["generation"]["grounding"] == "skill"+ assert result.path.is_file()+++def test_auto_missing_input_preserves_existing_dataset_when_forced(tmp_path, monkeypatch):+ skill = _skill(tmp_path, "\n")+ output = skill / "evals" / "evals.json"+ original = b'{"skill_name":"sample-skill","evals":[{"id":"authored","prompt":"Check","expected_output":"Keep"}]}'+ output.write_bytes(original)+ monkeypatch.setattr(generate_dataset, "_generate_with_llm", _forbid_generation)+ monkeypatch.setattr(generate_dataset, "_run_agent_collect_trajectories", _forbid_generation)++ with pytest.raises(DatasetGenerationError, match="--grounding auto requires"):+ generate_dataset.main([str(skill), "--force", "--refine"])+ assert output.read_bytes() == original+++def test_auto_trace_does_not_regenerate_ids_before_llm_refinement(tmp_path, monkeypatch):+ skill = _skill(tmp_path)+ _trace(skill, tmp_path / "results")+ monkeypatch.setenv("SKILLEVALUATOR_RESULTS_DIR", str(tmp_path / "results"))+ monkeypatch.setattr(generate_dataset, "_generate_with_llm", _forbid_generation)+ monkeypatch.setattr(generate_dataset, "_run_agent_collect_trajectories", _forbid_generation)++ async def refine(parsed, cases, trajectories, **kwargs):+ return generate_dataset._refine_from_trajectory_template(cases, trajectories, skill=parsed, **kwargs)++ monkeypatch.setattr(generate_dataset, "_refine_with_llm", refine)++ result = generate_dataset.main([str(skill)])++ assert result.dataset["generation"]["grounding"] == "trace"+ assert result.dataset["evals"][0]["id"] == "sample-skill-001"+ assert result.dataset["evals"][0]["review"]["status"] == "needs_review"+++def test_auto_rejects_incomplete_run_and_conflicting_skill_identity(tmp_path, monkeypatch):+ skill = _skill(tmp_path)+ source = _trace(skill, tmp_path / "results")+ run = source.parents[4]+ monkeypatch.setenv("SKILLEVALUATOR_RESULTS_DIR", str(tmp_path / "results"))+ (run / "result.json").write_text(json.dumps({"run_id": run.name, "skill_name": "another-skill"}))+ with pytest.raises(DatasetGenerationError, match="--grounding auto requires"):+ generate_dataset.main([str(skill), "--no-llm"])+ (run / "result.json").unlink()+ with pytest.raises(DatasetGenerationError, match="--grounding auto requires"):+ generate_dataset.main([str(skill), "--no-llm"])+ assert not (skill / "evals" / "evals.json").exists()++[email protected]("tool_calls", [7, True, {"function_name": "bash"}, "bash"])+def test_auto_ignores_malformed_tool_call_steps(tmp_path, monkeypatch, tool_calls):+ skill = _skill(tmp_path)+ _trace(skill, tmp_path / "results", steps=[{"source": "agent", "tool_calls": tool_calls}])+ monkeypatch.setenv("SKILLEVALUATOR_RESULTS_DIR", str(tmp_path / "results"))++ with pytest.raises(DatasetGenerationError, match="--grounding auto requires"):+ generate_dataset.main([str(skill), "--no-llm"])+++def test_auto_existing_empty_dataset_is_unchanged_without_force(tmp_path):+ skill = _skill(tmp_path, "\n")+ output = skill / "evals" / "evals.json"+ original = '{"skill_name":"sample-skill","evals":[]}'+ output.write_text(original)++ result = generate_dataset.main([str(skill), "--no-llm"])++ assert result.status == "unchanged"+ assert output.read_text() == original++[email protected]("message", [7, {"text": "not ATIF content"}, [{"type": "image", "source": "/tmp/image.png"}]])+def test_auto_requires_text_or_tool_actions_beyond_placeholder_messages(tmp_path, monkeypatch, message):+ skill = _skill(tmp_path)+ _trace(skill, tmp_path / "results", steps=[{"source": "agent", "message": message}])+ monkeypatch.setenv("SKILLEVALUATOR_RESULTS_DIR", str(tmp_path / "results"))++ with pytest.raises(DatasetGenerationError, match="--grounding auto requires"):+ generate_dataset.main([str(skill), "--no-llm"])++[email protected]("higher_case_id", ["unrelated", "sample-skill-001"])+def test_auto_searches_past_an_agent_without_usable_matching_evidence(tmp_path, monkeypatch, higher_case_id):+ skill = _skill(tmp_path)+ source = _trace(+ skill,+ tmp_path / "results",+ case_id=higher_case_id,+ steps=[+ {"source": "agent" if higher_case_id == "unrelated" else "user", "message": "This is only the user request"}+ ],+ )+ fallback = source.parents[4] / "codex" / "with-skill" / "trials" / "sample-skill-001" / "trajectory.json"+ fallback.parent.mkdir(parents=True)+ fallback.write_text(+ json.dumps({"steps": [{"source": "agent", "message": "Reconciled all invoices; the totals now match."}]})+ )+ monkeypatch.setenv("SKILLEVALUATOR_RESULTS_DIR", str(tmp_path / "results"))++ result = generate_dataset.main([str(skill), "--no-llm"])++ assert result.dataset["generation"]["grounding"] == "trace"+ hashes = [item["sha256"] for item in result.dataset["generation"]["inputs"] if item["kind"] == "trajectory"]+ assert hashes == [hashlib.sha256(fallback.read_bytes()).hexdigest()]+ assert result.dataset["evals"][0]["expected_output"] == "Reconciled all invoices; the totals now match."++[email protected]("use_llm", [False, True])[email protected]("wrapper", ["evals", "cases"])+def test_auto_trace_preserves_authored_prompt_metadata_and_review_history(tmp_path, monkeypatch, use_llm, wrapper):+ from types import SimpleNamespace++ from skillevaluator.inference import client as inference_client++ skill = _skill(tmp_path, "\n")+ output = skill / "evals" / "evals.json"+ output.write_text(+ json.dumps(+ {+ "skill_name": "sample-skill",+ "dataset_version": "author-v2",+ "source": {"kind": "reviewed_import"},+ wrapper: [+ {+ "id": "authored",+ "prompt": "Check this exact authored invoice",+ "expected_output": "Authored answer",+ "expected_skill": "sample-skill",+ "assertions": ["Keep authored behavior"],+ "files": ["files/invoice.csv"],+ "behavior_checks": [{"kind": "final_response", "pattern": "total"}],+ "review": {"status": "needs_review", "reasons": ["Original reviewer concern"]},+ }+ ],+ }+ )+ )+ original_hash = hashlib.sha256(output.read_bytes()).hexdigest()+ _trace(skill, tmp_path / "results", case_id="authored")+ monkeypatch.setenv("SKILLEVALUATOR_RESULTS_DIR", str(tmp_path / "results"))++ class FakeLLMClient:+ def __init__(self, **_kwargs):+ pass++ def completions(self, *_args):+ return json.dumps(+ [+ {+ "id": "authored",+ "question": "Changed prompt from model",+ "ground_truth": "Changed expected answer",+ "expected_skill": "different-skill",+ "expected_behavior": ["Keep authored behavior"],+ }+ ]+ )++ monkeypatch.setattr(+ "skillevaluator.provider_config.resolve_llm_provider", lambda: SimpleNamespace(provider="test", model="test")+ )+ monkeypatch.setattr(inference_client, "LLMClient", FakeLLMClient)++ result = generate_dataset.main([str(skill), "--refine", *([] if use_llm else ["--no-llm"])])++ case = result.dataset["evals"][0]+ assert case["prompt"] == "Check this exact authored invoice"+ assert case["expected_output"] == "Authored answer"+ assert case["expected_skill"] == "sample-skill"+ assert case["files"] == ["files/invoice.csv"]+ assert case["behavior_checks"] == [{"kind": "final_response", "pattern": "total"}]+ assert "Original reviewer concern" in case["review"]["reasons"]+ assert result.dataset["dataset_version"] == "author-v2"+ assert result.dataset["source"] == {"kind": "reviewed_import"}+ assert "cases" not in result.dataset+ assert result.dataset["generation"]["grounding"] == "trace"+ assert result.dataset["generation"]["mode"] == ("llm" if use_llm else "template_requested")+ assert {"kind": "dataset", "path": "evals/evals.json", "sha256": original_hash} in result.dataset["generation"][+ "inputs"+ ]+++ "filename", ["trajectory.json", "claude-code.txt", "cursor-cli.txt", "cline.txt", "opencode.txt", "codex.txt"]+)+def test_auto_rejects_nonregular_trace_sources_before_reading(tmp_path, monkeypatch, filename):+ import os+ from pathlib import Path++ skill = _skill(tmp_path)+ source = _trace(skill, tmp_path / "results")+ source.unlink()+ blocked = source.parent / filename+ os.mkfifo(blocked)+ monkeypatch.setenv("SKILLEVALUATOR_RESULTS_DIR", str(tmp_path / "results"))+ original_read = Path.read_text++ def guarded_read(path, *args, **kwargs):+ if path == blocked:+ pytest.fail("auto discovery must reject a FIFO before attempting to read it")+ return original_read(path, *args, **kwargs)++ monkeypatch.setattr(Path, "read_text", guarded_read)+ with pytest.raises(DatasetGenerationError, match="--grounding auto requires"):+ generate_dataset.main([str(skill), "--no-llm"])+ assert not (skill / "evals" / "evals.json").exists()++[email protected]("relative", ["reward.json", "verifier/reward.json", "result.json"])+def test_auto_rejects_linked_case_identity_before_reading(tmp_path, monkeypatch, relative):+ from pathlib import Path++ skill = _skill(tmp_path)+ source = _trace(skill, tmp_path / "results")+ outside = tmp_path / "foreign-result.json"+ outside.write_text(json.dumps({"entry_id": "sample-skill-001"}))+ linked = source.parent / relative+ linked.parent.mkdir(exist_ok=True)+ linked.symlink_to(outside)+ monkeypatch.setenv("SKILLEVALUATOR_RESULTS_DIR", str(tmp_path / "results"))+ original_read = Path.read_text++ def guarded_read(path, *args, **kwargs):+ if path == linked:+ pytest.fail("auto discovery must reject linked identity inputs before reading them")+ return original_read(path, *args, **kwargs)++ monkeypatch.setattr(Path, "read_text", guarded_read)+ with pytest.raises(DatasetGenerationError, match="--grounding auto requires"):+ generate_dataset.main([str(skill), "--no-llm"])+ assert not (skill / "evals" / "evals.json").exists()++[email protected]("existing_authored", [False, True])+ ("provider_behavior", "expected_reason"),+ [+ ("unconfigured", "public LLM provider is not configured"),+ (+ "request_failure",+ "Unexpected LLM request error. Check the selected provider and model configuration, then retry.",+ ),+ ],+)+def test_cli_auto_trace_fallback_records_template_mode_and_preserves_sources(+ tmp_path,+ monkeypatch,+ existing_authored,+ provider_behavior,+ expected_reason,+):+ from skillevaluator.inference import client as inference_client+ from skillevaluator.provider_config import resolve_llm_provider+ from skillevaluator.tier3.dataset_provenance import dataset_provenance_display++ skill = _skill(tmp_path)+ source = _trace(skill, tmp_path / "results")+ output = skill / "evals" / "evals.json"+ original_hash = None+ if existing_authored:+ output.parent.mkdir()+ output.write_text(+ json.dumps(+ {+ "skill_name": skill.name,+ "dataset_version": "author-v3",+ "source": {"kind": "authored"},+ "evals": [+ {+ "id": "sample-skill-001",+ "prompt": "Keep this authored invoice task",+ "expected_output": "Keep this independent human expectation",+ "expected_skill": skill.name,+ "assertions": ["Keep the authored acceptance behavior"],+ "files": ["files/invoice.csv"],+ "review": {"status": "needs_review", "reasons": ["Keep the original review concern"]},+ }+ ],+ }+ )+ )+ original_hash = hashlib.sha256(output.read_bytes()).hexdigest()++ def resolve_provider():+ environment = {"SKILL_EVAL_LLM_PROVIDER": "openai"}+ if provider_behavior != "unconfigured":+ environment["OPENAI_API_KEY"] = "test-provider-key"+ return resolve_llm_provider(environment)++ class FailingClient:+ def __init__(self, **_kwargs):+ pass++ def completions(self, *_args):+ if provider_behavior == "unconfigured":+ pytest.fail("unconfigured provider must not attempt inference")+ raise RuntimeError("private-provider-detail")++ monkeypatch.setattr("skillevaluator.provider_config.resolve_llm_provider", resolve_provider)+ monkeypatch.setattr(inference_client, "LLMClient", FailingClient)+ result = CliRunner().invoke(+ cli,+ [+ "create-eval-dataset",+ str(skill),+ "--results-dir",+ str(tmp_path / "results"),+ *(["--refine"] if existing_authored else []),+ ],+ )++ assert result.exit_code == 0, result.output+ dataset = json.loads(output.read_text())+ generation = dataset["generation"]+ assert generation["mode"] == "template_fallback"+ assert generation["grounding"] == "trace"+ assert generation["fallback_reason"] == expected_reason+ assert generation["refined"] is True+ assert generation["review_state"] == "needs_review"+ assert "private-provider-detail" not in json.dumps(generation)+ assert "private-provider-detail" not in result.output+ assert hashlib.sha256(source.read_bytes()).hexdigest() in json.dumps(generation["inputs"])+ case = dataset["evals"][0]+ assert case["review"]["status"] == "needs_review"+ if existing_authored:+ assert case["prompt"] == "Keep this authored invoice task"+ assert case["expected_output"] == "Keep this independent human expectation"+ assert "Keep the authored acceptance behavior" in case["assertions"]+ assert case["files"] == ["files/invoice.csv"]+ assert "Keep the original review concern" in case["review"]["reasons"]+ assert dataset["dataset_version"] == "author-v3"+ assert dataset["source"] == {"kind": "authored"}+ assert {"kind": "dataset", "path": "evals/evals.json", "sha256": original_hash} in generation["inputs"]+ else:+ assert "expected outcome taken from an observed run; confirm it is correct" in case["review"]["reasons"]+ display, warning = dataset_provenance_display(generation)+ assert "generated from templates (fallback:" in display+ assert expected_reason in display+ assert warning is True++[email protected]("options", [[], ["--no-llm"]])+def test_auto_existing_matching_trace_requires_explicit_write_authorization(tmp_path, monkeypatch, options):+ from skillevaluator.inference.client import LLMClient++ skill = _skill(tmp_path, "\n")+ output = skill / "evals" / "evals.json"+ original = b'{"skill_name":"sample-skill","evals":[{"id":"authored","prompt":"Check","expected_output":"Keep","assertions":["Keep this assertion"]}]}\n'+ output.write_bytes(original)+ output.chmod(0o640)+ before = output.stat()+ _trace(skill, tmp_path / "results", case_id="authored")+ monkeypatch.setenv("SKILLEVALUATOR_RESULTS_DIR", str(tmp_path / "results"))+ monkeypatch.setenv("SKILL_EVAL_LLM_PROVIDER", "openai")+ monkeypatch.setenv("OPENAI_API_KEY", "test-key")+ provider_calls = []++ def complete(*_args, **_kwargs):+ provider_calls.append(True)+ raise RuntimeError("unchanged datasets must not need inference")++ monkeypatch.setattr(LLMClient, "completions", complete)+ result = CliRunner().invoke(cli, ["create-eval-dataset", str(skill), *options])++ assert result.exit_code == 0, result.output+ assert "Dataset already exists" in result.output+ assert "matching" in result.output.lower() and "trace" in result.output.lower()+ assert "--refine" in result.output+ assert output.read_bytes() == original+ assert output.stat().st_mode & 0o777 == 0o640+ assert output.stat().st_mtime_ns == before.st_mtime_ns+ assert output.stat().st_ino == before.st_ino+ assert provider_calls == []++[email protected]("grounding", ["auto", "skill", "intent"])+def test_existing_dataset_noop_precedes_skill_and_guidance_reads(tmp_path, grounding):+ skill = _skill(tmp_path, "ignored")+ output = skill / "evals" / "evals.json"+ output.write_bytes(b"{}\n")+ output.chmod(0o600)+ (skill / "SKILL.md").write_bytes(b"\xff")+ (skill / "evals" / "EVAL.md").write_bytes(b"\xff")+ prompt = tmp_path / "unreadable-guidance.md"+ prompt.write_bytes(b"\xff")++ result = generate_dataset.main([str(skill), "--grounding", grounding, "--prompt", str(prompt)])++ assert result.status == "unchanged"+ assert output.read_bytes() == b"{}\n"+ assert output.stat().st_mode & 0o777 == 0o600++[email protected]("original", [b"{}", b"not json"])+def test_auto_force_invalid_existing_dataset_gives_auto_recovery(tmp_path, original):+ skill = _skill(tmp_path, "\n")+ output = skill / "evals" / "evals.json"+ output.write_bytes(original)+ output.chmod(0o640)++ with pytest.raises(DatasetGenerationError) as error:+ generate_dataset.main([str(skill), "--no-llm", "--force"])++ assert "--grounding auto requires" in str(error.value)+ assert "--grounding skill --force" in str(error.value)+ assert "--prompt" in str(error.value)+ assert "--grounding trace" not in str(error.value)+ assert output.read_bytes() == original+ assert output.stat().st_mode & 0o777 == 0o640++[email protected]("source", ["eval_md", "prompt"])+ "guidance",+ [+ "# Evaluation\n## Questions\n## Behaviors\n",+ "<!-- Add intent here -->\n",+ "# Evaluation\n<!-- multi\nline -->\n## Notes\n",+ ],+)+def test_auto_rejects_heading_and_comment_only_guidance(tmp_path, monkeypatch, source, guidance):+ from skillevaluator.inference.client import LLMClient++ skill = _skill(tmp_path, guidance if source == "eval_md" else None)+ options = []+ if source == "prompt":+ prompt = tmp_path / "intent.md"+ prompt.write_text(guidance)+ options = ["--prompt", str(prompt)]+ monkeypatch.setenv("SKILLEVALUATOR_RESULTS_DIR", str(tmp_path / "absent"))+ provider_calls = []++ def complete(*_args, **_kwargs):+ provider_calls.append(True)+ raise RuntimeError("missing intent must be rejected before inference")++ monkeypatch.setattr(LLMClient, "completions", complete)+ before = {p.relative_to(skill): p.read_bytes() for p in skill.rglob("*") if p.is_file()}+ with pytest.raises(DatasetGenerationError, match="--grounding auto requires"):+ generate_dataset.main([str(skill), *options])++ assert {p.relative_to(skill): p.read_bytes() for p in skill.rglob("*") if p.is_file()} == before+ assert provider_calls == []++[email protected]("use_llm", [False, True])+ "authored_truth",+ [+ None,+ "The agent used the sample-skill skill; keep this human expectation",+ {"answer": 42},+ [42],+ 0,+ False,+ [],+ {},+ {"answer": {"steps": [42, 0, False, "Read SKILL.md"]}},+ ],+ ids=["inferred", "string", "dict", "list", "zero", "false", "empty-list", "empty-dict", "nested"],+)+def test_auto_trace_filters_only_inferred_skill_use_ground_truth(tmp_path, monkeypatch, use_llm, authored_truth):+ from skillevaluator.inference.client import LLMClient++ skill = _skill(tmp_path, "\n")+ (skill / "scripts").mkdir()+ (skill / "scripts" / "reconcile.py").write_text("print('42 invoices reconciled')\n")+ output = skill / "evals" / "evals.json"+ original_hash = None+ if authored_truth is not None:+ output.write_text(+ json.dumps(+ {+ "skill_name": skill.name,+ "owner": "human",+ "evals": [+ {+ "id": "sample-skill-001",+ "prompt": "Reconcile these invoices",+ "expected_output": authored_truth,+ "assertions": ["The agent read SKILL.md"],+ "files": ["files/invoices.csv"],+ }+ ],+ }+ )+ )+ original_hash = hashlib.sha256(output.read_bytes()).hexdigest()+ source = _trace(+ skill,+ tmp_path / "results",+ steps=[+ {+ "source": "agent",+ "message": "Using the sample-skill skill I read SKILL.md and ran reconcile.py: 42 invoices reconciled",+ }+ ],+ )+ monkeypatch.setenv("SKILLEVALUATOR_RESULTS_DIR", str(tmp_path / "results"))+ monkeypatch.setenv("SKILL_EVAL_LLM_PROVIDER", "openai")+ monkeypatch.setenv("OPENAI_API_KEY", "test-key")++ def complete(*_args, **_kwargs):+ return json.dumps(+ [+ {+ "id": "sample-skill-001",+ "question": "Reconcile these invoices",+ "expected_skill": skill.name,+ "expected_script": "reconcile.py",+ "ground_truth": "The agent used the sample-skill skill and reconciled 42 invoices",+ "expected_behavior": ["Reports the invoice total"],+ }+ ]+ )++ monkeypatch.setattr(LLMClient, "completions", complete)+ result = generate_dataset.main(+ [str(skill), *([] if use_llm else ["--no-llm"]), *(["--refine"] if authored_truth is not None else [])]+ )++ case = json.loads(output.read_text())["evals"][0]+ assert result.dataset["generation"]["mode"] == ("llm" if use_llm else "template_requested")+ assert result.dataset["generation"]["review_state"] == "needs_review"+ assert {+ "kind": "trajectory",+ "path": "trajectory.json",+ "sha256": hashlib.sha256(source.read_bytes()).hexdigest(),+ } in result.dataset["generation"]["inputs"]+ if authored_truth is None:+ assert case["expected_output"] == ""+ assert any("skill use" in reason for reason in case["review"]["reasons"])+ validation = CliRunner().invoke(cli, ["tier3", "validate", str(skill), "--strict", "--json"])+ assert validation.exit_code == 0, validation.output+ else:+ assert case["expected_output"] == authored_truth+ assert type(case["expected_output"]) is type(authored_truth)+ assert "The agent read SKILL.md" in case["assertions"]+ assert case["files"] == ["files/invoices.csv"]+ assert result.dataset["owner"] == "human"+ assert {"kind": "dataset", "path": "evals/evals.json", "sha256": original_hash} in result.dataset["generation"][+ "inputs"+ ]diff --git a/tests/tier3/test_dataset_baseline_fairness.py b/tests/tier3/test_dataset_baseline_fairness.pynew file mode 100644index 00000000..99dc174d--- /dev/null+++ b/tests/tier3/test_dataset_baseline_fairness.py@@ -0,0 +1,1750 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++"""Eval datasets must not grade the no-skill baseline on using the skill it does not have."""++from __future__ import annotations++import asyncio+import json+import re+import shutil+import subprocess+import sys+import time+from pathlib import Path+from types import SimpleNamespace++import pytest+from click.testing import CliRunner++from skillevaluator.cli import cli+from skillevaluator.tier3 import generate_dataset+from skillevaluator.tier3.dataset_utils import load_dataset_entries_with_format, normalize_dataset_entries+from skillevaluator.tier3.evals_spec import (+ EVALS_SPEC,+ _baseline_fairness_warnings,+ validate_skillevaluators,+ validate_tier3_source,+)++_REPO = Path(__file__).resolve().parents[2]+++def _entry(**fields) -> dict:+ """A legacy entry (question, ground_truth, expected_behavior)."""+ return {"id": "case-1", "expected_skill": "release-review", **fields}+++def _case(skill_name: str = "release-review", **fields) -> dict:+ """An agentskills.io entry (prompt, expected_output, assertions), normalized as the loader does."""+ (entry,) = normalize_dataset_entries({"skill_name": skill_name, "evals": [{"id": "case-1", **fields}]})+ return entry+++ "prompt",+ [+ "Use the skill at skills/release-review to check manifest.yaml",+ "Read release-review/SKILL.md and then check manifest.yaml",+ ],+)+def test_prompt_pointing_at_skill_files_warns(prompt):+ (warning,) = _baseline_fairness_warnings(_case(prompt=prompt))+ assert warning.startswith("prompt points at the skill's files")+++ "assertion",+ [+ "Read release-review/SKILL.md before acting",+ "The agent read SKILL.md before taking action",+ "The agent read the release-review SKILL.md before executing commands",+ "The agent used the release-review skill",+ "Identified release-review as the right skill",+ "The agent invoked release-review before checking the manifest",+ "The agent activated `release-review`.",+ "The agent followed the SKILL.md workflow step by step",+ "Follows SKILL.md step by step",+ ],+)+def test_assertion_grading_skill_use_warns(assertion):+ entry = _case(prompt="Check manifest.yaml for blockers", assertions=[assertion])+ (warning,) = _baseline_fairness_warnings(entry)+ assert warning.startswith("assertions grades skill use")+++def test_expected_output_grading_skill_use_warns():+ entry = _entry(question="Check manifest.yaml", ground_truth="The agent used release-review and found 2 blockers")+ (warning,) = _baseline_fairness_warnings(entry)+ assert warning.startswith("ground_truth grades skill use")+++def test_one_warning_per_entry_for_graded_text():+ entry = _case(+ prompt="Check manifest.yaml",+ expected_output="The agent used the release-review skill",+ assertions=["The agent read SKILL.md", "The agent used release-review."],+ )+ (warning,) = _baseline_fairness_warnings(entry)+ assert warning.startswith("expected_output grades skill use")+++ "entry",+ [+ _entry(+ question="Use release-review to check manifest.yaml",+ ground_truth="Two release blockers: missing SBOM and an unsigned image",+ expected_behavior=["Lists both blockers", "Names the file each blocker comes from"],+ ),+ _entry(expected_skill=None, question="What is semantic versioning?", expected_behavior=["Explains it"]),+ ],+)+def test_outcome_entries_do_not_warn(entry):+ assert _baseline_fairness_warnings(entry) == []+++ "entry",+ [+ # A skill named after the CLI it wraps: the baseline can run the same CLI.+ {+ "expected_skill": "glab",+ "question": "List my open merge requests in group foo",+ "ground_truth": "The open MRs, listed using glab mr list",+ "expected_behavior": ["The agent ran glab mr list for group foo"],+ },+ {+ "expected_skill": "kubectl",+ "question": "Which pods are crash-looping in namespace web?",+ "ground_truth": "The crash-looping pods, found by using kubectl get pods",+ "expected_behavior": ["The agent used kubectl get pods -n web"],+ },+ # A skill named after a file format: "the input PDF" is the task's file.+ {+ "expected_skill": "pdf",+ "question": "What is the invoice total in invoice.pdf?",+ "expected_behavior": ["Reads the input PDF and returns the invoice total"],+ },+ # "the <format>" names the task's file, not the skill.+ {+ "expected_skill": "pdf",+ "question": "What is the invoice total in invoice.pdf?",+ "expected_behavior": ["Loads the PDF and returns the invoice total"],+ },+ {+ "expected_skill": "csv",+ "question": "Total the revenue in sales.csv by region",+ "expected_behavior": ["The agent loaded the CSV and grouped revenue by region"],+ },+ # A skill whose task output, or input, is a SKILL.md.+ {+ "expected_skill": "skill-creator",+ "question": "Write a SKILL.md for my csv-cleaner script",+ "ground_truth": "A SKILL.md with valid frontmatter",+ "expected_behavior": ["Writes skills/csv-cleaner/SKILL.md with a name and description"],+ },+ {+ "expected_skill": "skill-linter",+ "question": "Read SKILL.md in ./my-skill and fix its frontmatter",+ "expected_behavior": ["Opens SKILL.md in ./my-skill", "The fixed SKILL.md has valid frontmatter"],+ },+ ],+ ids=[+ "cli-named",+ "cli-named-with-args",+ "format-named",+ "format-named-the-pdf",+ "format-named-the-csv",+ "authoring",+ "reviewing",+ ],+)+def test_task_text_that_shares_the_skill_name_or_file_does_not_warn(entry):+ assert _baseline_fairness_warnings({"id": "case-1", **entry}) == []+++ ("skill", "assertion"),+ [("glab", "The agent used glab to list MRs"), ("git", "The agent used git to commit the change")],+)+def test_used_name_then_connective_warns_even_for_cli_named_skill(skill, assertion):+ # Only CLI arguments or a noun after the name exempt it, so "used <name> to ..."+ # still warns for a CLI-named skill.+ entry = _case(skill, prompt="q", assertions=[assertion])+ (warning,) = _baseline_fairness_warnings(entry)+ assert warning.startswith("assertions grades skill use")+++ ("field", "entry"),+ [+ ("prompt", {"prompt": "Open SKILL.md and fix its frontmatter"}),+ (+ "assertions",+ {+ "prompt": "Fix the frontmatter of the SKILL.md in ./my-skill",+ "assertions": ["The agent read the SKILL.md and reported the missing description"],+ },+ ),+ ],+ ids=["prompt", "assertion"],+)+def test_bare_read_skill_md_warns_even_for_skill_md_editing_skill(field, entry):+ # A SKILL.md is exempt only when the task writes it or the text names its+ # location, so a bare "read/open SKILL.md" still means the skill's own instructions.+ (warning,) = _baseline_fairness_warnings(_case("skill-linter", **entry))+ assert warning.startswith(f"{field} ")+ assert "SKILL.md" in warning+++def test_spec_example_dataset_is_fair_to_the_baseline(tmp_path: Path):+ example = next(spec for spec in EVALS_SPEC if spec.rel_path == "evals/evals.json").example+ path = tmp_path / "evals.json"+ path.write_text(example, encoding="utf-8")+ entries, _dataset_format = load_dataset_entries_with_format(path)++ assert entries+ for entry in entries:+ assert _baseline_fairness_warnings(entry) == []+++# Pages whose dataset examples users and agents copy.+_DATASET_DOC_PAGES = ["docs/eval-datasets.mdx", "skills/skillevaluator/references/tier3-datasets.md"]++[email protected]("page", _DATASET_DOC_PAGES)+def test_documented_dataset_examples_are_fair_to_the_baseline(page):+ checked = 0+ text = (_REPO / page).read_text(encoding="utf-8")+ for block in re.findall(r"```json[^\n]*\n(.*?)```", text, re.DOTALL):+ try:+ data = json.loads(block)+ entries = normalize_dataset_entries(data)+ except (json.JSONDecodeError, ValueError):+ continue+ for entry in entries:+ if entry.get("id") and entry.get("question"):+ checked += 1+ assert _baseline_fairness_warnings(entry) == [], (page, entry["id"])+ assert checked, f"no dataset examples found in {page}"+++def test_public_starter_dataset_passes_strict_validate(tmp_path: Path):+ # scripts/demo_starter.py copies this dataset next to the text-analyzer skill, and+ # docs/starter-demo.mdx runs the paired evaluation on it.+ reference = _REPO / "src" / "skillevaluator" / "tier3" / "reference_skills" / "text-analyzer"+ skill = tmp_path / "text-analyzer"+ (skill / "evals" / "files").mkdir(parents=True)+ (skill / "SKILL.md").write_bytes((reference / "SKILL.md").read_bytes())+ shutil.copytree(reference / "scripts", skill / "scripts", ignore=shutil.ignore_patterns("__pycache__"))+ starter = _REPO / "examples" / "starter"+ (skill / "evals" / "evals.json").write_bytes((starter / "evals.json").read_bytes())+ (skill / "evals" / "files" / "input.txt").write_bytes((starter / "input.txt").read_bytes())++ result = CliRunner().invoke(cli, ["tier3", "validate", str(skill), "--strict", "--json"])++ assert result.exit_code == 0, result.output+++def test_documented_eval_md_behaviors_are_fair_to_the_baseline():+ # EVAL.md `## Behaviors` become expected_behavior entries, which the+ # baseline is graded on, so they must not ask for SKILL.md or skill scripts.+ text = (_REPO / "docs" / "eval-datasets.mdx").read_text(encoding="utf-8")+ behaviors = []+ for block in re.findall(r"```markdown[^\n]*\n(.*?)```", text, re.DOTALL):+ if section := re.search(r"^## Behaviors\n(.*?)(?:^## |\Z)", block, re.DOTALL | re.MULTILINE):+ behaviors += re.findall(r"^- (.+)$", section.group(1), re.MULTILINE)++ assert behaviors, "no EVAL.md behaviors found in docs/eval-datasets.mdx"+ for behavior in behaviors:+ assert not re.search(r"\bSKILL\.md\b|\b[\w-]+\.(?:py|sh)\b", behavior), behavior+++def test_spec_guidance_names_the_command_that_reports_fairness_warnings():+ notes = next(spec for spec in EVALS_SPEC if spec.rel_path == "evals/evals.json").validation_notes+ (note,) = [note for note in notes if "no-skill baseline" in note]+ command = re.search(r"`skillevaluator ([\w -]+)`", note)++ assert command is not None, note+ result = CliRunner().invoke(cli, [*command.group(1).split(), "--help"])+ assert result.exit_code == 0, result.output+ assert "--strict" in result.output+++def _write_release_review_skill(tmp_path: Path, assertions: list[str]) -> Path:+ skill = tmp_path / "release-review"+ (skill / "evals").mkdir(parents=True)+ (skill / "SKILL.md").write_text("---\nname: release-review\ndescription: Review releases\n---\n", encoding="utf-8")+ (skill / "evals" / "evals.json").write_text(+ json.dumps(+ {+ "skill_name": "release-review",+ "evals": [+ {+ "id": "release-review-001",+ "prompt": "Review manifest.yaml for release blockers",+ "expected_output": "Two release blockers: missing SBOM and an unsigned image",+ "assertions": assertions,+ }+ ],+ }+ ),+ encoding="utf-8",+ )+ return skill+++def test_validate_evals_reports_fairness_warnings(tmp_path: Path):+ skill = _write_release_review_skill(tmp_path, ["Read release-review/SKILL.md"])+ dataset = skill / "evals" / "evals.json"+ payload = json.loads(dataset.read_text(encoding="utf-8"))+ payload["evals"][0]["prompt"] = "Use the skill at skills/release-review to review manifest.yaml"+ dataset.write_text(json.dumps(payload), encoding="utf-8")++ warnings = [result for result in validate_skillevaluators(skill) if result.status == "warning"]++ assert {result.path for result in warnings} == {"entry release-review-001"}+ assert any("points at the skill's files" in result.message for result in warnings)+ assert any("grades skill use" in result.message for result in warnings)++[email protected](("strict", "exit_code"), [(True, 1), (False, 0)], ids=["strict", "default"])+def test_tier3_validate_cli_fails_on_fairness_warning_only_with_strict(tmp_path: Path, strict: bool, exit_code: int):+ skill = _write_release_review_skill(tmp_path, ["The agent read SKILL.md before reviewing", "Lists both blockers"])+ args = ["tier3", "validate", str(skill), "--json", *(["--strict"] if strict else [])]++ result = CliRunner().invoke(cli, args)++ assert result.exit_code == exit_code, result.output+ payload = json.loads(result.output)+ fairness = [item for item in payload if item["path"] == "entry release-review-001"]+ assert [item["status"] for item in fairness] == ["warning"]+ assert fairness[0]["message"].startswith("assertions grades skill use ('read SKILL.md')")+ assert not [item for item in payload if item["status"] == "error"]+++def test_tier3_validate_strict_passes_an_outcome_dataset(tmp_path: Path):+ skill = _write_release_review_skill(tmp_path, ["Lists both blockers", "Names the file each blocker comes from"])++ result = CliRunner().invoke(cli, ["tier3", "validate", str(skill), "--strict", "--json"])++ assert result.exit_code == 0, result.output+++def test_fairness_warnings_do_not_block_the_tier3_source_check(tmp_path: Path):+ # Runs, autopilot and `validate` gate on errors from this check, never on warnings.+ skill = _write_release_review_skill(tmp_path, ["The agent used the release-review skill"])++ source, checks = validate_tier3_source(skill)++ assert source == "evals_json"+ assert [check.status for check in checks if check.path == "entry release-review-001"] == ["warning"]+ assert not [check for check in checks if check.status in {"error", "missing"}]+++def test_all_tier_ci_tier3_dataset_check_is_strict_about_fairness_warnings(tmp_path: Path, monkeypatch):+ # All-tier CI runs its advisory Tier 3 step only on a dataset that passes strict validation.+ # A staged verifier bundle in another test can leave its own secret_redaction module behind;+ # without it, the CI scripts import ci.secret_redaction.+ monkeypatch.delitem(sys.modules, "secret_redaction", raising=False)+ from ci.run_tiers import ConfigurationError, dataset_preflight++ unfair = _write_release_review_skill(tmp_path / "unfair", ["The agent used the release-review skill"])+ fair = _write_release_review_skill(tmp_path / "fair", ["Lists both blockers"])++ with pytest.raises(ConfigurationError, match="strict validation"):+ dataset_preflight(unfair)+ assert "evals/evals.json" in dataset_preflight(fair)+++def test_accept_traces_reports_fairness_warnings_on_promoted_cases(tmp_path: Path):+ # Cases promoted from reviewed production traces are validated with the same check.+ from skillevaluator.tier3.trace_import import accept_traces, import_traces++ skill = tmp_path / "release-review"+ skill.mkdir()+ (skill / "SKILL.md").write_text("---\nname: release-review\ndescription: Review releases\n---\n", encoding="utf-8")+ export = tmp_path / "export.jsonl"+ export.write_text(+ json.dumps({"session_id": "session-one", "prompt": "Review manifest.yaml for release blockers"}),+ encoding="utf-8",+ )+ review = tmp_path / "review"+ document = import_traces(skill, export, review)+ document["candidates"][0]["review"].update(+ decision="accept",+ expected_output="Two release blockers: missing SBOM and an unsigned image",+ assertions=["The agent read release-review/SKILL.md"],+ )+ (review / "candidates.json").write_text(json.dumps(document), encoding="utf-8")++ result = accept_traces(skill, review)++ (case_id,) = result["added"]+ assert [check.status for check in result["validation"] if check.path == f"entry {case_id}"] == ["warning"]+++def _skill(**overrides) -> dict:+ return {+ "name": "release-review",+ "description": "Reviews release manifests for policy problems.",+ "scripts": ["scripts/review.py"],+ "content": "",+ "eval_prompt": "",+ **overrides,+ }+++ "eval_prompt",+ ["", "## Negative Cases\n- What is the capital of Peru?"],+ ids=["no-guidance", "with-negative"],+)[email protected]("generate", [generate_dataset._generate_simple, generate_dataset._generate_full])+def test_template_generator_cases_are_fair_to_the_baseline(generate, eval_prompt):+ cases = generate(_skill(eval_prompt=eval_prompt))++ assert cases+ for case in cases:+ assert _baseline_fairness_warnings(case, skill_scripts=["review.py"]) == [], case+ assert "SKILL.md" not in json.dumps(case)+ assert "review.py" not in json.dumps([case["ground_truth"], case["expected_behavior"]])+++def test_template_positive_cases_grade_the_task_outcome():+ cases = generate_dataset._generate_full(_skill())++ assert [case["id"] for case in cases] == ["release-review-001", "release-review-002", "release-review-003"]+ for case in cases:+ assert case["expected_skill"] == "release-review"+ assert case["expected_script"] == "scripts/review.py"+ assert "reviews release manifests for policy problems" in case["ground_truth"]+ assert case["expected_behavior"][0] == (+ "The agent produced concrete results for the request "+ "(reviews release manifests for policy problems), not only a plan"+ )+ assert case["expected_behavior"][-1] == generate_dataset.SECURITY_BEHAVIOR+++def test_template_cases_keep_developer_behaviors():+ skill = _skill(eval_prompt="## Behaviors\n- The agent lists every blocker with its manifest line")++ (case,) = generate_dataset._generate_simple(skill)++ assert "The agent lists every blocker with its manifest line" in case["expected_behavior"]+ assert case["expected_behavior"][-1] == generate_dataset.SECURITY_BEHAVIOR++[email protected]("grounding", ["skill", "intent"])[email protected]("generate", [generate_dataset._generate_simple, generate_dataset._generate_full])+def test_template_cases_keep_the_grounding_order_and_stay_fair(generate, grounding):+ # --grounding intent puts the authored EVAL.md behaviors first; the outcome check replaces skill use.+ authored = ["The agent lists every blocker with its manifest line", "The agent names the policy each one breaks"]+ skill = _skill(eval_prompt="## Behaviors\n" + "".join(f"- {item}\n" for item in authored), grounding=grounding)+ outcome = (+ "The agent produced concrete results for the request "+ "(reviews release manifests for policy problems), not only a plan"+ )+ leading = [*authored, outcome] if grounding == "intent" else [outcome, *authored]++ cases = generate(skill)++ assert cases+ for case in cases:+ assert case["expected_behavior"] == [+ *leading,+ generate_dataset._FINAL_RESPONSE_BEHAVIOR,+ generate_dataset.SECURITY_BEHAVIOR,+ ]+ assert _baseline_fairness_warnings(case, skill_scripts=["review.py"]) == []+++def test_template_negative_case_is_unchanged():+ without_guidance = generate_dataset._generate_full(_skill())+ with_guidance = generate_dataset._generate_full(+ _skill(eval_prompt="## Negative Cases\n- What is the capital of Peru?")+ )++ assert not [case for case in without_guidance if case["id"].endswith("-neg-001")]+ assert with_guidance[-1] == {+ "id": "release-review-neg-001",+ "question": "What is the capital of Peru?",+ "expected_skill": None,+ "expected_script": None,+ "ground_truth": "The agent answered an unrelated question without loading or applying this skill",+ "expected_behavior": [+ "The agent responded without reading or applying this skill",+ "The agent did not invoke this skill's tools or scripts",+ generate_dataset.SECURITY_BEHAVIOR,+ ],+ }+++def test_autopilot_template_case_does_not_grade_skill_use(tmp_path: Path):+ skill = tmp_path / "release-review"+ (skill / "scripts").mkdir(parents=True)+ (skill / "SKILL.md").write_text(+ "---\nname: release-review\ndescription: Reviews release manifests for policy problems.\n---\n# Body\n",+ encoding="utf-8",+ )+ (skill / "scripts" / "review.py").write_text("print('ok')\n", encoding="utf-8")++ output = generate_dataset.generate_one_case(skill, use_llm=False)++ (case,) = json.loads(output.read_text(encoding="utf-8"))["evals"]+ graded = json.dumps([case["expected_output"], case["assertions"]])+ assert not re.search(r"SKILL\.md|review\.py|used the|identified", graded), graded+ assert case["expected_script"] == "review.py"+ assert not [result for result in validate_skillevaluators(skill) if result.path == f"entry {case['id']}"], (+ "generated starter case should pass the fairness check"+ )+++def llm_prompts(monkeypatch) -> list[str]:+ """Stub the public provider and capture every dataset prompt it is sent."""+ from skillevaluator import provider_config+ from skillevaluator.inference.client import LLMClient++ prompts: list[str] = []++ def _completions(_self, _system_prompt: str, user_prompt: str, **_kwargs) -> str:+ prompts.append(user_prompt)+ return "[]"++ monkeypatch.setattr(+ provider_config, "resolve_llm_provider", lambda: SimpleNamespace(provider="openai", model="test-model")+ )+ monkeypatch.setattr(LLMClient, "completions", _completions)+ return prompts++[email protected]("full", [False, True], ids=["simple", "full"])+def test_llm_generation_prompt_examples_are_fair_to_the_baseline(llm_prompts, full):+ asyncio.run(generate_dataset._generate_with_llm(_skill(), full=full))++ (prompt,) = llm_prompts+ good_examples = re.findall(r'GOOD: "([^"]+)"', prompt)+ assert good_examples+ for example in good_examples:+ entry = _entry(ground_truth=example, expected_behavior=[example])+ assert _baseline_fairness_warnings(entry) == [], example+ assert not re.search(r"release-review|SKILL\.md|review\.py", example), example+ assert "skill_execution" in prompt+ assert "observable checks on the task outcome" in prompt+++def test_llm_refine_prompt_does_not_ask_for_skill_use_behaviors(llm_prompts):+ skill = _skill(scripts=["review.py"])+ cases = generate_dataset._generate_simple(skill)++ asyncio.run(generate_dataset._refine_with_llm(skill, cases, {cases[0]["id"]: _SKILL_USE_TRAJECTORY}))++ (prompt,) = llm_prompts+ instructions = prompt.split("REFINEMENT INSTRUCTIONS", 1)[1]+ assert "skill_execution" in instructions+ assert not re.search(r'"The agent executed\s+[^"]*\.py', instructions)+ assert not re.search(r"\b\w+\.py\b", instructions)+ for example in re.findall(r'"(The agent[^"]*)"', instructions):+ assert _baseline_fairness_warnings(_entry(expected_behavior=[example])) == [], example+++_SKILL_USE_TRAJECTORY = {+ "steps": [+ {+ "source": "agent",+ "tool_calls": [{"function_name": "read", "arguments": {"path": "/skills/release-review/SKILL.md"}}],+ },+ {+ "source": "agent",+ "tool_calls": [+ {"function_name": "read", "arguments": {"path": "/skills/release-review/references/policy.md"}}+ ],+ },+ {+ "source": "agent",+ "tool_calls": [+ {"function_name": "bash", "arguments": {"command": "python scripts/review.py --manifest release.yaml"}}+ ],+ },+ {"source": "agent", "tool_calls": [{"function_name": "read", "arguments": {"path": "/work/release.yaml"}}]},+ {+ "source": "agent",+ "tool_calls": [{"function_name": "bash", "arguments": {"command": "grep -n image release.yaml"}}],+ },+ {+ "source": "agent",+ "message": "The manifest has two blockers: a missing changelog entry and an unsigned image.",+ },+ ]+}++[email protected]("with_skill_context", [True, False], ids=["skill", "case-only"])+def test_template_refine_drops_skill_use_and_keeps_task_work(with_skill_context):+ skill = _skill(scripts=["review.py"])+ cases = generate_dataset._generate_simple(skill)++ # create-eval-dataset --refine passes no authored case ids for cases it generated.+ (refined,) = generate_dataset._refine_from_trajectory_template(+ cases,+ {cases[0]["id"]: _SKILL_USE_TRAJECTORY},+ skill=skill if with_skill_context else None,+ authored_case_ids=set(),+ )++ behaviors = refined["expected_behavior"]+ assert behaviors[:2] == ["The agent read release.yaml", "The agent executed: grep -n image release.yaml"]+ assert not [item for item in behaviors if re.search(r"SKILL\.md|review\.py|policy\.md", item)]+ assert refined["ground_truth"].startswith("The manifest has two blockers")+ assert _baseline_fairness_warnings(refined, skill_scripts=["review.py"]) == []+++ ("text", "uses"),+ [+ ("/root/.claude/skills/release-review/SKILL.md", True),+ ("/workspace/skills/release-review/references/policy.md", True),+ ("cat ~/.agents/skills/release-review/notes.txt", True),+ ("python3 ./review.py --manifest m.yaml", True),+ ("/workspace/skills/release-review-extra/notes.txt", False),+ ("python3 preview.py", False),+ ("cat review.python.txt", False),+ ("grep -n image release.yaml", False),+ ],+)+def test_uses_skill_files_matches_whole_names_only(text, uses):+ assert generate_dataset._uses_skill_files(text, "release-review", ["scripts/review.py", None]) is uses+++# --- Skill scripts, negation and wording the check must not misread ---------+++ "assertion",+ [+ "Ran scripts/convert.py",+ "The agent executed convert.py or explained how to run it",+ "Ran `python3 ./convert.py report.docx`.",+ "Saved the output of tools/convert.py next to the input",+ "Used convert.py to convert report.docx",+ "Converted the file using convert.py --format pdf",+ ],+)+def test_assertion_running_a_skill_script_warns(assertion):+ entry = _case("my-skill", prompt="Convert report.docx to PDF", assertions=[assertion])++ (warning,) = _baseline_fairness_warnings(entry, skill_scripts=["convert.py"])++ assert warning.startswith("assertions grades skill use")+ assert "convert.py" in warning+++ "assertion",+ [+ "Saves report.pdf next to report.docx",+ "The agent did not run convert.py",+ "Converted the file without running convert.py",+ "Ran preconvert.py on the input",+ "Attached convert.py.txt to the answer",+ # "uses" or "called" before a file name that does not end the clause names the file.+ "The fix uses convert.py's existing parser",+ "Writes a file called convert.py with the fixed checks",+ ],+)+def test_text_that_does_not_run_a_skill_script_does_not_warn(assertion):+ entry = _case("my-skill", prompt="Convert report.docx to PDF", assertions=[assertion])++ assert _baseline_fairness_warnings(entry, skill_scripts=["convert.py"]) == []+++ "assertions",+ [["Ran scripts/convert.py"], ["The agent executed convert.py or explained how to run it"]],+ ids=["path", "old-generator-text"],+)+def test_tier3_validate_strict_fails_on_a_skill_script_assertion(tmp_path: Path, assertions):+ skill = tmp_path / "my-skill"+ (skill / "scripts").mkdir(parents=True)+ (skill / "evals").mkdir()+ (skill / "SKILL.md").write_text("---\nname: my-skill\ndescription: Convert documents\n---\n", encoding="utf-8")+ (skill / "scripts" / "convert.py").write_text("print('ok')\n", encoding="utf-8")+ case = {"id": "my-skill-001", "prompt": "Convert report.docx to PDF", "expected_output": "report.pdf"}+ (skill / "evals" / "evals.json").write_text(+ json.dumps({"skill_name": "my-skill", "evals": [{**case, "assertions": assertions}]}), encoding="utf-8"+ )++ result = CliRunner().invoke(cli, ["tier3", "validate", str(skill), "--strict", "--json"])++ assert result.exit_code == 1, result.output+ (warning,) = [item for item in json.loads(result.output) if item["path"] == "entry my-skill-001"]+ assert warning["message"].startswith("assertions grades skill use")+++ ("skill_name", "text"),+ [+ ("skill-creator", "The new file follows the SKILL.md frontmatter format"),+ ("skill-creator", "Follows the SKILL.md conventions for the new skill"),+ ("skill-linter", "Fix the frontmatter of the following SKILL.md"),+ ("skill-creator", "Create a pdf-tools skill following SKILL.md best practices"),+ ("skill-creator", "Scaffold a new skill following the SKILL.md structure"),+ ("skill-creator", "Write a skill for CSV cleanup following SKILL.md guidelines"),+ ("skill-creator", "Create a skill following the SKILL.md frontmatter rules"),+ ("skill-creator", "The new skill follows the SKILL.md layout and naming rules"),+ ("skill-linter", "Loads SKILL.md files and checks their frontmatter"),+ ("python", "Ranks the python developers by skill level"),+ ("release-review", "The agent did not read SKILL.md"),+ ("release-review", "Answers directly, without reading SKILL.md"),+ ],+)+def test_format_wording_and_negated_checks_do_not_warn(skill_name, text):+ entry = _case(skill_name, prompt=text, expected_output=text, assertions=[text])++ assert _baseline_fairness_warnings(entry) == []+++ "assertion",+ [+ "Reads SKILL.md in the skill directory",+ "Reads SKILL.md from the installed skill",+ "Did not ask questions, and read SKILL.md first",+ "Reads SKILL.md and files under references/",+ ],+)+def test_skill_md_in_the_skill_itself_still_warns(assertion):+ entry = _case(prompt="Check manifest.yaml", assertions=[assertion])++ (warning,) = _baseline_fairness_warnings(entry)++ assert warning.startswith("assertions grades skill use")+++ "assertion",+ [+ "The agent never edits files before reading SKILL.md",+ "The agent does not run any command without first reading SKILL.md",+ "The agent should not proceed until it has read SKILL.md",+ "The agent doesn't act before it reads SKILL.md",+ "The agent did not modify files while reading SKILL.md",+ "The agent did not touch the output while it read SKILL.md",+ "The agent did not change files yet read SKILL.md",+ "The agent did not modify files after reading SKILL.md",+ "The agent used the skill",+ "The agent followed the skill's instructions",+ "The agent read the contents of SKILL.md",+ "The agent ran cat SKILL.md",+ "The agent ran python3 -I review.py",+ "The agent read SKILL\u200b.md",+ "The agent read \uff33\uff2b\uff29\uff2c\uff2c.md",+ "The agent read **SKILL.md**",+ "The agent read [SKILL.md](SKILL.md)",+ ],+)+def test_reviewed_skill_use_requirements_warn(assertion):+ warnings = _baseline_fairness_warnings(_entry(expected_behavior=[assertion]), skill_scripts=["review.py"])+ assert len(warnings) == 1+ assert "grades skill use" in warnings[0]++[email protected]("negation", ["not", "never", "not actually", "without first", "doesn't"])+def test_directly_negated_reads_remain_fair(negation):+ assert _baseline_fairness_warnings(_entry(expected_behavior=[f"The agent {negation} read SKILL.md"])) == []+++ "fields",+ [+ {"expected_behavior": [{"text": "The agent read SKILL.md"}]},+ {"expected_behavior": [["The agent read SKILL.md"]]},+ {"expected_behavior": "The agent read SKILL.md"},+ {"ground_truth": ["The agent read SKILL.md"]},+ {"ground_truth": {"result": "The agent read SKILL.md"}},+ {"ground_truth": {"The agent read SKILL.md": True}},+ ],+)+def test_nested_graded_text_warns(fields):+ warnings = _baseline_fairness_warnings(_entry(**fields))+ assert len(warnings) == 1+ assert "grades skill use" in warnings[0]++[email protected]("expected_skill", [None, "rr", "", "<omitted>"])[email protected]("field", ["prompt", "assertions"])[email protected]("own_name", ["release-review", "release-audit"])+def test_validation_checks_directory_and_frontmatter_names(tmp_path, expected_skill, field, own_name):+ skill = _write_release_review_skill(tmp_path, [])+ (skill / "SKILL.md").write_text("---\nname: release-audit\ndescription: Review releases\n---\n")+ dataset = skill / "evals" / "evals.json"+ payload = json.loads(dataset.read_text())+ case = payload["evals"][0]+ case["expected_skill"] = expected_skill+ if expected_skill == "<omitted>":+ del case["expected_skill"]+ case[field] = f"Use the skill at skills/{own_name}" if field == "prompt" else [f"The agent used {own_name}"]+ dataset.write_text(json.dumps(payload))+ warnings = [r for r in validate_skillevaluators(skill) if "skill_execution" in r.message]+ assert len(warnings) == 1+++ "entry",+ [+ _entry(question="read" + " " * 200_000 + "SKILL.md"),+ _entry(expected_behavior=["read" + " " * 200_000 + "SKILL.md"]),+ ],+)+def test_fairness_warning_excerpts_are_bounded(entry):+ (warning,) = _baseline_fairness_warnings(entry)+ assert len(warning) < 600++[email protected]("prompt", ["Run ./scripts/review.py on manifest.yaml", "Use the release-review skill"])+def test_prompt_requiring_skill_scripts_or_explicit_skill_warns(prompt):+ warnings = _baseline_fairness_warnings(_entry(question=prompt), skill_scripts=["review.py"])+ assert len(warnings) == 1+ assert "points at the skill's files" in warnings[0]+++def test_template_prompt_does_not_require_a_skill_script():+ skill = _skill(description="Runs ./scripts/review.py against a manifest", scripts=["review.py"])+ for case in generate_dataset._generate_full(skill):+ assert "review.py" not in case["question"]+++def test_warnings_name_the_fields_the_dataset_uses(tmp_path: Path):+ # evals.jsonl is always read as legacy, but its lines may use agentskills.io names.+ skill = tmp_path / "release-review"+ (skill / "evals").mkdir(parents=True)+ (skill / "SKILL.md").write_text("---\nname: release-review\ndescription: Review releases\n---\n", encoding="utf-8")+ lines = [+ {+ "id": "release-review-001",+ "expected_skill": "release-review",+ "prompt": "Use the skill at skills/release-review on manifest.yaml",+ "expected_output": "The agent used the release-review skill",+ },+ {+ "id": "release-review-002",+ "expected_skill": "release-review",+ "question": "Read release-review/SKILL.md, then check manifest.yaml",+ "expected_behavior": ["Read release-review/SKILL.md"],+ },+ ]+ (skill / "evals" / "evals.jsonl").write_text("".join(json.dumps(line) + "\n" for line in lines), encoding="utf-8")++ fields = {+ (result.path, result.message.split(" ", 1)[0])+ for result in validate_skillevaluators(skill)+ if result.status == "warning" and "skill_execution" in result.message+ }++ assert fields == {+ ("entry release-review-001", "prompt"),+ ("entry release-review-001", "expected_output"),+ ("entry release-review-002", "question"),+ ("entry release-review-002", "expected_behavior"),+ }+++# --- Generated starter cases -------------------------------------------------++# Descriptions that name the skill, its script or SKILL.md. Template cases+# quote the description, so these must not turn into graded skill use or a+# prompt that points at the skill's files.+_SKILL_NAMING_DESCRIPTIONS = [+ "The release-review skill checks release manifests",+ "Use release-review for release manifests. Use when a release is cut.",+ "Loads SKILL.md files and checks their frontmatter",+ "Follows the SKILL.md format to scaffold new agent skills",+ "Runs review.py on release manifests",+ "Runs review.sh on release manifests",+ "Reads SKILL.md and reports frontmatter errors.",+ "Opens the SKILL.md and fixes its description field.",+ "Keeps skills/release-review/SKILL.md in sync with the docs",+]+# A Python script and a shell script: `tier3 validate` checks graded text against both.+_SCRIPT_FILES = ("review.py", "review.sh")++[email protected]("description", _SKILL_NAMING_DESCRIPTIONS)[email protected]("generate", [generate_dataset._generate_simple, generate_dataset._generate_full])+def test_template_cases_stay_fair_when_the_description_names_the_skill(generate, description):+ skill = _skill(description=description, scripts=["review.py"], script_files=_SCRIPT_FILES)+ for case in generate(skill):+ assert _baseline_fairness_warnings(case, skill_scripts=_SCRIPT_FILES) == [], case+++ ("description", "task"),+ [+ ("Reads SKILL.md and reports frontmatter errors.", "reads my SKILL.md and reports frontmatter errors"),+ ("Opens the SKILL.md and fixes its description field.", "opens my SKILL.md and fixes its description field"),+ ],+)+def test_template_prompt_names_a_skill_md_in_the_description_as_the_users_file(description, task):+ # The task stays in the prompt and the graded text; only the SKILL.md is named as the user's.+ (case,) = generate_dataset._generate_simple(_skill(description=description))++ assert case["question"] == f"Use release-review to {task}"+ assert case["ground_truth"] == f"A correct, complete result for: {task}"+++def test_template_prompt_is_generic_when_the_description_names_the_skill_directory():+ skill = _skill(description="Keeps skills/release-review/SKILL.md in sync with the docs")++ simple, implicit, contextual = generate_dataset._generate_full(skill)++ assert simple["question"] == "Use release-review to handle a typical request"+ assert implicit["question"] == "I need to handle a typical request"+ assert "skills/release-review" not in contextual["question"]+ assert simple["ground_truth"] == "A correct, complete result for the request"+++def _write_skill(+ tmp_path: Path, description: str, eval_md: str | None = None, scripts: tuple[str, ...] = ("review.py",)+) -> Path:+ skill = tmp_path / "release-review"+ (skill / "scripts").mkdir(parents=True)+ (skill / "SKILL.md").write_text(+ f"---\nname: release-review\ndescription: {json.dumps(description)}\n---\n# Body\n", encoding="utf-8"+ )+ for script in scripts:+ (skill / "scripts" / script).write_text("echo ok\n", encoding="utf-8")+ if eval_md is not None:+ (skill / "evals").mkdir()+ (skill / "evals" / "EVAL.md").write_text(eval_md, encoding="utf-8")+ return skill++[email protected]("description", _SKILL_NAMING_DESCRIPTIONS)+def test_starter_case_passes_strict_validate(tmp_path: Path, description):+ skill = _write_skill(tmp_path, description, scripts=_SCRIPT_FILES)+ generate_dataset.generate_one_case(skill, use_llm=False)++ result = CliRunner().invoke(cli, ["tier3", "validate", str(skill), "--strict", "--json"])++ assert result.exit_code == 0, result.output+++def llm_reply(monkeypatch) -> list[str]:+ """Stub the public provider; the test appends the reply it returns."""+ from skillevaluator import provider_config+ from skillevaluator.inference.client import LLMClient++ replies: list[str] = []+ monkeypatch.setattr(+ provider_config, "resolve_llm_provider", lambda: SimpleNamespace(provider="openai", model="test-model")+ )+ monkeypatch.setattr(LLMClient, "completions", lambda _self, _system, _user, **_kwargs: replies[-1])+ return replies+++def test_autopilot_llm_case_does_not_grade_skill_use(tmp_path: Path, llm_reply):+ skill = _write_skill(tmp_path, "Reviews release manifests for policy problems.")+ llm_reply.append(+ json.dumps(+ [+ {+ "id": "release-review-001",+ "question": "Is release.yaml ready to ship?",+ "expected_skill": "release-review",+ "expected_script": "review.py",+ "ground_truth": "The agent used the release-review skill and listed the blockers",+ "expected_behavior": [+ "The agent read the release-review SKILL.md first",+ "The agent followed the SKILL.md workflow step by step",+ "The agent ran review.py on release.yaml",+ "The agent lists each blocker with its manifest line",+ ],+ }+ ]+ )+ )++ output = generate_dataset.generate_one_case(skill, use_llm=True)++ (case,) = json.loads(output.read_text(encoding="utf-8"))["evals"]+ assert case["prompt"] == "Is release.yaml ready to ship?"+ assert case["expected_output"] == ("A correct, complete result for: reviews release manifests for policy problems")+ assert case["assertions"] == [+ "The agent lists each blocker with its manifest line",+ generate_dataset.SECURITY_BEHAVIOR,+ ]+ result = CliRunner().invoke(cli, ["tier3", "validate", str(skill), "--strict", "--json"])+ assert result.exit_code == 0, result.output+++def test_autopilot_llm_case_with_only_skill_use_checks_gets_outcome_checks(tmp_path: Path, llm_reply):+ skill = _write_skill(tmp_path, "Reviews release manifests for policy problems.")+ llm_reply.append(+ json.dumps(+ [+ {+ "id": "release-review-001",+ "question": "Is release.yaml ready to ship?",+ "expected_skill": "release-review",+ "expected_script": None,+ "ground_truth": "Two blockers: a missing changelog entry and an unsigned image",+ "expected_behavior": ["The agent invoked release-review before answering"],+ }+ ]+ )+ )++ output = generate_dataset.generate_one_case(skill, use_llm=True)++ (case,) = json.loads(output.read_text(encoding="utf-8"))["evals"]+ assert case["expected_output"] == "Two blockers: a missing changelog entry and an unsigned image"+ assert case["assertions"] == generate_dataset._outcome_behaviors(+ "reviews release manifests for policy problems", []+ )+++def test_autopilot_llm_case_with_only_its_own_security_check_left_gets_outcome_checks(tmp_path: Path, llm_reply):+ # The LLM wrote its own security line, so none is appended; it alone does not test the task.+ skill = _write_skill(tmp_path, "Reviews release manifests for policy problems.")+ llm_reply.append(+ json.dumps(+ [+ {+ "id": "release-review-001",+ "question": "Is release.yaml ready to ship?",+ "expected_skill": "release-review",+ "expected_script": "review.py",+ "ground_truth": "Two blockers: a missing changelog entry and an unsigned image",+ "expected_behavior": [+ "The agent read SKILL.md",+ "The agent ran review.py",+ "The agent did not expose secrets",+ ],+ }+ ]+ )+ )++ output = generate_dataset.generate_one_case(skill, use_llm=True)++ (case,) = json.loads(output.read_text(encoding="utf-8"))["evals"]+ assert case["assertions"] == generate_dataset._outcome_behaviors(+ "reviews release manifests for policy problems", ["The agent did not expose secrets"]+ )+++ "task_check",+ [+ "The agent flags the destructive DROP COLUMN statement in 0042_drop_column.sql",+ "The agent reports each leaked secret with its file and line",+ ],+ ids=["destructive", "secret"],+)+def test_autopilot_llm_case_keeps_a_task_check_that_mentions_secrets_or_destructive_changes(+ tmp_path: Path, llm_reply, task_check+):+ # Such a line reads like a security check, but it is the only check on the task: keep it.+ skill = _write_skill(tmp_path, "Reviews release manifests for policy problems.")+ llm_reply.append(+ json.dumps(+ [+ {+ "id": "release-review-001",+ "question": "Is 0042_drop_column.sql safe to ship with this release?",+ "expected_skill": "release-review",+ "expected_script": "review.py",+ "ground_truth": "The migration drops a column that the release still reads",+ "expected_behavior": ["The agent ran review.py on the migration", task_check],+ }+ ]+ )+ )++ output = generate_dataset.generate_one_case(skill, use_llm=True)++ (case,) = json.loads(output.read_text(encoding="utf-8"))["evals"]+ assert case["assertions"] == generate_dataset._outcome_behaviors(+ "reviews release manifests for policy problems", [task_check]+ )+++def test_autopilot_starter_leaves_out_eval_md_skill_use_behaviors(tmp_path: Path):+ eval_md = "## Behaviors\n- The agent reads SKILL.md before acting\n- The agent lists every blocker\n"+ skill = _write_skill(tmp_path, "Reviews release manifests for policy problems.", eval_md)++ output = generate_dataset.generate_one_case(skill, use_llm=False)++ (case,) = json.loads(output.read_text(encoding="utf-8"))["evals"]+ assert "The agent lists every blocker" in case["assertions"]+ assert not [item for item in case["assertions"] if "SKILL.md" in item]+++def test_create_eval_dataset_warns_about_cases_that_grade_skill_use(tmp_path: Path, capsys):+ # create-eval-dataset keeps EVAL.md behaviors as written, so it names the ones the baseline cannot meet.+ eval_md = "## Behaviors\n- The agent reads SKILL.md before acting\n- The agent lists every blocker\n"+ skill = _write_skill(tmp_path, "Reviews release manifests for policy problems.", eval_md)++ result = generate_dataset.main([str(skill), "--grounding", "skill", "--no-llm", "--dry-run"])++ output = capsys.readouterr().out+ assert "Warning: case release-review-001: assertions grades skill use ('reads SKILL.md')" in output+ assert "The agent reads SKILL.md before acting" in result.dataset["evals"][0]["assertions"]+++ "description", ["Reviews release manifests for policy problems.", "Runs review.sh on release manifests."]+)+def test_create_eval_dataset_prints_no_warning_for_outcome_cases(tmp_path: Path, capsys, description):+ # A description that names a skill script is not quoted in graded text, whatever the script's language.+ skill = _write_skill(tmp_path, description, scripts=_SCRIPT_FILES)++ generate_dataset.main([str(skill), "--grounding", "skill", "--no-llm", "--full", "--dry-run"])++ assert "Warning:" not in capsys.readouterr().out+++def test_create_eval_dataset_warns_when_a_refined_case_has_an_invalid_expected_script(+ tmp_path: Path, capsys, monkeypatch+):+ # The LLM rewrite can return a list expected_script. tier3 validate reports that as an error;+ # the fairness warnings do not read it, so they still print and the dataset is still written.+ skill = _write_skill(tmp_path, "Reviews release manifests for policy problems.")++ async def generate(parsed, **_kwargs):+ return generate_dataset._generate_simple(parsed)++ async def refine(_skill, cases, _trajectories, **_kwargs):+ return [{**cases[0], "expected_script": ["review.py"], "expected_behavior": ["The agent read SKILL.md"]}]++ monkeypatch.setattr(generate_dataset, "_generate_with_llm", generate)+ monkeypatch.setattr(generate_dataset, "_refine_with_llm", refine)+ monkeypatch.setattr(+ generate_dataset,+ "_discover_trajectories",+ lambda *_args, **_kwargs: ({"release-review-001": {"steps": []}}, {}),+ )++ result = generate_dataset.main([str(skill), "--grounding", "skill", "--refine"])++ assert result.status == "created"+ assert "Warning: case release-review-001: assertions grades skill use" in capsys.readouterr().out+++def test_template_refine_ignores_non_string_skill_fields():+ # LLM-written cases are not type-checked for expected_skill or expected_script.+ skill = _skill(scripts=["review.py"])+ case = {**generate_dataset._generate_simple(skill)[0], "expected_script": ["review.py"]}+ trajectories = {case["id"]: _SKILL_USE_TRAJECTORY}++ (with_skill,) = generate_dataset._refine_from_trajectory_template([case], trajectories, skill=skill)+ (case_only,) = generate_dataset._refine_from_trajectory_template(+ [{**case, "expected_skill": ["release-review"]}], trajectories, skill=None+ )++ assert "The agent read release.yaml" in with_skill["expected_behavior"]+ assert "The agent read release.yaml" in case_only["expected_behavior"]+++ ("placeholder", "command"),+ [+ ("None", "python3 -c 'print(None)'"),+ ("N/A", "grep -c A grades.csv"),+ ("-", "sort - < grades.csv"),+ ],+)+def test_template_refine_treats_a_placeholder_expected_script_as_no_script(placeholder, command):+ # Placeholder expected_script values mean no script, so they must not drop task commands.+ case = {**generate_dataset._generate_simple(_skill(scripts=[]))[0], "expected_script": placeholder}+ trajectory = {+ "steps": [{"source": "agent", "tool_calls": [{"function_name": "bash", "arguments": {"command": command}}]}]+ }++ (refined,) = generate_dataset._refine_from_trajectory_template(+ [case], {case["id"]: trajectory}, authored_case_ids=set()+ )++ assert f"The agent executed: {command}" in refined["expected_behavior"]+++def test_template_refine_drops_runs_of_a_shell_skill_script(tmp_path: Path):+ skill = generate_dataset._parse_skill(_write_skill(tmp_path, "Reviews release manifests.", scripts=_SCRIPT_FILES))+ cases = generate_dataset._generate_simple(skill)+ trajectory = {+ "steps": [+ {+ "source": "agent",+ "tool_calls": [+ {"function_name": "bash", "arguments": {"command": "bash scripts/review.sh release.yaml"}}+ ],+ },+ {+ "source": "agent",+ "tool_calls": [{"function_name": "bash", "arguments": {"command": "grep -n image release.yaml"}}],+ },+ ]+ }++ (refined,) = generate_dataset._refine_from_trajectory_template(cases, {cases[0]["id"]: trajectory}, skill=skill)++ assert "The agent executed: grep -n image release.yaml" in refined["expected_behavior"]+ assert not [item for item in refined["expected_behavior"] if "review.sh" in item]+ assert _baseline_fairness_warnings(refined, skill_scripts=_SCRIPT_FILES) == []++[email protected]("command", ["init-custom-grader", "init-harbor-task"])+def test_scaffold_starter_case_grades_the_outcome(tmp_path: Path, command):+ skill = tmp_path / "release-review"+ skill.mkdir()+ (skill / "SKILL.md").write_text("---\nname: release-review\ndescription: Review releases\n---\n", encoding="utf-8")++ result = CliRunner().invoke(cli, [command, str(skill)])++ assert result.exit_code == 0, result.output+ (case,) = json.loads((skill / "evals" / "evals.json").read_text(encoding="utf-8"))["evals"]+ assert case["assertions"]+ assert not [item for item in case["assertions"] if re.search(r"\bskill\b", item, re.IGNORECASE)]+++def test_agent_skill_dataset_passes_the_strict_validate_its_docs_recommend():+ # skills/skillevaluator/SKILL.md and docs/agent-skill.mdx tell users to run this command.+ result = CliRunner().invoke(cli, ["tier3", "validate", str(_REPO / "skills" / "skillevaluator"), "--strict"])++ assert result.exit_code == 0, result.output+++ "text",+ [+ "The agent never edits files before reading SKILL.md",+ "The agent does not run any command without first reading SKILL.md",+ "The agent should not proceed until it has read SKILL.md",+ "The agent doesn't act before it reads SKILL.md",+ ],+)+def test_negated_action_that_requires_reading_the_skill_still_warns(text):+ assert _baseline_fairness_warnings(_case(prompt="Check manifest.yaml", assertions=[text]))+++ "text",+ [+ "The agent did not read SKILL.md",+ "The agent never reads SKILL.md",+ "The agent did not actually read SKILL.md",+ "The agent answered without first reading SKILL.md",+ "The agent didn't run review.py",+ ],+)+def test_immediately_negated_skill_use_does_not_warn(text):+ assert (+ _baseline_fairness_warnings(_case(prompt="Check manifest.yaml", assertions=[text]), skill_scripts=["review.py"])+ == []+ )++[email protected]("field", ["prompt", "expected_output", "assertions"])[email protected]("large_input", ["whitespace", "alias"])+def test_fairness_diagnostics_bound_untrusted_matched_text(field, large_input):+ name = "r" * 200_000 if large_input == "alias" else "release-review"+ text = f"Use the {name} skill" if large_input == "alias" else "Read" + " " * 200_000 + "SKILL.md"+ entry = (+ _case(name, prompt="Check manifest.yaml", **{field: [text] if field == "assertions" else text})+ if field != "prompt"+ else _case(name, prompt=text)+ )++ (warning,) = _baseline_fairness_warnings(entry)++ assert len(warning) < 1_000+ assert "skill_execution" in warning++[email protected]("declared_name", ["missing", None, "rr"])[email protected]("identity", ["release-review", "release-audit"])+def test_strict_validation_uses_the_directory_and_frontmatter_identity(tmp_path, declared_name, identity):+ skill = _write_release_review_skill(tmp_path, [f"The agent used {identity}."])+ (skill / "SKILL.md").write_text("---\nname: release-audit\ndescription: Review releases\n---\n", encoding="utf-8")+ path = skill / "evals" / "evals.json"+ case = json.loads(path.read_text())["evals"][0]+ case["prompt"] = f"Use the skill at skills/{identity}"+ if declared_name != "missing":+ case["expected_skill"] = declared_name+ path.write_text(json.dumps([{"id": "case-1", "question": case.pop("prompt"), **case}]))++ result = CliRunner().invoke(cli, ["tier3", "validate", str(skill), "--strict", "--json"])++ assert result.exit_code == 1, result.output+ warnings = [item["message"] for item in json.loads(result.output) if "skill_execution" in item["message"]]+ assert len(warnings) == 2+++ "fields",+ [+ {"assertions": [{"text": "The agent read SKILL.md"}]},+ {"assertions": [["The agent read SKILL.md"]]},+ {"expected_output": {"result": ["The agent read SKILL.md"]}},+ {"expected_output": ["The agent read SKILL.md"]},+ {"expected_behavior": "The agent read SKILL.md"},+ {"assertions": {"The agent read SKILL.md": "required"}},+ ],+)+def test_every_judge_graded_string_leaf_is_checked_after_loading(tmp_path, fields):+ skill = _write_release_review_skill(tmp_path, ["Lists both blockers"])+ path = skill / "evals" / "evals.json"+ data = json.loads(path.read_text())+ data["evals"][0].update(fields)+ path.write_text(json.dumps(data))++ result = CliRunner().invoke(cli, ["tier3", "validate", str(skill), "--strict", "--json"])++ assert result.exit_code == 1, result.output+ assert any("grades skill use" in item["message"] for item in json.loads(result.output))+++ "text",+ [+ "The agent read SKILL\u200b.md",+ "The agent read SKILL.md", # noqa: RUF001 -- compatibility spelling under test+ "The agent read **SKILL.md**",+ "The agent read [SKILL.md](SKILL.md)",+ "The agent used the skill",+ "The agent followed the skill's instructions",+ "The agent read the contents of SKILL.md",+ "The agent ran cat SKILL.md",+ "The agent ran python3 -I review.py",+ ],+)+def test_common_skill_use_spellings_warn(text):+ assert _baseline_fairness_warnings(+ _case(prompt="Check manifest.yaml", assertions=[text]), skill_scripts=["review.py"]+ )++[email protected]("prompt", ["Run ./scripts/review.py on manifest.yaml", "Use the release-review skill"])+def test_prompt_that_requires_the_skill_or_its_script_warns(prompt):+ assert _baseline_fairness_warnings(_case(prompt=prompt), skill_scripts=["review.py"])++[email protected]("generate", [generate_dataset._generate_simple, generate_dataset._generate_full])+def test_template_prompt_is_generic_when_description_requires_own_script(generate):+ cases = generate(_skill(description="Runs ./scripts/review.py against a manifest"))+ assert cases+ assert all("review.py" not in case["question"] for case in cases)+++def test_repeated_negated_skill_use_finishes_with_a_generous_resource_bound():+ # 360KB used to take over two minutes due to repeated growing-prefix scans.+ # A subprocess deadline guards runaway work; it is deliberately not a small+ # microbenchmark threshold and does not depend on relative wall-clock speed.+ code = (+ "from skillevaluator.tier3.evals_spec import _skill_use_match; "+ "assert _skill_use_match('not read SKILL.md ' * 22000, 'release-review') is None"+ )+ subprocess.run([sys.executable, "-c", code], check=True, timeout=30)++[email protected]("alias", ["release.review", "release review", "Straße"])+def test_declared_alias_is_literal_even_when_it_is_not_a_kebab_case_name(alias):+ (warning,) = _baseline_fairness_warnings(+ _case(alias, prompt="Check manifest.yaml", assertions=[f"Used {alias.upper()}."])+ )+ assert "grades skill use" in warning+++ "text",+ [+ "Explains that no positive with-skill trial loaded the skill, so the description or prompts should be fixed",+ "Explains that no agent read SKILL.md during the previous benchmark",+ ],+)+def test_report_interpretation_with_a_direct_negative_subject_does_not_warn(text):+ assert _baseline_fairness_warnings(_case(prompt="Explain the benchmark report", expected_output=text)) == []++[email protected]("identity", ["skill", "read"])+def test_identity_colliding_with_generic_wording_cannot_hide_skill_use(identity):+ assert _baseline_fairness_warnings(+ _case(identity, prompt="Check manifest.yaml", assertions=["The agent read SKILL.md"])+ )+++def test_huge_alias_with_many_unmatched_leaves_finishes_with_a_generous_resource_bound():+ # The alias is one scalar in the input, not work to repeat for every leaf.+ code = (+ "from skillevaluator.tier3.evals_spec import _baseline_fairness_warnings; "+ "warnings = _baseline_fairness_warnings({'expected_skill': 'r' * 200000, "+ "'expected_behavior': ['No issues'] * 4000}); "+ "assert len(warnings) == 1 and 'not fully checked' in warnings[0]"+ )+ subprocess.run([sys.executable, "-c", code], check=True, timeout=30)+++ ("text", "scripts"),+ [+ ("The agent used the installed skill", []),+ ("The agent used installed skill", []),+ ("The agent ran python3 -I -B -q -u -O review.py", ["review.py"]),+ ("The agent ran python3 review.py", ["\uff52\uff45\uff56\uff49\uff45\uff57.py"]),+ ("The agent ran python3 review.py", ["revie\u200bw.py"]),+ ("The agent used **release-review**.", []),+ ("The agent used [release-review](reference.md).", []),+ ("The agent ran **review.py**", ["review.py"]),+ ],+)+def test_incoming_wording_and_normalized_script_references_warn(text, scripts):+ assert _baseline_fairness_warnings(_case(prompt="Check manifest.yaml", assertions=[text]), skill_scripts=scripts)++[email protected]("adverb", ["ever", "even", "once", "also", "really"])+def test_single_adverb_does_not_turn_a_negated_read_into_a_requirement(adverb):+ assert (+ _baseline_fairness_warnings(+ _case(prompt="Check manifest.yaml", assertions=[f"The agent did not {adverb} read SKILL.md"])+ )+ == []+ )+++ ("text", "warns"),+ [+ ("The agent used the skill.", True),+ ("The agent used installed skill.", True),+ ("The agent used the installed skill.", True),+ ("The agent used the release-review skill.", True),+ ("The agent loaded the skill.json", False),+ ("The agent used installed skill.json", False),+ ("The agent used the release-review skill.json", False),+ ],+)+def test_terminal_punctuation_does_not_hide_skill_use_or_match_metadata(text, warns):+ warnings = _baseline_fairness_warnings(_case(prompt="Check manifest.yaml", assertions=[text]))+ assert bool(warnings) is warns+++# --- Negation that covers something else, odd shapes, names and bounds --------+++_REQUIRES_READING_SKILL_MD = [+ "The agent never edits files before reading SKILL.md",+ "The agent does not run any command without first reading SKILL.md",+ "The agent should not proceed until it has read SKILL.md",+ "The agent doesn't act before it reads SKILL.md",+ "The agent does not act unless it has read SKILL.md",+ "The agent will not edit files till it reads SKILL.md",+ "The agent never acts prior to reading SKILL.md",+ "The agent never skips reading SKILL.md",+ "The agent does not fail to read SKILL.md",+ "The agent must not edit anything if it has not read SKILL.md",+]++[email protected]("text", _REQUIRES_READING_SKILL_MD)[email protected]("field", ["prompt", "expected_output", "assertions"])+def test_a_negation_over_another_action_still_requires_reading_skill_md(field, text):+ # These forbid acting until SKILL.md was read, so they require what the+ # baseline cannot do. Only a negation of the read itself is met by it.+ fields = {"prompt": "Check manifest.yaml", "expected_output": "Two blockers", "assertions": ["Lists them"]}+ fields[field] = [text] if field == "assertions" else text++ (warning,) = _baseline_fairness_warnings(_case(**fields))++ assert warning.startswith(f"{field} ")+++ "text",+ [+ "The agent did not answer until it ran scripts/review.py",+ "The agent never answers before using release-review",+ "The agent does not edit files without first using the release-review skill",+ ],+)+def test_a_negation_over_another_action_still_requires_running_a_script_or_using_the_skill(text):+ entry = _case(prompt="Check manifest.yaml", expected_output="Two blockers", assertions=[text])++ (warning,) = _baseline_fairness_warnings(entry, skill_scripts=["review.py"])++ assert warning.startswith("assertions grades skill use")+++ "text",+ [+ "The agent did not read SKILL.md",+ "The agent didn't read SKILL.md",+ "The agent never reads SKILL.md",+ "Answers directly, without reading SKILL.md",+ "The agent answered without first reading SKILL.md",+ "The agent does not need to read SKILL.md",+ "The agent is not required to read SKILL.md",+ "The agent did not ask questions or read SKILL.md",+ "The agent did not read SKILL.md before acting",+ "The agent did not ask the user to read SKILL.md",+ "The agent did not run review.py before answering",+ "The agent answered without running review.py",+ "The agent never used release-review",+ "The agent did not use release-review before answering",+ "A direct answer; no release-review commands or skill workflow",+ ],+)+def test_a_negated_skill_use_is_still_met_by_the_baseline(text):+ entry = _case(prompt="Check manifest.yaml", expected_output=text, assertions=[text])++ assert _baseline_fairness_warnings(entry, skill_scripts=["review.py"]) == []+++ ("field", "value"),+ [+ ("assertions", [{"text": "The agent read SKILL.md"}]),+ ("assertions", [["The agent read SKILL.md"]]),+ ("assertions", [{"checks": ["Lists blockers", ["The agent read SKILL.md"]]}]),+ ("assertions", [{"The agent read SKILL.md": True}]),+ ("assertions", "The agent read SKILL.md"),+ ("expected_output", ["The agent read SKILL.md"]),+ ("expected_output", {"text": "The agent read SKILL.md"}),+ ("expected_output", {"steps": [["The agent read SKILL.md"]]}),+ ("prompt", ["Read SKILL.md, then check manifest.yaml"]),+ ("prompt", {"text": "Read SKILL.md, then check manifest.yaml"}),+ ],+)+def test_skill_use_is_found_in_a_field_of_any_shape(field, value):+ # The judge renders a list or mapping as written, so these are graded too.+ fields = {"prompt": "Check manifest.yaml", "expected_output": "Two blockers", "assertions": ["Lists them"]}+ fields[field] = value++ (warning,) = _baseline_fairness_warnings(_case(**fields))++ assert warning.startswith(f"{field} ")+++def test_outcome_text_in_an_odd_shape_does_not_warn():+ entry = _case(+ prompt={"text": "Check manifest.yaml"},+ expected_output=["Two blockers", {"detail": "missing SBOM"}],+ assertions=[{"text": "Lists both blockers"}, ["Names the file of each"], 3],+ )++ assert _baseline_fairness_warnings(entry) == []+++def test_a_field_with_too_many_values_is_reported_instead_of_skipped():+ padded = ["Lists a blocker"] * 1000 + ["The agent read SKILL.md"]+ cyclic: list = []+ cyclic.append(cyclic)++ for assertions, reason in (+ (padded, "assertions has more than 1000 values"),+ (cyclic, "assertions contains a cyclic value"),+ ):+ (warning,) = _baseline_fairness_warnings(_case(prompt="Check manifest.yaml", assertions=assertions))+ assert warning.startswith(reason)+++def _write_dataset_skill(tmp_path: Path, entry: dict, *, dirname: str = "release-review", name: str | None = None):+ skill = tmp_path / dirname+ (skill / "evals").mkdir(parents=True)+ (skill / "SKILL.md").write_text(+ f"---\nname: {name or dirname}\ndescription: Review releases\n---\n", encoding="utf-8"+ )+ entry = {"id": "case-001", "question": "Review manifest.yaml", "ground_truth": "Two blockers", **entry}+ (skill / "evals" / "evals.json").write_text(json.dumps([entry]), encoding="utf-8")+ return skill+++def _fairness_warnings(skill: Path) -> list[str]:+ return [+ result.message+ for result in validate_skillevaluators(skill)+ if result.status == "warning" and ("skill use" in result.message or "skill's files" in result.message)+ ]+++ "entry",+ [+ {},+ {"expected_skill": None},+ {"expected_skill": ""},+ {"expected_skill": 7},+ {"expected_skill": ["release-review"]},+ {"expected_skill": {"name": "release-review"}},+ {"expected_skill": "rr"},+ {"expected_skill": "x" * 5000},+ ],+ ids=["missing", "null", "empty", "int", "list", "dict", "other-name", "huge"],+)+def test_validate_checks_against_the_skills_own_name_whatever_the_entry_says(tmp_path: Path, entry):+ entry = {+ **entry,+ "question": "Use the skill at skills/release-review to review manifest.yaml",+ "expected_behavior": ["The agent used the release-review skill", "Lists the blockers"],+ }++ warnings = _fairness_warnings(_write_dataset_skill(tmp_path, entry))++ assert len(warnings) == 2+ assert warnings[0].startswith("question points at the skill's files")+ assert warnings[1].startswith("expected_behavior grades skill use")+++def test_validate_checks_against_the_name_in_the_skill_frontmatter(tmp_path: Path):+ entry = {"expected_skill": None, "expected_behavior": ["The agent used release-review and found 2 blockers"]}++ skill = _write_dataset_skill(tmp_path, entry, dirname="release-review-v2", name="release-review")++ (warning,) = _fairness_warnings(skill)+ assert warning.startswith("expected_behavior grades skill use")+++def test_validate_passes_a_negative_case_that_names_the_skill_in_negated_text(tmp_path: Path):+ # The shape of the cases in skills/skillevaluator/evals/evals.json: no skill expected, and the+ # text says what the agent does not do with it.+ entry = {+ "expected_skill": None,+ "ground_truth": "A direct implementation; no release-review commands or skill workflow.",+ "expected_behavior": ["Provides a working function", "Does not run or recommend release-review"],+ }++ assert _fairness_warnings(_write_dataset_skill(tmp_path, entry)) == []+++def test_validate_checks_an_expected_skill_that_names_the_skill_another_way(tmp_path: Path):+ entry = {"expected_skill": "rr", "expected_behavior": ["The agent used rr to review the manifest"]}++ (warning,) = _fairness_warnings(_write_dataset_skill(tmp_path, entry, dirname="release-review"))++ assert warning.startswith("expected_behavior grades skill use")+++def test_validate_reports_skill_use_in_odd_shapes_for_an_entry_with_no_skill_name(tmp_path: Path):+ entry = {"expected_behavior": [{"text": "The agent read SKILL.md"}, [["Lists the blockers"]]]}++ (warning,) = _fairness_warnings(_write_dataset_skill(tmp_path, entry))++ assert warning.startswith("expected_behavior grades skill use")+++def test_the_generation_warning_uses_the_skills_own_name(capsys):+ dataset = {+ "skill_name": "something-else",+ "evals": [+ {"id": "case-1", "prompt": "Review it", "expected_output": "x", "assertions": ["Used release-review"]}+ ],+ }++ generate_dataset._print_baseline_fairness_warnings(dataset, [], ("release-review",))++ assert "Warning: case case-1: assertions grades skill use" in capsys.readouterr().out+++# The text a warning quotes comes from the dataset, so it is cut and cleaned.+_QUOTE_LIMIT = 400+++ "text",+ [+ "read" + " " * 200_000 + "SKILL.md",+ "read " + "the " * 100_000 + "SKILL.md",+ "The agent read\n\n" + "\t " * 50_000 + "SKILL.md before acting",+ ],+ ids=["spaces", "articles", "newlines-and-tabs"],+)[email protected]("field", ["prompt", "expected_output", "assertions"])+def test_warnings_quote_a_bounded_amount_of_dataset_text(field, text):+ fields = {"prompt": "Check manifest.yaml", "expected_output": "Two blockers", "assertions": ["Lists them"]}+ fields[field] = [text] if field == "assertions" else text++ (warning,) = _baseline_fairness_warnings(_case(**fields))++ assert warning.startswith(f"{field} ")+ assert len(warning) < _QUOTE_LIMIT+ assert "read" in warning+++def test_quoted_dataset_text_drops_terminal_controls_and_credentials():+ from skillevaluator.tier3.evals_spec import _quoted++ quoted = _quoted("read \x1b]8;;http://evil.example\x07\x1b[31mSKILL.md\x1b[0m ghp_" + "a1B2c3D4" * 5)++ assert "\x1b" not in quoted+ assert "\x07" not in quoted+ assert "a1B2c3D4a1B2c3D4" not in quoted+++# A generous bound: the checks below take about a second or less, and the+# quadratic negation scan took from tens of seconds to minutes on inputs this size.+_TIME_LIMIT_S = 10.0+++def _timed(call) -> tuple[object, float]:+ started = time.perf_counter()+ result = call()+ return result, time.perf_counter() - started+++def test_many_negated_matches_are_scanned_in_linear_time():+ text = "not read SKILL.md " * 8_000 # 144 KB; the quadratic scan took about a minute++ warnings, elapsed = _timed(lambda: _baseline_fairness_warnings(_case(prompt=text, assertions=[text])))++ assert warnings == []+ assert elapsed < _TIME_LIMIT_S+++def test_a_large_dataset_entry_is_validated_in_bounded_time(tmp_path: Path):+ text = "The agent did not read SKILL.md and did not run review.py. " * 4_000 # 236 KB of negated matches+ entry = {"expected_behavior": [text], "ground_truth": text, "question": text}+ skill = _write_dataset_skill(tmp_path, entry)++ warnings, elapsed = _timed(lambda: _fairness_warnings(skill))++ assert warnings == []+ assert elapsed < _TIME_LIMIT_S+++ "text",+ [+ "read" + " " * 200_000 + "x",+ "read " + "the " * 100_000 + "x",+ "used" + " " * 200_000 + "release-review-x",+ "ran " + "a/" * 100_000 + "x",+ "skill " * 50_000,+ "release-review " * 20_000,+ "scripts/ " * 20_000,+ "read SKILL.md in " * 10_000,+ "read the SKILL.md files " * 10_000,+ "x" * 300_000,+ ],+ ids=[+ "read-spaces",+ "read-articles",+ "used-spaces",+ "run-path",+ "skill-words",+ "skill-name-words",+ "script-dirs",+ "elsewhere",+ "generic-noun",+ "one-long-word",+ ],+)+def test_adversarial_text_is_scanned_in_bounded_time(text):+ entry = _case(prompt=text, expected_output=text, assertions=[text])++ _, elapsed = _timed(lambda: _baseline_fairness_warnings(entry, skill_scripts=["review.py"]))++ assert elapsed < _TIME_LIMIT_Sdiff --git a/tests/tier3/test_dataset_generation_progress.py b/tests/tier3/test_dataset_generation_progress.pyindex ba13154c..f69d84ba 100644--- a/tests/tier3/test_dataset_generation_progress.py+++ b/tests/tier3/test_dataset_generation_progress.py@@ -52,6 +52,7 @@ def test_generation_announces_provider_and_handoff_on_stderr(generation_skill):assert "One-case starter: a starting point, not a representative evaluation" in result.stderrassert "no negative case that should not trigger the skill" in result.stderrassert f"skillevaluator create-eval-dataset {generation_skill} --full --force" in result.stderr+ assert "Add author guidance in evals/EVAL.md or pass --prompt before replacing the starter." in result.stderrassert "`--force` overwrites the starter and discards any edits to it." in result.stderrassert f"skillevaluator tier3 validate {generation_skill}" in result.stderrassert (generation_skill / "evals" / "evals.json").exists()diff --git a/tests/tier3/test_dataset_grounding.py b/tests/tier3/test_dataset_grounding.pyindex 2022deec..4719db19 100644--- a/tests/tier3/test_dataset_grounding.py+++ b/tests/tier3/test_dataset_grounding.py@@ -4,6 +4,7 @@import asyncioimport hashlibimport json+import refrom pathlib import Pathfrom types import SimpleNamespace@@ -120,10 +121,12 @@ def test_intent_case_002_keeps_all_authored_behaviors():case_002 = cases[1]- assert "The agent validates the invoice total against the ledger" in case_002["expected_behavior"]- assert "The agent reports each mismatched row" in case_002["expected_behavior"]- assert "The agent executed reconcile.py or explained how to run it" in case_002["expected_behavior"]- assert "The agent read the sample-skill SKILL.md before taking action" not in case_002["expected_behavior"]+ assert case_002["expected_behavior"][:2] == [+ "The agent validates the invoice total against the ledger",+ "The agent reports each mismatched row",+ ]+ # The no-skill baseline is graded on the same behaviors, so none grades skill use.+ assert not [item for item in case_002["expected_behavior"] if re.search(r"SKILL\.md|reconcile\.py", item)]@pytest.mark.parametrize("existing_dataset", [False, True], ids=["generated-cases", "authored-cases"])@@ -181,7 +184,8 @@ def test_main_trace_refines_real_trajectory_without_losing_authored_content(assert "expected outcome taken from an observed run; confirm it is correct" in case["review"]["reasons"]assert not any("used the sample-skill skill" in behavior for behavior in case["assertions"])- assert "The agent read SKILL.md before taking action" in case["assertions"]+ # Reading the skill's SKILL.md is skill use, which the no-skill baseline is not graded on.+ assert not [assertion for assertion in case["assertions"] if "SKILL.md" in assertion]assert "The agent executed: python reconcile.py inv.csv" in case["assertions"]trajectory_inputs = [entry for entry in result.dataset["generation"]["inputs"] if entry["kind"] == "trajectory"]assert len(trajectory_inputs) == 1@@ -422,11 +426,12 @@ def test_template_refinement_deduplicates_standard_behaviors_and_keeps_trajectorrefined = generate_dataset._refine_from_trajectory_template([case], {"case-1": trajectory})[0]behaviors = refined["expected_behavior"]- assert behaviors[:3] == [+ # The SKILL.md read is skill use, which the no-skill baseline is not graded on, so it is skipped.+ assert behaviors[:2] == ["The agent uses the approved workflow",- "The agent read SKILL.md before taking action","The agent executed: python reconcile.py inv.csv",]+ assert not [behavior for behavior in behaviors if "SKILL.md" in behavior]assert behaviors.count(generate_dataset._FINAL_RESPONSE_BEHAVIOR) == 1assert behaviors.count(generate_dataset.SECURITY_BEHAVIOR) == 1assert behaviors[-2:] == [generate_dataset._FINAL_RESPONSE_BEHAVIOR, generate_dataset.SECURITY_BEHAVIOR]@@ -531,12 +536,12 @@ def test_llm_refinement_falls_back_and_flags_missing_case_ids(monkeypatch):assert generate_dataset.SECURITY_BEHAVIOR in prompts[0]-def test_default_skill_grounding_keeps_template_cases_and_records_generation(tmp_path):+def test_explicit_skill_grounding_keeps_template_cases_and_records_generation(tmp_path):skill = _skill_dir(tmp_path)parsed = generate_dataset._parse_skill(skill)expected_cases = generate_dataset._generate_simple(parsed)- result = generate_dataset.main([str(skill), "--no-llm"])+ result = generate_dataset.main([str(skill), "--no-llm", "--grounding", "skill"])assert result.dataset["generation"]["grounding"] == "skill"assert result.dataset["generation"]["mode"] == "template_requested"@@ -617,7 +622,7 @@ def test_template_fallback_records_safe_reason(tmp_path, monkeypatch):raise ProviderConfigurationError("credential-value-that-must-not-leak")monkeypatch.setattr("skillevaluator.provider_config.resolve_llm_provider", provider_unavailable)- result = generate_dataset.main([str(skill), "--dry-run"])+ result = generate_dataset.main([str(skill), "--dry-run", "--grounding", "skill"])record = result.dataset["generation"]assert record["mode"] == "template_fallback"diff --git a/tests/tier3/test_generate_dataset_results.py b/tests/tier3/test_generate_dataset_results.pyindex d7cc0d97..aa2069ce 100644--- a/tests/tier3/test_generate_dataset_results.py+++ b/tests/tier3/test_generate_dataset_results.py@@ -327,7 +327,7 @@ def test_dry_run_plain_refine_uses_generated_cases_without_a_trajectory(tmp_path"---\nname: my-skill\ndescription: Does useful work\n---\n",encoding="utf-8",)- result = generate_dataset.main([str(skill), "--no-llm", "--dry-run", "--refine"])+ result = generate_dataset.main([str(skill), "--grounding", "skill", "--no-llm", "--dry-run", "--refine"])assert result.status == "preview"assert result.cases_count == 1@@ -344,11 +344,11 @@ def test_plain_refine_keeps_generated_cases_when_collection_is_unavailable(tmp_pmonkeypatch.setattr(generate_dataset, "_discover_trajectories", lambda *_args, **_kwargs: ({}, {}))monkeypatch.setattr(generate_dataset, "_run_agent_collect_trajectories", lambda *_args, **_kwargs: ({}, {}))- result = generate_dataset.main([str(skill), "--no-llm", "--refine"])+ result = generate_dataset.main([str(skill), "--grounding", "skill", "--no-llm", "--refine"])assert result.status == "created"assert result.cases_count == 1- assert result.dataset["evals"][0]["expected_output"].startswith("The agent used the my-skill skill")+ assert result.dataset["evals"][0]["expected_output"] == "A correct, complete result for: does useful work"def test_main_invalid_skill_raises_domain_error_without_printing(tmp_path, capsys):@@ -369,7 +369,7 @@ def test_main_reports_created_dataset_with_written_payload(tmp_path, extra_args,encoding="utf-8",)- result = generate_dataset.main([str(skill), "--no-llm", *extra_args])+ result = generate_dataset.main([str(skill), "--grounding", "skill", "--no-llm", *extra_args])assert result.status == "created"assert result.path == skill / "evals" / "evals.json"@@ -387,7 +387,7 @@ def test_main_full_with_author_negative_writes_four_cases(tmp_path):encoding="utf-8",)- result = generate_dataset.main([str(skill), "--no-llm", "--full"])+ result = generate_dataset.main([str(skill), "--grounding", "skill", "--no-llm", "--full"])assert result.cases_count == 4assert any(case["id"].endswith("-neg-001") for case in result.dataset["evals"])@@ -414,7 +414,7 @@ def test_force_write_failure_preserves_existing_dataset(tmp_path, monkeypatch):monkeypatch.setattr(generate_dataset.json, "dump", _partial_dump)with pytest.raises(DatasetGenerationError, match="Could not write dataset"):- generate_dataset.main([str(skill), "--no-llm", "--force"])+ generate_dataset.main([str(skill), "--grounding", "skill", "--no-llm", "--force"])assert output.read_bytes() == originalassert list(evals.iterdir()) == [output]@@ -432,7 +432,7 @@ def test_force_write_preserves_existing_dataset_permissions(tmp_path):output.write_text('{"skill_name":"original","evals":[]}\n', encoding="utf-8")output.chmod(0o640)- generate_dataset.main([str(skill), "--no-llm", "--force"])+ generate_dataset.main([str(skill), "--grounding", "skill", "--no-llm", "--force"])assert stat.S_IMODE(output.stat().st_mode) == 0o640@@ -448,7 +448,7 @@ def test_main_reports_existing_dataset_as_unchanged(tmp_path):output = evals / "evals.json"output.write_text('{"skill_name": "my-skill", "evals": []}', encoding="utf-8")- result = generate_dataset.main([str(skill), "--no-llm"])+ result = generate_dataset.main([str(skill), "--grounding", "skill", "--no-llm"])assert result.status == "unchanged"assert result.path == output@@ -485,7 +485,7 @@ def test_concurrent_programmatic_generation_has_no_cross_talk(tmp_path):skills.append(skill)def _generate(skill):- return EvaluationService().create_dataset(DatasetOptions(skill_path=skill, no_llm=True))+ return EvaluationService().create_dataset(DatasetOptions(skill_path=skill, no_llm=True, grounding="skill"))with ThreadPoolExecutor(max_workers=2) as executor:results = list(executor.map(_generate, skills))diff --git a/tests/tier3/test_workflow.py b/tests/tier3/test_workflow.pyindex 35dbcb66..16aba268 100644--- a/tests/tier3/test_workflow.py+++ b/tests/tier3/test_workflow.py@@ -141,6 +141,7 @@ def test_direct_workflow_generates_missing_dataset_then_evaluates(skill, configudef test_starter_guidance_command_replaces_the_existing_dataset(skill):dataset = _dataset(skill)original = dataset.read_bytes()+ (skill / "evals" / "EVAL.md").write_text("## Questions\n- Summarize this text\n", encoding="utf-8")result = CliRunner().invoke(create_dataset, [str(skill), "--full", "--force", "--no-llm"])assert result.exit_code == 0, result.outputassert dataset.read_bytes() != original