Multi-tier framework for evaluating AI agent skills and plugins with quality gates, security scanning, harness compatibility checks, semantic overlap detection, synthetic evaluation dataset generation, and live agent evaluation that measures how skills affect agent behavior. Ships reusable CI templates that bring every check to any repository.
Python agent-evaluationagent-pluginsagent-securityagent-skillsagentic-aibenchmarkci-templatesclaude-codecodexevaluateevaluationharnesspluginplugin-evaluationsecurity-scannerskill-evalskill-evaluationskill-evaluatorskill-gap-analysisskills
feat(datasets): choose a grounding source for generated datasets and keep authored expectations (#401)
Christopher Kevinf256e03152f5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4e07f305..726a13da 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,16 @@ All notable changes to SkillEvaluator are documented in this file.### Added+- Tier 3 generation provenance distinguishes LLM, requested-template, and+ template-fallback datasets, marks trace refinement and autopilot generation,+ and displays the source and review state in terminal, HTML, and BENCHMARK+ reports. Run payloads retain the generation record with shortened input hashes.++- `create-eval-dataset --grounding` selects skill, author-intent, or trace+ grounding. Generated datasets record relative input provenance and review+ flags for observed answers that differ from authored expectations and+ authored behavior steps omitted by refinement output.+- `tier3 validate` reports informational dataset coverage counts and concretegaps in text and JSON. Generated one-case starters now explain their limitsand point authors to full dataset generation and coverage validation.diff --git a/docs/cli-reference.mdx b/docs/cli-reference.mdxindex db3fba80..3f7e7f06 100644--- a/docs/cli-reference.mdx+++ b/docs/cli-reference.mdx@@ -548,7 +548,7 @@ skillevaluator create-eval-dataset ./my-skill --full```<Warning>-`--force` overwrites an existing `evals/evals.json`, including any hand-edited cases, and `--refine` implies `--force`. Use `--dry-run` first if you are unsure.+`--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.</Warning>| Flag | Default | Effect |@@ -558,9 +558,10 @@ 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`). |-| `--refine` | off | Refine cases using existing or collected trajectories. Reading trajectories from existing results does not require the `tier3` extra; when none exist, collecting one 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 `--refine`: results path containing agent trajectories (default: latest results). |-| `--results-dir DIRECTORY` | unset | With `--refine`: external results root to search for trajectories. |+| `--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. |## init-custom-graderdiff --git a/docs/eval-datasets.mdx b/docs/eval-datasets.mdxindex c60f6076..524d76d1 100644--- a/docs/eval-datasets.mdx+++ b/docs/eval-datasets.mdx@@ -200,10 +200,38 @@ requirements for the live evaluation. Use `validate PATH --no-autopilot` torequire an existing source instead of generating one.<Warning>- `--force` overwrites `evals/evals.json` without a backup. `--refine` implies- overwrite too — it produces the final version of the dataset.+ `--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.</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.++Generated datasets include a `generation` record with the mode, grounding+source, relative input paths and SHA-256 digests, generation time, and review+state. The mode is `llm`, `template_requested`, or `template_fallback`. After+reviewing 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+`template_fallback` with `skill` grounding. Cases whose authored expectations conflict with an observed answer, or+whose authored behavior steps are dropped by the refinement output, include+`review.status: needs_review` and reasons. The trace itself does not determine+whether every authored step occurred. A proposed ground truth based on an+observed answer is also flagged for review; inspect these cases before relying+on them as authored expectations.+### The four case buckets`--full` with an LLM provider targets one case per bucket, including a negativediff --git a/docs/reports.mdx b/docs/reports.mdxindex 18507801..e0846849 100644--- a/docs/reports.mdx+++ b/docs/reports.mdx@@ -222,6 +222,23 @@ report data and do not read the source tree or contact providers while renderingFull downloads and preview omission counts remain available; with-skill tokencharts are labeled separately from the resource table's two-arm comparisons.+### Dataset generation provenance++When a Tier 3 dataset has a generation record, the CLI evaluate summary,+validate's `AGENT_EVAL` section, the HTML overview, and `BENCHMARK.md` show one+dataset line. LLM-generated datasets name their grounding source and review+state. Template-generated datasets show whether templates were requested or+used as a fallback, explain that they are generic starters, and warn readers+to review them before relying on scores. The line adds the number of cases+marked `needs_review`; handwritten datasets and older datasets without+generation metadata have no line. Run reports retain the generation metadata,+with input hashes shortened to their first 12 characters and recorded paths+preserved. The LLM form is `Dataset: generated by <grounding> grounding, review+state <state>`. The template form is+`Dataset: generated from templates (requested|fallback: reason) — cases are+generic starters; review before relying on scores`. Either form appends+`; N cases need review` when applicable.+## File namingReport filenames follow two patterns, both under the output directory:diff --git a/src/skillevaluator/cli.py b/src/skillevaluator/cli.pyindex ef9a3f08..dd46e0e9 100644--- a/src/skillevaluator/cli.py+++ b/src/skillevaluator/cli.py@@ -1134,7 +1134,14 @@ def _ensure_autopilot_dataset(enabled=not quiet and progress != "off", stream=click.get_text_stream("stderr")):try:- service.create_autopilot_dataset(skill_path, use_llm=not no_llm)+ if no_llm:+ service.create_autopilot_dataset(+ skill_path,+ use_llm=False,+ fallback_reason="public LLM provider is not configured",+ )+ else:+ service.create_autopilot_dataset(skill_path, use_llm=True)generated = Trueexcept FileExistsError:echo("Autopilot: an evaluation source appeared concurrently; reusing it unchanged.")@@ -1147,7 +1154,7 @@ def _ensure_autopilot_dataset(echo(" Falling back to one deterministic starter case; review evals/ before using it as a benchmark.")dataset_note = f"deterministic starter — LLM generation failed: {diagnostic} Review evals/."if not eval_source_exists():- service.create_autopilot_dataset(skill_path, use_llm=False)+ service.create_autopilot_dataset(skill_path, use_llm=False, fallback_reason=diagnostic)generated = Trueif not eval_source_exists():raise click.ClickException("Autopilot dataset generation did not produce an evaluation source.")@@ -3431,6 +3438,7 @@ def evaluate(@click.option("--dry-run", is_flag=True, help="Preview without writing.")@click.option("--force", is_flag=True, help="Overwrite existing evals/evals.json.")@click.option("--prompt", type=click.Path(exists=True, path_type=Path), default=None)[email protected]("--grounding", type=click.Choice(["skill", "intent", "trace"]), default="skill")@click.option("--refine", is_flag=True, help="Refine cases using existing or collected trajectories.")@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)@@ -3441,6 +3449,7 @@ def create_dataset(dry_run: bool,force: bool,prompt: Path | None,+ grounding: str,refine: bool,from_results: Path | None,results_dir: Path | None,@@ -3457,6 +3466,7 @@ def create_dataset(dry_run=dry_run,force=force,prompt=prompt,+ grounding=grounding,refine=refine,from_results=from_results,results_dir=results_dir,diff --git a/src/skillevaluator/evaluation/options.py b/src/skillevaluator/evaluation/options.pyindex ad1345a4..066b2a2c 100644--- a/src/skillevaluator/evaluation/options.py+++ b/src/skillevaluator/evaluation/options.py@@ -76,6 +76,7 @@ class DatasetOptions:dry_run: bool = Falseforce: bool = Falseprompt: Path | None = None+ grounding: str = "skill"refine: bool = Falsefrom_results: Path | None = Noneresults_dir: Path | None = Nonediff --git a/src/skillevaluator/evaluation/service.py b/src/skillevaluator/evaluation/service.pyindex 72b23b1d..e39229b6 100644--- a/src/skillevaluator/evaluation/service.py+++ b/src/skillevaluator/evaluation/service.py@@ -76,11 +76,17 @@ class EvaluationService:return _create_dataset(options.skill_path, **options.engine_kwargs())- def create_autopilot_dataset(self, skill_path: Path, *, use_llm: bool) -> Path:+ def create_autopilot_dataset(+ self,+ skill_path: Path,+ *,+ use_llm: bool,+ fallback_reason: str | None = None,+ ) -> Path:"""Create one missing eval case for the CLI autopilot workflow."""from skillevaluator.tier3.generate_dataset import generate_one_case- return generate_one_case(skill_path, use_llm=use_llm)+ return generate_one_case(skill_path, use_llm=use_llm, fallback_reason=fallback_reason)def discover_latest_results(self, skill_path: Path, results_dir: Path | None = None) -> Path | None:"""Return the latest results directory for a skill, or None if absent.diff --git a/src/skillevaluator/evaluation/tier3_report.py b/src/skillevaluator/evaluation/tier3_report.pyindex a49f76c8..5ffb3faf 100644--- a/src/skillevaluator/evaluation/tier3_report.py+++ b/src/skillevaluator/evaluation/tier3_report.py@@ -545,6 +545,7 @@ def agent_eval_result_from_directory(persisted_dataset_summary=run_truth.get("dataset_summary"),dataset_digest=run_truth.get("dataset_digest"),dataset_digest_algorithm=run_truth.get("dataset_digest_algorithm"),+ dataset_provenance=run_truth.get("dataset_provenance"),run_id=run_truth.get("run_id"),publication_target=publication_target,publication_target_conflict=run_truth.get("publication_target_conflict"),@@ -680,6 +681,7 @@ def build_agent_eval_payload(persisted_dataset_summary: dict[str, Any] | None = None,dataset_digest: str | None = None,dataset_digest_algorithm: str | None = None,+ dataset_provenance: dict[str, Any] | None = None,historical_missing_score_policy: bool = False,run_id: str | None = None,publication_target: dict[str, str] | None = None,@@ -886,6 +888,9 @@ def build_agent_eval_payload(evidence_links = [link for link in harbor_summary.get("evidence_links") or [] if link.get("agent") in advice_agents]best_evidence_links = [link for link in evidence_links if link.get("agent") == best_agent]+ from skillevaluator.tier3.dataset_provenance import sanitize_generation_record++ safe_dataset_provenance = sanitize_generation_record(dataset_provenance)summary = {"schema_version": _SCHEMA_VERSION,"verdict": verdict,@@ -916,6 +921,8 @@ def build_agent_eval_payload(),"scored_attempts": sum(_as_nonnegative_int(agent.get("scored_attempts")) for agent in agent_payloads.values()),}+ if safe_dataset_provenance is not None:+ summary["dataset_provenance"] = safe_dataset_provenanceif publication_target_conflict in _PUBLICATION_TARGET_CONFLICT_MARKERS:summary["publication_target_conflict"] = publication_target_conflictcase_selection = _case_selection(run_config)@@ -993,6 +1000,7 @@ def build_agent_eval_payload("dataset_summary": dataset_summary,"dataset_digest": effective_dataset_digest,"dataset_digest_algorithm": effective_dataset_digest_algorithm,+ "dataset_provenance": safe_dataset_provenance,"score_policy": policy["score_policy"],"run_id": run_id,"publication_target": dict(publication_target) if isinstance(publication_target, dict) else None,@@ -4201,6 +4209,12 @@ def _run_truth_metadata(truth["dataset"] = [entry for entry in candidate["dataset"] if isinstance(entry, dict)]if "dataset_summary" not in truth and isinstance(candidate.get("dataset_summary"), dict):truth["dataset_summary"] = dict(candidate["dataset_summary"])+ if "dataset_provenance" not in truth:+ from skillevaluator.tier3.dataset_provenance import sanitize_generation_record++ provenance = sanitize_generation_record(candidate.get("dataset_provenance"))+ if provenance is not None:+ truth["dataset_provenance"] = provenancefor field_name in ("evaluator_version", "dataset_digest", "dataset_digest_algorithm"):value = candidate.get(field_name)if field_name not in truth and isinstance(value, str) and value.strip():diff --git a/src/skillevaluator/reporting/benchmark.py b/src/skillevaluator/reporting/benchmark.pyindex bf91ce09..52f86b9f 100644--- a/src/skillevaluator/reporting/benchmark.py+++ b/src/skillevaluator/reporting/benchmark.py@@ -52,6 +52,7 @@ from skillevaluator.reporting.base import (from skillevaluator.reporting.run_status import resolve_run_statusfrom skillevaluator.reporting.tier3_scope import completed_agent_result, validate_report_scopefrom skillevaluator.source_identity import evaluated_source_revision, recorded_evaluated_source+from skillevaluator.tier3.dataset_provenance import dataset_provenance_displayfrom skillevaluator.tier3_environments import HARBOR_ENV_MODESif TYPE_CHECKING:@@ -379,6 +380,10 @@ class BenchmarkReporter(ReporterBase):else:lines.append("- Tasks: not recorded (legacy or non-live result)")+ dataset_line, _ = dataset_provenance_display(ae.get("dataset_provenance") if ae else None)+ if dataset_line:+ lines.append(f"- {_publication_safe_inline(dataset_line)}")+dataset_provenance = agent_eval_publication_dataset_provenance(ae)if dataset_provenance is not None:digest, digest_algorithm = dataset_provenancediff --git a/src/skillevaluator/reporting/cli.py b/src/skillevaluator/reporting/cli.pyindex 1a080705..df8cd20a 100644--- a/src/skillevaluator/reporting/cli.py+++ b/src/skillevaluator/reporting/cli.py@@ -29,6 +29,7 @@ from typing import TYPE_CHECKINGfrom rich.console import Consolefrom rich.panel import Panelfrom rich.table import Table+from rich.text import Textfrom skillevaluator.constants import (DIMENSION_VERDICT_NEUTRAL_THRESHOLD,@@ -53,6 +54,7 @@ from skillevaluator.reporting.harbor_viewer import (from skillevaluator.reporting.presentation import FinalRenderContext, build_final_render_context, trial_coveragefrom skillevaluator.reporting.run_status import Status, result_statusfrom skillevaluator.reporting.terminal_styles import AMBER, FAINT, GREEN, RED, TEXT, grade_style, lift_style+from skillevaluator.tier3.dataset_provenance import dataset_provenance_displayfrom skillevaluator.utils.rich_markup import escape_markupif TYPE_CHECKING:@@ -212,6 +214,11 @@ class CLIReporter(ReporterBase):if id(result) not in rendered:agent_eval = result.metadata.get("agent_eval")if isinstance(agent_eval, dict):+ provenance_line, provenance_is_template = dataset_provenance_display(+ agent_eval.get("dataset_provenance")+ )+ if provenance_line:+ console.print(Text(f" {provenance_line}", style="yellow" if provenance_is_template else "dim"))self._print_harbor_artifacts(agent_eval, console)color = {Status.PASSED: "green", Status.FAILED: "red"}.get(context.command_status, "yellow")@@ -411,6 +418,9 @@ class CLIReporter(ReporterBase):f"\n [{vc}]Verdict: {verdict_text}[/{vc}] "f"(composite lift = [{composite_style}]{composite_text}[/{composite_style}])")+ provenance_line, provenance_is_template = dataset_provenance_display(agent_eval.get("dataset_provenance"))+ if provenance_line:+ console.print(Text(f" {provenance_line}", style="yellow" if provenance_is_template else "dim"))if verdict == "inconclusive":console.print(" [yellow]Skill never activated. Scores are diagnostic only; no lift verdict was computed.[/yellow]"diff --git a/src/skillevaluator/reporting/html.py b/src/skillevaluator/reporting/html.pyindex 25ddfe97..77cb3daf 100644--- a/src/skillevaluator/reporting/html.py+++ b/src/skillevaluator/reporting/html.py@@ -92,6 +92,7 @@ from skillevaluator.reporting.tier3_scope import completed_agent_result, validatfrom skillevaluator.reporting.trial_charts import steps_by_case_chartfrom skillevaluator.skillspector_provenance import skillspector_provenance_recordsfrom skillevaluator.source_identity import recorded_evaluated_source+from skillevaluator.tier3.dataset_provenance import dataset_provenance_displayif TYPE_CHECKING:from skillevaluator.models import ValidationResult@@ -3037,6 +3038,9 @@ class HTMLReporter(ReporterBase):tier2_summary = self._compute_tier_summary(tier2_results, presentation=context.tiers[2])tier3_summary = self._compute_tier_summary(tier3_results, presentation=context.tiers[3])tier3_preview, tier3_preview_notice = _bounded_tier3_preview(tier3_data)+ tier3_dataset_provenance_line, tier3_dataset_provenance_warning = dataset_provenance_display(+ tier3_data.get("dataset_provenance") if isinstance(tier3_data, dict) else None+ )tier3_canonical_data, tier3_canonical_encoding = _canonical_tier3_embed(tier3_data)tier3_truncation = tier3_data.get("report_truncation", {}) if isinstance(tier3_data, dict) else {}@@ -3376,6 +3380,8 @@ class HTMLReporter(ReporterBase):content_label_plural=cl + "s",quality_scores=quality_scores_by_skill,tier3=tier3_preview,+ tier3_dataset_provenance_line=tier3_dataset_provenance_line,+ tier3_dataset_provenance_warning=tier3_dataset_provenance_warning,chart_assets=_load_chart_assets,tier3_canonical_data=tier3_canonical_data,tier3_canonical_encoding=tier3_canonical_encoding,diff --git a/src/skillevaluator/reporting/markdown.py b/src/skillevaluator/reporting/markdown.pyindex 40278c93..da6caebc 100644--- a/src/skillevaluator/reporting/markdown.py+++ b/src/skillevaluator/reporting/markdown.py@@ -42,6 +42,7 @@ from skillevaluator.reporting.harbor_viewer import (safe_url,)from skillevaluator.reporting.run_status import Status, resolve_run_status, result_status+from skillevaluator.tier3.dataset_provenance import dataset_provenance_displayif TYPE_CHECKING:from skillevaluator.models import Finding, ValidationResult@@ -355,6 +356,9 @@ class MarkdownReporter(ReporterBase):lines.append("")composite_text = _format_report_number(composite, signed=True)lines.append(f"**Verdict:** {verdict} (composite lift = {composite_text})")+ provenance_line, _ = dataset_provenance_display(ae.get("dataset_provenance"))+ if provenance_line:+ lines.append(_markdown_inline_text(provenance_line))if verdict == "INCONCLUSIVE":lines.append("Skill never activated. Scores are diagnostic only; no lift verdict was computed.")runtime_number = _finite_report_number(runtime)diff --git a/src/skillevaluator/reporting/templates/report.html.j2 b/src/skillevaluator/reporting/templates/report.html.j2index 346f9202..7d34d8ab 100644--- a/src/skillevaluator/reporting/templates/report.html.j2+++ b/src/skillevaluator/reporting/templates/report.html.j2@@ -2256,6 +2256,8 @@.t3-agent-scorecards-row { display:grid; grid-template-columns:minmax(220px,0.85fr) repeat(2,minmax(260px,1fr)); gap:1.25rem; align-items:stretch; margin-top:0.75rem; }.t3-agent-scorecard-list { display:grid; gap:1rem; align-content:start; }.t3-overview-lead { background:linear-gradient(135deg,var(--bg),var(--bg-secondary)); border:1px solid var(--border-color); border-left:4px solid var(--secondary-color); border-radius:12px; padding:1rem 1.15rem; box-shadow:var(--shadow); color:var(--dark-text); line-height:1.55; margin:0 0 1rem; }+ .t3-dataset-provenance { margin:0 0 1rem; padding:0.7rem 0.9rem; border-left:4px solid var(--border-color); border-radius:6px; background:var(--bg-secondary); color:var(--dark-text); }+ .t3-dataset-provenance.warning { border-left-color:var(--warning-color); background:var(--badge-warn-bg); color:var(--badge-warn-tx); }.t3-harbor-panel { background:var(--bg); border:1px solid var(--border-color); border-left:4px solid var(--secondary-color); border-radius:12px; padding:0.95rem 1.1rem; box-shadow:var(--shadow); margin:0 0 1rem; display:flex; gap:1rem; justify-content:space-between; align-items:center; flex-wrap:wrap; }.t3-harbor-panel strong { color:var(--dark-text); }.t3-harbor-panel p { color:var(--text-secondary); margin:0.2rem 0 0; font-size:0.85rem; line-height:1.45; }@@ -2521,6 +2523,9 @@{% endif %}{% endif %}</div>+ {% if tier3_dataset_provenance_line %}+ <p class="t3-dataset-provenance{{ ' warning' if tier3_dataset_provenance_warning else '' }}">{{ tier3_dataset_provenance_line }}</p>+ {% endif %}{% if harbor_jobs %}<div class="t3-harbor-panel"><div>diff --git a/src/skillevaluator/tier3/commands.py b/src/skillevaluator/tier3/commands.pyindex 7df35dde..02b6e283 100644--- a/src/skillevaluator/tier3/commands.py+++ b/src/skillevaluator/tier3/commands.py@@ -431,6 +431,7 @@ def create_dataset(dry_run: bool = False,force: bool = False,prompt: Path | None = None,+ grounding: str = "skill",refine: bool = False,from_results: Path | None = None,results_dir: Path | None = None,@@ -449,6 +450,8 @@ def create_dataset(argv.append("--force")if prompt:argv.extend(["--prompt", str(prompt.resolve())])+ if grounding != "skill":+ argv.extend(["--grounding", grounding])if refine:argv.append("--refine")if from_results:diff --git a/src/skillevaluator/tier3/dataset_provenance.py b/src/skillevaluator/tier3/dataset_provenance.pynew file mode 100644index 00000000..38d00516--- /dev/null+++ b/src/skillevaluator/tier3/dataset_provenance.py@@ -0,0 +1,91 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import Any++_GENERATION_MODES = frozenset({"llm", "template", "template_requested", "template_fallback"})+_GROUNDING_MODES = frozenset({"skill", "intent", "trace"})+_TEMPLATE_WARNING = "cases are generic starters; review before relying on scores"+++def sanitize_generation_record(value: object) -> dict[str, Any] | None:+ if not isinstance(value, Mapping):+ return None+ mode = value.get("mode")+ if not isinstance(mode, str) or mode not in _GENERATION_MODES:+ return None++ record: dict[str, Any] = {"mode": mode}+ grounding = value.get("grounding")+ if isinstance(grounding, str) and grounding in _GROUNDING_MODES:+ record["grounding"] = grounding+ generated_at = value.get("generated_at")+ if isinstance(generated_at, str):+ record["generated_at"] = generated_at+ review_state = value.get("review_state")+ if isinstance(review_state, str) and review_state in {"needs_review", "unreviewed", "reviewed"}:+ record["review_state"] = review_state+ if value.get("refined") is True:+ record["refined"] = True++ fallback_reason = value.get("fallback_reason")+ if isinstance(fallback_reason, str):+ from skillevaluator.evaluation.tier3_findings import sanitize_grader_text+ from skillevaluator.utils.rich_markup import strip_terminal_controls++ safe_reason = " ".join(strip_terminal_controls(sanitize_grader_text(fallback_reason, max_len=256)).split())+ if safe_reason:+ record["fallback_reason"] = safe_reason++ raw_count = value.get("needs_review_count")+ if isinstance(raw_count, int) and not isinstance(raw_count, bool) and 0 <= raw_count <= 1_000_000_000:+ record["needs_review_count"] = raw_count++ raw_inputs = value.get("inputs")+ if isinstance(raw_inputs, list):+ inputs = []+ for item in raw_inputs[:32]:+ if not isinstance(item, Mapping):+ continue+ entry: dict[str, str] = {}+ for key in ("kind", "path"):+ field = item.get(key)+ if isinstance(field, str):+ entry[key] = field+ digest = item.get("sha256")+ if isinstance(digest, str):+ entry["sha256"] = digest[:12]+ inputs.append(entry)+ record["inputs"] = inputs+ return record+++def dataset_provenance_display(value: object) -> tuple[str | None, bool]:+ record = sanitize_generation_record(value)+ if record is None:+ return None, False++ mode = record["mode"]+ if mode == "llm":+ grounding = record.get("grounding")+ if grounding not in _GROUNDING_MODES:+ return None, False+ review_state = record.get("review_state", "unknown")+ line = f"Dataset: generated by {grounding} grounding, review state {review_state}"+ is_template = False+ elif mode == "template":+ line = f"Dataset: generated from templates — {_TEMPLATE_WARNING}"+ is_template = True+ else:+ requested_or_fallback = (+ "requested"+ if mode == "template_requested"+ else f"fallback: {record.get('fallback_reason') or 'LLM generation was unavailable'}"+ )+ line = f"Dataset: generated from templates ({requested_or_fallback}) — {_TEMPLATE_WARNING}"+ is_template = True++ needs_review = record.get("needs_review_count", 0)+ if needs_review > 0:+ line += f"; {needs_review} cases need review"+ return line, is_templatediff --git a/src/skillevaluator/tier3/generate_dataset.py b/src/skillevaluator/tier3/generate_dataset.pyindex d61c6877..12ca8582 100644--- a/src/skillevaluator/tier3/generate_dataset.py+++ b/src/skillevaluator/tier3/generate_dataset.py@@ -41,6 +41,7 @@ Agent-refined mode (--refine):import argparseimport asyncio+import hashlibimport jsonimport osimport re@@ -48,6 +49,7 @@ import secretsimport statimport sysfrom collections.abc import Sequence+from datetime import UTC, datetimefrom pathlib import Pathfrom typing import Any@@ -55,6 +57,7 @@ import yamlfrom skillevaluator.constants import EXECUTABLE_SKILL_DIRSfrom skillevaluator.evaluation.results import DatasetGenerationError, DatasetGenerationResult+from skillevaluator.tier3.dataset_utils import load_dataset_entriesfrom skillevaluator.tier3.eval_core.codex_tool_call_normalizer import atif_content_textfrom skillevaluator.tier3.eval_core.optional_reference import normalize_expected_behaviors, normalize_optional_referencefrom skillevaluator.validators.frontmatter_parser import FRONTMATTER_PATTERN@@ -67,9 +70,14 @@ _INTERACTIVE_RE = re.compile(r"interactive|opens?\s+a?\s*browser|waits?\s+for\s+(the\s+)?user|device.code\s+flow",re.IGNORECASE,)+_FINAL_RESPONSE_BEHAVIOR = "The agent's final response directly addresses the user's request"-def _to_agentskills_dataset(skill_name: str, cases: list[dict[str, Any]]) -> dict[str, Any]:+def _to_agentskills_dataset(+ skill_name: str,+ cases: list[dict[str, Any]],+ generation: dict[str, Any] | None = None,+) -> 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:@@ -93,8 +101,13 @@ def _to_agentskills_dataset(skill_name: str, cases: list[dict[str, Any]]) -> dic):if key in case:entry[key] = case[key]+ if isinstance(case.get("review"), dict):+ entry["review"] = case["review"]evals.append(entry)- return {"skill_name": skill_name, "evals": evals}+ dataset = {"skill_name": skill_name, "evals": evals}+ if generation is not None:+ dataset["generation"] = generation+ return datasetdef _parse_skill(skill_path: Path, prompt_file: str | None = None) -> dict[str, Any]:@@ -300,11 +313,16 @@ def _generate_simple(skill: dict[str, Any]) -> list[dict[str, Any]]:question = eval_hints["questions"][0] if eval_hints["questions"] else f"Use {name} to {desc.lower().rstrip('.')}"- behaviors = [f"The agent read the {name} SKILL.md before taking action"]+ skill_behaviors = [f"The agent read the {name} SKILL.md before taking action"]if script:- behaviors.append(f"The agent executed {script} or explained how to run it")- behaviors.append("The agent's final response directly addresses the user's request")- behaviors.extend(eval_hints["behaviors"])+ 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)return _normalize_generated_cases(@@ -343,11 +361,16 @@ def _generate_full(skill: dict[str, Any]) -> list[dict[str, Any]]:eval_hints = _extract_eval_hints(skill.get("eval_prompt", ""))hint_qs = eval_hints["questions"]- pos_behaviors = [f"The agent read the {name} SKILL.md before taking action"]+ skill_behaviors = [f"The agent read the {name} SKILL.md before taking action"]if script:- pos_behaviors.append(f"The agent executed {script} or explained how to run it")- pos_behaviors.append("The agent's final response directly addresses the user's request")- pos_behaviors.extend(eval_hints["behaviors"])+ 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.append(_FINAL_RESPONSE_BEHAVIOR)pos_behaviors.append(SECURITY_BEHAVIOR)cases = [@@ -367,7 +390,11 @@ def _generate_full(skill: dict[str, Any]) -> list[dict[str, Any]]:"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",- *pos_behaviors[1:],+ *[+ behavior+ for behavior in pos_behaviors+ if behavior != f"The agent read the {name} SKILL.md before taking action"+ ],],},{@@ -415,6 +442,8 @@ async def _generate_with_llm(except ProviderConfigurationError as exc:if not fallback_to_template:raise RuntimeError("LLM dataset generation requires a configured provider") from exc+ skill["_generation_mode"] = "template_fallback"+ skill["_generation_fallback_reason"] = "public LLM provider is not configured"print("Public LLM provider is not configured. Using deterministic template mode.")return _generate_full(skill) if full else _generate_simple(skill)@@ -440,16 +469,25 @@ FIELD QUALITY GUIDELINES (follow strictly):"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"}"""- # Build rich context block from SKILL.md body + developer eval guidance- context_sections = []- if skill_content:- context_sections.append(f"""--- SKILL.MD CONTENT (use this to understand what the skill does) ---+ # Build rich context block from SKILL.md body + developer eval guidance.+ skill_section = (+ f"""--- SKILL.MD CONTENT (use this to understand what the skill does) ---{skill_content}---- END SKILL.MD ---""")- if eval_prompt:- context_sections.append(f"""--- DEVELOPER EVAL GUIDANCE (high priority — the skill author provided this) ---+--- END SKILL.MD ---"""+ if skill_content+ else ""+ )+ guidance_section = (+ f"""--- DEVELOPER EVAL GUIDANCE (high priority — the skill author provided this) ---{eval_prompt}---- END DEVELOPER EVAL GUIDANCE ---""")+--- END DEVELOPER EVAL GUIDANCE ---"""+ if eval_prompt+ else ""+ )+ if skill.get("grounding") == "intent":+ context_sections = [section for section in (guidance_section, skill_section) if section]+ else:+ context_sections = [section for section in (skill_section, guidance_section) if section]context_block = "\n\n".join(context_sections)if full:@@ -568,11 +606,18 @@ No other fields."""diagnostic = llm_failure_diagnostic(exc)if not fallback_to_template:raise DatasetGenerationError(f"LLM dataset generation failed: {diagnostic}") from exc+ skill["_generation_mode"] = "template_fallback"+ skill["_generation_fallback_reason"] = diagnosticprint(f"Warning: LLM generation failed: {diagnostic} Using deterministic template mode.")return _generate_full(skill) if full else _generate_simple(skill)-def generate_one_case(skill_path: Path, *, use_llm: bool) -> Path:+def generate_one_case(+ skill_path: Path,+ *,+ use_llm: bool,+ fallback_reason: str | None = None,+) -> Path:"""Create exactly one new eval case without overwriting an existing dataset."""skill_path = skill_path.resolve()evals_dir = skill_path / "evals"@@ -582,16 +627,27 @@ def generate_one_case(skill_path: Path, *, use_llm: bool) -> Path:if output_path.exists():raise FileExistsError(f"Dataset already exists: {output_path}")skill = _parse_skill(skill_path)- cases = (- asyncio.run(_generate_with_llm(skill, fallback_to_template=False, announce_provider=False))- if use_llm- else _generate_simple(skill)- )+ if use_llm:+ cases = asyncio.run(_generate_with_llm(skill, fallback_to_template=False, announce_provider=False))+ skill["_generation_mode"] = "llm"+ else:+ cases = _generate_simple(skill)+ skill["_generation_mode"] = "template_fallback"+ 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")+ generation = _generation_record(+ skill_path,+ mode=str(skill["_generation_mode"]),+ grounding="skill",+ skill=skill,+ prompt_path=None,+ trajectory_paths={},+ cases=cases,+ )evals_dir.mkdir(parents=True, exist_ok=True)with output_path.open("x", encoding="utf-8") as output:- json.dump(_to_agentskills_dataset(skill["name"], cases), output, indent=2, ensure_ascii=False)+ json.dump(_to_agentskills_dataset(skill["name"], cases, generation), output, indent=2, ensure_ascii=False)output.write("\n")return output_path@@ -647,7 +703,9 @@ def _discover_trajectories(skill_path: Path,from_results: str | None = None,results_dir: str | Path | None = None,-) -> dict[str, dict[str, Any]]:+ *,+ return_sources: 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.@@ -659,7 +717,7 @@ def _discover_trajectories(from skillevaluator.tier3.results_location import resolve_explicit_or_latest_resultsexcept ImportError:print(" Warning: eval_core not importable. Cannot discover trajectories.")- return {}+ return ({}, {}) if return_sources else {}results_dir = resolve_explicit_or_latest_results(skill_path,@@ -668,7 +726,7 @@ def _discover_trajectories()if not results_dir.exists():- return {}+ return ({}, {}) if return_sources else {}agent_priority = ["claude-code",@@ -686,6 +744,7 @@ def _discover_trajectories(continuetrajectories: dict[str, dict[str, Any]] = {}+ sources: dict[str, Path] = {}last_good_source = "unknown"for trial_dir in sorted(trials_dir.iterdir()):if not trial_dir.is_dir():@@ -697,13 +756,21 @@ def _discover_trajectories(traj, meta = load_trajectory_with_fallback(traj_path, logs_dir=trial_dir)if traj and traj.get("steps"):trajectories[case_id] = traj+ source_name = meta.get("source")+ source_path = Path(source_name) if isinstance(source_name, str) else traj_path+ if not source_path.is_absolute():+ source_path = trial_dir / source_path+ if not source_path.is_file():+ source_path = traj_path+ if source_path.is_file():+ sources[case_id] = source_pathlast_good_source = meta.get("source", "unknown")if trajectories:print(f" Found {len(trajectories)} trajectory(s) from {agent_name} ({last_good_source})")- return trajectories+ return (trajectories, sources) if return_sources else trajectories- return {}+ return ({}, {}) if return_sources else {}def _summarize_trajectory(trajectory: dict[str, Any], max_steps: int = 25) -> str:@@ -747,8 +814,11 @@ def _run_agent_collect_trajectories(skill_path: Path,cases: list[dict[str, Any]],results_dir: str | Path | None = None,-) -> dict[str, dict[str, Any]]:- """Run claude-code agent via Harbor and return per-case trajectories.+ *,+ return_sources: bool = False,+ strict: bool = False,+) -> dict[str, dict[str, Any]] | tuple[dict[str, dict[str, Any]], dict[str, Path]]:+ """Run claude-code agent via Harbor and return trajectories and optional source paths.Writes initial cases to evals/evals.json, runs Harbor, then discoversthe trajectory files Harbor wrote to the resolved results root.@@ -757,17 +827,23 @@ def _run_agent_collect_trajectories(from skillevaluator.utils.tool_runner import resolve_tool_path+ def failed(reason: str) -> dict[str, dict[str, Any]] | tuple[dict[str, dict[str, Any]], dict[str, Path]]:+ if strict:+ raise DatasetGenerationError(reason)+ print(f" Warning: {reason}")+ return ({}, {}) if return_sources else {}+if not resolve_tool_path("harbor"):print(" Warning: harbor CLI not found. Reinstall with the Tier 3 extra: "'uv tool install "skillevaluator[all] @ git+https://github.com/NVIDIA/SkillEvaluator.git"')print(" Skipping agent run — using initial cases without refinement.")- return {}+ return failed("Harbor CLI is not available.")if not shutil.which("docker"):print(" Warning: Docker not found. Harbor requires Docker.")print(" Skipping agent run — using initial cases without refinement.")- return {}+ return failed("Docker is not available; Harbor requires Docker.")from skillevaluator.provider_config import ProviderConfigurationError, resolve_llm_provider@@ -776,7 +852,7 @@ def _run_agent_collect_trajectories(except ProviderConfigurationError as exc:print(f" Warning: public LLM provider is not configured ({exc}).")print(" Skipping agent run — using initial cases without refinement.")- return {}+ return failed(f"Public LLM provider is not configured: {exc}")evals_dir = skill_path / "evals"evals_dir.mkdir(parents=True, exist_ok=True)@@ -797,12 +873,12 @@ def _run_agent_collect_trajectories(try:from skillevaluator.tier3.harbor.runner import run_harbor_evalfrom skillevaluator.tier3.results_location import resolve_results_root- except ImportError:+ except ImportError as exc:print(" Warning: harbor runner not importable. Reinstall with the Tier 3 extra: "'uv tool install "skillevaluator[all] @ git+https://github.com/NVIDIA/SkillEvaluator.git"')- return {}+ return failed(f"Harbor runner could not be imported: {exc}")print(" Running claude-code agent via Harbor (skip-baseline)...")try:@@ -813,24 +889,31 @@ def _run_agent_collect_trajectories(output_dir=resolve_results_root(skill_path, results_dir) if results_dir else None,)- if "error" in result:- errors = result["error"]- if isinstance(errors, list):- errors = "; ".join(errors)- print(f" Warning: Harbor eval returned error: {errors}")- return {}-except Exception as e:print(f" Warning: Harbor eval failed: {e}")- return {}+ return failed(f"Harbor collection failed: {e}")++ if not isinstance(result, dict):+ return failed("Harbor collection returned an invalid result.")+ if "error" in result:+ errors = result["error"]+ if isinstance(errors, list):+ errors = "; ".join(errors)+ print(f" Warning: Harbor eval returned error: {errors}")+ return failed(f"Harbor eval returned an error: {errors}")- return _discover_trajectories(skill_path, results_dir=results_dir)+ discovered = _discover_trajectories(skill_path, results_dir=results_dir, return_sources=True)+ if return_sources:+ return discovered if isinstance(discovered, tuple) else (discovered, {})+ return discovered[0] if isinstance(discovered, tuple) else discoveredasync def _refine_with_llm(skill: dict[str, Any],cases: list[dict[str, Any]],trajectories: dict[str, dict[str, Any]],+ *,+ authored_case_ids: set[str] | None = None,) -> list[dict[str, Any]]:"""Refine eval cases using agent trajectory evidence via LLM."""if not trajectories:@@ -854,7 +937,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.")- return _refine_from_trajectory_template(cases, trajectories, skill=skill)+ return _refine_from_trajectory_template(+ cases,+ trajectories,+ skill=skill,+ authored_case_ids=authored_case_ids,+ )name = skill["name"]eval_prompt = skill.get("eval_prompt", "")@@ -895,8 +983,7 @@ PRIORITY 2 — AGENT TRAJECTORY (above):PRIORITY 3 — DEFAULTS:- Keep "question" unchanged unless the agent clearly misunderstood it.- Keep "id", "expected_skill", "expected_script" unchanged.- - Always include a security behavior: "The agent did not leak secrets, run destructive- commands, or access resources outside the expected workspace"+ - Always include a security behavior: "{SECURITY_BEHAVIOR}"- For negative cases (expected_skill is null), keep existing behaviors about NOTexecuting tools.@@ -917,19 +1004,76 @@ Return ONLY the refined JSON array. No other text."""text = match.group(1) if match else "[]"refined = json.loads(text)+ if not isinstance(refined, list) or any(not isinstance(case, dict) for case in refined):+ raise ValueError("refinement output must be a list of case objects")for case in refined: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):- behaviors.append(SECURITY_BEHAVIOR)-- return refined+ behaviors = case.get("expected_behavior")+ behaviors = behaviors if isinstance(behaviors, list) else []+ case["expected_behavior"] = [+ behavior for behavior in behaviors if behavior not in {_FINAL_RESPONSE_BEHAVIOR, SECURITY_BEHAVIOR}+ ]++ input_ids = {case.get("id") for case in cases}+ refined_by_id: dict[str, dict[str, Any]] = {}+ duplicate_ids: set[str] = set()+ for case in refined:+ case_id = case.get("id")+ if not isinstance(case_id, str) or case_id not in input_ids:+ continue+ if case_id in refined_by_id:+ duplicate_ids.add(case_id)+ else:+ refined_by_id[case_id] = case+ for case_id in duplicate_ids:+ refined_by_id.pop(case_id, None)+ refined_cases: list[dict[str, Any]] = []+ for authored in cases:+ case = refined_by_id.get(authored.get("id"))+ if case is None:+ fallback = _refine_from_trajectory_template(+ [authored],+ trajectories,+ skill=skill,+ authored_case_ids=authored_case_ids,+ )[0]+ _mark_case_for_review(fallback, "refinement output did not return this case")+ refined_cases.append(fallback)+ continue+ is_authored = authored_case_ids is None or authored.get("id") in authored_case_ids+ original_behaviors = authored.get("expected_behavior") if is_authored else []+ original_behaviors = original_behaviors if isinstance(original_behaviors, list) else []+ behaviors = case.get("expected_behavior")+ behaviors = behaviors if isinstance(behaviors, list) else []+ behaviors = _restore_authored_behaviors(case, original_behaviors, behaviors)+ case["expected_behavior"] = [+ behavior for behavior in behaviors if behavior not in {_FINAL_RESPONSE_BEHAVIOR, SECURITY_BEHAVIOR}+ ] + [_FINAL_RESPONSE_BEHAVIOR, SECURITY_BEHAVIOR]+ trajectory = trajectories.get(authored.get("id"))+ ground_truth = authored.get("ground_truth") if is_authored else None+ proposed = 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 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+ elif final_message:+ case["ground_truth"] = final_message[:400]+ _mark_case_for_review(case, "expected outcome taken from an observed run; confirm it is correct")+ refined_cases.append(case)++ return refined_casesexcept Exception as e:print(f" LLM refinement failed ({e}). Applying template-based refinement.")- return _refine_from_trajectory_template(cases, trajectories, skill=skill)+ return _refine_from_trajectory_template(+ cases,+ trajectories,+ skill=skill,+ authored_case_ids=authored_case_ids,+ )def _extract_agent_final_message(trajectory: dict[str, Any]) -> str:@@ -943,10 +1087,43 @@ def _extract_agent_final_message(trajectory: dict[str, Any]) -> str:return ""+def _mark_case_for_review(case: dict[str, Any], reason: str) -> None:+ review = case.get("review")+ if not isinstance(review, dict):+ review = {"status": "needs_review", "reasons": []}+ reasons = review.get("reasons")+ if not isinstance(reasons, list):+ reasons = []+ if reason not in reasons:+ reasons.append(reason)+ case["review"] = {"status": "needs_review", "reasons": reasons}+++def _restore_authored_behaviors(+ case: dict[str, Any],+ authored_behaviors: list[Any],+ refined_behaviors: list[Any],+) -> list[Any]:+ standard_behaviors = {_FINAL_RESPONSE_BEHAVIOR, SECURITY_BEHAVIOR}+ behaviors = list(refined_behaviors)+ missing_behaviors = [+ behavior+ for behavior in authored_behaviors+ if isinstance(behavior, str) and behavior not in standard_behaviors and behavior not in behaviors+ ]+ for behavior in missing_behaviors:+ _mark_case_for_review(case, f"refinement dropped authored step: {behavior}")+ for behavior in reversed(missing_behaviors):+ behaviors.insert(0, behavior)+ return behaviors++def _refine_from_trajectory_template(cases: list[dict[str, Any]],trajectories: dict[str, dict[str, Any]],skill: dict[str, Any] | None = None,+ *,+ authored_case_ids: set[str] | None = None,) -> list[dict[str, Any]]:"""Refine all eval fields from trajectory + developer guidance without LLM.@@ -975,6 +1152,10 @@ def _refine_from_trajectory_template(case = dict(case)+ is_authored = authored_case_ids is None or case.get("id") in authored_case_ids+ authored_behaviors = case.get("expected_behavior") if is_authored else []+ authored_behaviors = authored_behaviors if isinstance(authored_behaviors, list) else []+# --- Refine expected_behavior ---traj_behaviors: list[str] = []seen: set[str] = set()@@ -1000,24 +1181,38 @@ def _refine_from_trajectory_template(seen.add(b)is_negative = case.get("expected_skill") is None- merged_behaviors: list[str] = []+ standard_behaviors = {_FINAL_RESPONSE_BEHAVIOR, SECURITY_BEHAVIOR}+ merged_behaviors: list[str] = [+ item for item in authored_behaviors if isinstance(item, str) and item not in standard_behaviors+ ]+ authored_set = set(merged_behaviors)if traj_behaviors:- merged_behaviors.extend(traj_behaviors)+ merged_behaviors.extend(+ item for item in traj_behaviors if item not in authored_set and item not in standard_behaviors+ )+ seen = set(merged_behaviors)if not is_negative:for db in developer_behaviors:- if db not in seen:+ if db not in seen and db not in standard_behaviors:merged_behaviors.append(db)seen.add(db)- if merged_behaviors:- merged_behaviors.append("The agent's final response directly addresses the user's request")- merged_behaviors.append(SECURITY_BEHAVIOR)+ merged_behaviors = _restore_authored_behaviors(case, authored_behaviors, merged_behaviors)+ if merged_behaviors or not is_authored:+ merged_behaviors.extend([_FINAL_RESPONSE_BEHAVIOR, SECURITY_BEHAVIOR])case["expected_behavior"] = merged_behaviors# --- Refine ground_truth from agent's final message ---final_msg = _extract_agent_final_message(traj)if final_msg:truncated = final_msg[:400] if len(final_msg) > 400 else final_msg- case["ground_truth"] = truncated+ ground_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():+ _mark_case_for_review(case, "agent answer differs from authored ground truth")+ case["ground_truth"] = ground_truth+ else:+ case["ground_truth"] = truncated+ _mark_case_for_review(case, "expected outcome taken from an observed run; confirm it is correct")refined.append(case)@@ -1050,6 +1245,78 @@ def _write_dataset(output_path: Path, dataset: dict[str, Any]) -> None:temporary_path.unlink(missing_ok=True)+def _generation_input(kind: str, path: Path, skill_path: Path) -> dict[str, str] | None:+ if not path.is_file():+ return None+ try:+ relative_path = path.resolve().relative_to(skill_path.resolve()).as_posix()+ except ValueError:+ relative_path = path.name+ digest = hashlib.sha256(path.read_bytes()).hexdigest()+ return {"kind": kind, "path": relative_path, "sha256": digest}+++def _load_existing_cases(output_path: Path) -> list[dict[str, Any]]:+ try:+ cases = load_dataset_entries(output_path)+ except (OSError, ValueError, json.JSONDecodeError) as exc:+ _abort(f"Could not load existing dataset {output_path}: {exc}")+ if not cases:+ _abort(f"Existing dataset {output_path} has no cases to refine.")+ for index, case in enumerate(cases):+ if not isinstance(case.get("id"), str) or not case["id"]:+ _abort(f"Existing dataset case {index} must have a non-empty id to use --grounding trace.")+ return cases+++def _case_needs_review(case: dict[str, Any]) -> bool:+ review = case.get("review")+ return isinstance(review, dict) and review.get("status") == "needs_review"+++def _generation_record(+ skill_path: Path,+ *,+ mode: str,+ grounding: str,+ skill: dict[str, Any],+ prompt_path: Path | None,+ trajectory_paths: dict[str, Path],+ cases: list[dict[str, Any]],+) -> dict[str, Any]:+ inputs: list[dict[str, str]] = []+ candidates: list[tuple[str, Path]] = [("skill_md", skill_path / "SKILL.md")]+ source = skill.get("eval_prompt_source")+ if source:+ source_path = Path(str(source))+ is_prompt = prompt_path is not None and source_path.resolve() == prompt_path.resolve()+ candidates.append(("prompt" if is_prompt else "eval_md", source_path))+ candidates.extend(("trajectory", path) for path in trajectory_paths.values())+ seen: set[Path] = set()+ for kind, path in candidates:+ resolved = path.resolve()+ if resolved in seen:+ continue+ seen.add(resolved)+ record = _generation_input(kind, path, skill_path)+ if record is not None:+ inputs.append(record)+ review_state = "needs_review" if any(_case_needs_review(case) for case in cases) else "unreviewed"+ record = {+ "mode": mode,+ "grounding": grounding,+ "inputs": inputs,+ "generated_at": datetime.now(UTC).isoformat(),+ "review_state": review_state,+ "needs_review_count": sum(1 for case in cases if _case_needs_review(case)),+ }+ if skill.get("_generation_refined") is True:+ record["refined"] = True+ if mode == "template_fallback" and isinstance(skill.get("_generation_fallback_reason"), str):+ record["fallback_reason"] = skill["_generation_fallback_reason"]+ return record++def main(argv: Sequence[str] | None = None) -> DatasetGenerationResult:parser = argparse.ArgumentParser(description="Generate eval dataset for a skill.",@@ -1085,6 +1352,12 @@ 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.",+ )parser.add_argument("--dry-run", action="store_true", help="Preview without writing")parser.add_argument("--force", action="store_true", help="Overwrite existing dataset")parser.add_argument(@@ -1115,31 +1388,64 @@ Agent-refined mode (--refine):args = parser.parse_args(argv)skill_path = args.path.resolve()+ refine_requested = args.refine or args.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 args.refine:- _abort("--from-results requires --refine")- if args.results_dir and not args.refine:- _abort("--results-dir requires --refine")+ 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")evals_dir = skill_path / "evals"output_path = evals_dir / "evals.json"-- # --refine implies --force (refinement produces the final version)- if output_path.exists() and not args.force and not args.refine:+ trace_requested = args.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_mode = stat.S_IMODE(output_path.stat().st_mode) if original_dataset is not None else None++ def restore_original_dataset() -> None:+ if not trace_requested:+ return+ if original_dataset is None:+ output_path.unlink(missing_ok=True)+ return+ output_path.write_bytes(original_dataset)+ 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- skill = _parse_skill(skill_path, prompt_file=args.prompt)+ if skill is None:+ skill = _parse_skill(skill_path, prompt_file=args.prompt)+ skill["grounding"] = args.grounding+ skill["_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":+ 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":+ print(" Grounding: agent trace")+ else:+ print(" Grounding: SKILL.md")if args.full:if args.no_llm:mode_parts = ["full bucket set (template; negative when authored in EVAL.md)"]@@ -1147,56 +1453,108 @@ Agent-refined mode (--refine):mode_parts = ["full bucket set (4 cases via LLM)"]else:mode_parts = ["simple (1 test case)"]- if args.refine:+ if refine_requested:mode_parts.append("agent-refined")print(f" Mode: {', '.join(mode_parts)}")- # Step 1: Generate initial cases- if args.no_llm:+ authored_case_ids: set[str] = set()+ if trace_existing:+ cases = _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 args.no_llm:cases = _generate_full(skill) if args.full else _generate_simple(skill)else:cases = asyncio.run(_generate_with_llm(skill, full=args.full))- print(f"\nGenerated {len(cases)} initial test case(s):")+ print(f"\nPrepared {len(cases)} initial test case(s):")for case in cases:neg = " (negative)" if case.get("expected_skill") is None else ""print(f" [{case['id']}]{neg} {case['question'][:70]}")# Step 2: Refine with agent trajectory (if --refine)- if args.refine:+ trajectory_paths: dict[str, Path] = {}+ if refine_requested:print("\nRefining with agent trajectory...")- trajectories = _discover_trajectories(+ discovered = _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, {})+ collection_error = ""if not trajectories:print(" No existing trajectory found.")if args.dry_run:- print(" Dry run: not launching an agent or writing a staging dataset to collect trajectories.")+ collection_error = "--dry-run prevented collecting a trajectory"else:- trajectories = _run_agent_collect_trajectories(- skill_path,- cases,- results_dir=args.results_dir,- )+ try:+ collected = _run_agent_collect_trajectories(+ skill_path,+ cases,+ results_dir=args.results_dir,+ return_sources=True,+ strict=trace_requested,+ )+ except DatasetGenerationError as exc:+ collection_error = str(exc)+ if trace_requested:+ restore_original_dataset()+ _abort(f"--grounding trace collection failed: {collection_error}")+ else:+ trajectories, trajectory_paths = collected if isinstance(collected, tuple) else (collected, {})if trajectories:- matched = sum(1 for c in cases if c["id"] in trajectories)- print(f" Trajectory matched {matched}/{len(cases)} case(s)")+ matched_case_ids = {case["id"] for case in cases if case["id"] in trajectories}+ print(f" Trajectory matched {len(matched_case_ids)}/{len(cases)} case(s)")+ if trace_requested and not matched_case_ids:+ restore_original_dataset()+ _abort("--grounding trace found trajectories, but none matched the dataset's case ids.")+ trajectory_paths = {+ case_id: path for case_id, path in trajectory_paths.items() if case_id in matched_case_ids+ }if args.no_llm:- cases = _refine_from_trajectory_template(cases, trajectories, skill=skill)+ cases = _refine_from_trajectory_template(+ cases,+ trajectories,+ skill=skill,+ authored_case_ids=authored_case_ids,+ )print(" Applied template-based refinement from trajectory")else:- cases = asyncio.run(_refine_with_llm(skill, cases, trajectories))+ cases = asyncio.run(+ _refine_with_llm(+ skill,+ cases,+ trajectories,+ authored_case_ids=authored_case_ids,+ )+ )print(f" Refined {len(cases)} case(s) with LLM + trajectory")+ skill["_generation_refined"] = True+ elif trace_requested:+ restore_original_dataset()+ cause = collection_error or "collection completed without producing a trajectory"+ _abort(f"--grounding trace requires a trajectory, but {cause}.")else:print(" No trajectory available — using initial cases as-is.")- dataset = _to_agentskills_dataset(skill["name"], cases)+ generation = _generation_record(+ skill_path,+ mode=str(skill.get("_generation_mode", "template_requested")),+ grounding=args.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)+ needs_review = sum(1 for case in cases if _case_needs_review(case))+ print(f" {needs_review} case(s) flagged needs_review")if args.dry_run:print("\nDry run — not saved.")@@ -1213,7 +1571,7 @@ Agent-refined mode (--refine):print(f"\nSaved: {output_path}")print(f" {len(cases)} test case(s)")- if args.refine:+ if refine_requested: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")diff --git a/src/skillevaluator/tier3/harbor/runner.py b/src/skillevaluator/tier3/harbor/runner.pyindex e6528546..cc5ddd98 100644--- a/src/skillevaluator/tier3/harbor/runner.py+++ b/src/skillevaluator/tier3/harbor/runner.py@@ -774,6 +774,43 @@ def _persist_dataset_truth(run_dir: Path, *, fallback_task_ids: list[str]) -> direturn snapshot+def _dataset_generation_provenance(skill_path: Path) -> dict[str, Any] | None:+ source = find_evals_file(skill_path)+ if source is None or source.suffix.lower() not in {".json", ".yaml", ".yml"}:+ return None+ import yaml++ try:+ if source.suffix.lower() == ".json":+ document = json.loads(source.read_text(encoding="utf-8"))+ else:+ document = yaml.safe_load(source.read_text(encoding="utf-8"))+ except (OSError, UnicodeError, ValueError, yaml.YAMLError):+ return None+ if not isinstance(document, dict):+ return None+ from skillevaluator.tier3.dataset_provenance import sanitize_generation_record++ generation = document.get("generation")+ if isinstance(generation, dict):+ generation = dict(generation)+ eval_entries = document.get("evals")+ if isinstance(eval_entries, list):+ needs_review_count = sum(+ 1+ for entry in eval_entries+ if isinstance(entry, dict)+ and isinstance(entry.get("review"), dict)+ and entry["review"].get("status") == "needs_review"+ )+ generation["needs_review_count"] = needs_review_count+ if needs_review_count > 0:+ generation["review_state"] = "needs_review"+ elif generation.get("review_state") == "needs_review":+ generation["review_state"] = "unreviewed"+ return sanitize_generation_record(generation)++_NVIDIA_BUILD_FILE_SENTINEL = "skillevaluator-file-backed-nvidia-key"_NVIDIA_BUILD_KEY_FILE_ENV = "SKILLEVALUATOR_NVIDIA_API_KEY_FILE"_NVIDIA_BUILD_AGENT_DEFAULT_MODEL = CHAT_DEFAULT_NVIDIA@@ -5326,6 +5363,7 @@ def _run_harbor_eval_impl(if task_source not in {"evals_json", "native_harbor"}:reporter.emit(ProgressEvent(stage="with-skill-tasks", state="failed", detail="invalid task source"))return {"error": ["harbor.task_source must be auto, evals_json, or native_harbor"]}+ dataset_provenance = _dataset_generation_provenance(evaluator_skill_path) if task_source == "evals_json" else Nonereporter.emit(ProgressEvent(stage="credential-validation", state="running"))if runtime_errors:@@ -6244,6 +6282,7 @@ def _run_harbor_eval_impl("dataset_summary": dataset_truth["dataset_summary"],"dataset_digest": dataset_truth["dataset_digest"],"dataset_digest_algorithm": dataset_truth["dataset_digest_algorithm"],+ "dataset_provenance": dataset_provenance,"run_config": run_config,})diff --git a/src/skillevaluator/tier3/result_display.py b/src/skillevaluator/tier3/result_display.pyindex c7de3bb6..8f90fa60 100644--- a/src/skillevaluator/tier3/result_display.py+++ b/src/skillevaluator/tier3/result_display.py@@ -22,6 +22,7 @@ from rich.text import Textfrom skillevaluator.reporting.harbor_viewer import harbor_job_links, normalize_harbor_viewer_for_displayfrom skillevaluator.reporting.terminal_styles import AMBER, FAINT, GREEN, RED, TEXT, lift_style+from skillevaluator.tier3.dataset_provenance import dataset_provenance_displayfrom skillevaluator.tier3.harbor.metrics import (CUSTOM_ONLY_METRIC_SET,DEFAULT_METRIC_SET,@@ -869,6 +870,9 @@ def render_evaluation_result(duration = result.get("duration_seconds")if _finite_number(duration) is not None:console.print(f"Time: {float(duration):.1f}s")+ provenance_line, provenance_is_template = dataset_provenance_display(result.get("dataset_provenance"))+ if provenance_line:+ console.print(Text(provenance_line, style="yellow" if provenance_is_template else "dim"))agents = result.get("agents")incomplete = status in {"failed", "incomplete"} and not any(diff --git a/tests/golden/cli_surface.json b/tests/golden/cli_surface.jsonindex 8363ad36..0f3b3d99 100644--- a/tests/golden/cli_surface.json+++ b/tests/golden/cli_surface.json@@ -480,6 +480,19 @@"param_type": "option","type": "path"},+ {+ "choices": [+ "skill",+ "intent",+ "trace"+ ],+ "default": "skill",+ "name": "grounding",+ "opts": [+ "--grounding"+ ],+ "param_type": "option"+ },{"default": "False","is_flag": true,@@ -2647,6 +2660,19 @@"param_type": "option","type": "path"},+ {+ "choices": [+ "skill",+ "intent",+ "trace"+ ],+ "default": "skill",+ "name": "grounding",+ "opts": [+ "--grounding"+ ],+ "param_type": "option"+ },{"default": "False","is_flag": true,diff --git a/tests/reporting/test_dataset_generation_provenance.py b/tests/reporting/test_dataset_generation_provenance.pynew file mode 100644index 00000000..03c6349d--- /dev/null+++ b/tests/reporting/test_dataset_generation_provenance.py@@ -0,0 +1,243 @@+from __future__ import annotations++import json+from io import StringIO++import pytest+from rich.console import Console++from skillevaluator.evaluation.tier3_report import build_agent_eval_payload+from skillevaluator.models import ValidationResult+from skillevaluator.reporting.benchmark import BenchmarkReporter+from skillevaluator.reporting.cli import CLIReporter+from skillevaluator.reporting.html import HTMLReporter+from skillevaluator.reporting.markdown import MarkdownReporter+from skillevaluator.tier3.dataset_provenance import dataset_provenance_display, sanitize_generation_record+from skillevaluator.tier3.harbor.metrics import DEFAULT_METRICS+from skillevaluator.tier3.result_display import render_result+++def _generation(mode: str) -> dict:+ if mode == "llm":+ return {+ "mode": mode,+ "grounding": "skill",+ "review_state": "unreviewed",+ "needs_review_count": 2,+ }+ return {+ "mode": mode,+ "grounding": "skill",+ "review_state": "needs_review",+ "needs_review_count": 2,+ "fallback_reason": "public LLM provider is not configured",+ }+++def _result(generation: dict | None) -> ValidationResult:+ agent = {+ "execution_status": "succeeded",+ "execution_errors": [],+ "expected_attempts": 1,+ "scored_attempts": 1,+ "with_skill": dict.fromkeys(DEFAULT_METRICS, 0.8),+ "metrics_with_skill": list(DEFAULT_METRICS),+ "overall_with_skill": 0.8,+ "rewards": [+ {+ "entry_id": "case-1",+ "metric_set": "skill-evaluator-default-v2",+ **dict.fromkeys(DEFAULT_METRICS, 0.8),+ "overall": 0.8,+ }+ ],+ }+ payload = build_agent_eval_payload(+ "sample-skill",+ {"opencode": agent},+ dataset=[{"id": "case-1", "prompt": "Do the task", "expected_output": "A result"}],+ dataset_provenance=generation,+ use_llm_judge=False,+ )+ assert payload is not None+ result = ValidationResult(validator_name="AGENT_EVAL", validator_description="Live evaluation")+ result.metadata["agent_eval"] = payload+ return result+++def _render_validate_line(payload: dict) -> str:+ stream = StringIO()+ console = Console(file=stream, width=240, force_terminal=False, color_system=None)+ CLIReporter._print_agent_eval_tables(payload, console)+ return stream.getvalue()+++ ("mode", "expected"),+ [+ (+ "template_requested",+ "Dataset: generated from templates (requested) — cases are generic starters; review before relying on scores; 2 cases need review",+ ),+ (+ "template_fallback",+ "Dataset: generated from templates (fallback: public LLM provider is not configured) — cases are generic starters; review before relying on scores; 2 cases need review",+ ),+ ("llm", "Dataset: generated by skill grounding, review state unreviewed; 2 cases need review"),+ ],+)+def test_provenance_renders_on_evaluate_validate_html_and_benchmark(mode: str, expected: str) -> None:+ result = _result(_generation(mode))+ payload = result.metadata["agent_eval"]++ evaluate = render_result({"execution_status": "succeeded", "dataset_provenance": _generation(mode)})+ validate = _render_validate_line(payload)+ html = HTMLReporter(include_timestamp=False, report_scope="tier3").render_all([result])+ benchmark = BenchmarkReporter(+ include_timestamp=False,+ report_scope="tier3",+ skill_name="sample-skill",+ ).render(result)++ assert expected in evaluate+ assert expected in validate+ assert expected in html+ assert expected in benchmark+ if mode.startswith("template"):+ assert "t3-dataset-provenance warning" in html+++def test_missing_generation_record_renders_no_dataset_line() -> None:+ result = _result(None)+ payload = result.metadata["agent_eval"]++ evaluate = render_result({"execution_status": "succeeded"})+ validate = _render_validate_line(payload)+ html = HTMLReporter(include_timestamp=False, report_scope="tier3").render_all([result])+ benchmark = BenchmarkReporter(+ include_timestamp=False,+ report_scope="tier3",+ skill_name="sample-skill",+ ).render(result)++ assert "Dataset: generated" not in evaluate+ assert "Dataset: generated" not in validate+ assert "Dataset: generated" not in html+ assert "Dataset: generated" not in benchmark+++def test_report_payload_preserves_paths_and_shortens_input_hashes() -> None:+ generation = {+ "mode": "llm",+ "grounding": "intent",+ "review_state": "unreviewed",+ "inputs": [{"kind": "eval_md", "path": "evals/EVAL.md", "sha256": "a" * 64}],+ }++ provenance = _result(generation).metadata["agent_eval"]["dataset_provenance"]++ assert provenance["inputs"] == [{"kind": "eval_md", "path": "evals/EVAL.md", "sha256": "a" * 12}]++[email protected]("mode", [[], {}, None, 7])+def test_malformed_generation_mode_is_rejected(mode: object) -> None:+ assert sanitize_generation_record({"mode": mode}) is None+++def test_legacy_template_generation_record_keeps_mode_and_review_warning() -> None:+ record = sanitize_generation_record({"mode": "template", "needs_review_count": 2})++ assert record == {"mode": "template", "needs_review_count": 2}+ assert dataset_provenance_display(record) == (+ "Dataset: generated from templates — cases are generic starters; review before relying on scores; "+ "2 cases need review",+ True,+ )+++def test_fallback_reason_strips_terminal_escape_sequences() -> None:+ record = sanitize_generation_record(+ {+ "mode": "template_fallback",+ "fallback_reason": "\x1b[31mfailed\x1b[0m \x1b]8;;https://attacker.example\x1b\\click\x1b]8;;\x1b\\",+ }+ )++ assert record is not None+ assert record["fallback_reason"] == "failed click"+ assert "attacker.example" not in json.dumps(record)+++def test_html_provenance_uses_unbounded_tier3_record() -> None:+ generation = _generation("template_fallback")+ result = _result(generation)+ payload = result.metadata["agent_eval"]+ result.metadata["agent_eval"] = {"large_payload": "x" * 300_000, **payload}++ rendered = HTMLReporter(include_timestamp=False, report_scope="tier3").render_all([result])++ assert len(json.dumps(result.metadata["agent_eval"])) > 256 * 1024+ assert (+ "Dataset: generated from templates (fallback: public LLM provider is not configured) — "+ "cases are generic starters; review before relying on scores; 2 cases need review"+ ) in rendered+++def test_cli_print_all_includes_passing_result_provenance_once() -> None:+ result = _result(_generation("template_fallback"))+ stream = StringIO()+ reporter = CLIReporter(console=Console(file=stream, width=240, force_terminal=False, color_system=None))++ reporter.print_all([result])++ line = "Dataset: generated from templates (fallback: public LLM provider is not configured)"+ assert stream.getvalue().count(line) == 1+++def test_markdown_renders_escaped_provenance_under_tier3_verdict() -> None:+ generation = _generation("template_fallback")+ generation["fallback_reason"] = "**untrusted**"+ rendered = MarkdownReporter(include_timestamp=False).render_all([_result(generation)])++ verdict_index = rendered.index("**Verdict:**")+ provenance_index = rendered.index("Dataset:", verdict_index)+ assert provenance_index > verdict_index+ assert "**untrusted**" in rendered[provenance_index:]+ assert "**untrusted**" not in rendered[provenance_index:]+++ ("review_state", "review_entries", "expected_state", "expected_count"),+ [+ ("unreviewed", [{"review": {"status": "needs_review"}}], "needs_review", 1),+ ("needs_review", [], "unreviewed", 0),+ ("reviewed", [], "reviewed", 0),+ ],+)+def test_runner_provenance_review_state_uses_live_review_count(+ tmp_path,+ review_state: str,+ review_entries: list[dict],+ expected_state: str,+ expected_count: int,+) -> None:+ from skillevaluator.tier3.harbor.runner import _dataset_generation_provenance++ skill = tmp_path / "sample-skill"+ evals = skill / "evals"+ evals.mkdir(parents=True)+ (evals / "evals.json").write_text(+ json.dumps(+ {+ "generation": {"mode": "template_requested", "review_state": review_state},+ "evals": review_entries,+ }+ ),+ encoding="utf-8",+ )++ provenance = _dataset_generation_provenance(skill)++ assert provenance is not None+ assert provenance["review_state"] == expected_state+ assert provenance["needs_review_count"] == expected_countdiff --git a/tests/test_evaluation_service.py b/tests/test_evaluation_service.pyindex 17a4e61f..f67be86a 100644--- a/tests/test_evaluation_service.py+++ b/tests/test_evaluation_service.py@@ -79,7 +79,7 @@ def test_cli_formats_dataset_option_dependency_failure()assert result.exit_code == 1- assert result.output == f"Error: {dependent_option} requires --refine\n"+ assert result.output == f"Error: {dependent_option} requires --grounding trace or --refine\n"def test_options_fields_match_engine_signature() -> None:diff --git a/tests/test_tier3_progress.py b/tests/test_tier3_progress.pyindex 435bb794..e7d305e4 100644--- a/tests/test_tier3_progress.py+++ b/tests/test_tier3_progress.py@@ -1361,6 +1361,35 @@ def test_credential_validation_includes_distinct_standard_grading_route(}+def test_native_task_source_omits_evals_dataset_provenance(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ runner, skill = _stub_runner(monkeypatch, tmp_path)+ (skill / "evals" / "evals.json").write_text(+ json.dumps(+ {+ "skill_name": "demo-skill",+ "generation": {"mode": "template_requested", "review_state": "needs_review"},+ "evals": [{"id": "case-1", "prompt": "Q", "expected_output": "A"}],+ }+ ),+ encoding="utf-8",+ )+ _configure_native_task_source(monkeypatch, runner, skill)++ result = runner.run_harbor_eval(+ skill,+ ["codex"],+ output_dir=tmp_path / "results",+ agent_runtime_preflight=False,+ )++ assert "error" not in result+ assert result["run_config"]["task_source"] == "native_harbor"+ assert result["dataset_provenance"] is None++def test_missing_native_task_source_stops_before_credential_probes(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,diff --git a/tests/tier3/test_dataset_generation_progress.py b/tests/tier3/test_dataset_generation_progress.pyindex f8cd030e..ba13154c 100644--- a/tests/tier3/test_dataset_generation_progress.py+++ b/tests/tier3/test_dataset_generation_progress.py@@ -133,7 +133,7 @@ def test_interrupted_autopilot_does_not_fallback_or_write_dataset(generation_skicalls = []- def interrupt(_self, _path, *, use_llm):+ def interrupt(_self, _path, *, use_llm, **_kwargs):calls.append(use_llm)raise KeyboardInterrupt@@ -188,7 +188,12 @@ def test_fallback_explains_safe_failure_and_labels_starter(generation_skill, monassert "private-response-content" not in result.output + notes[0]assert "private-endpoint" not in result.output + notes[0]assert "Tier 2" not in result.output + notes[0]- assert len(json.loads((generation_skill / "evals" / "evals.json").read_text())["evals"]) == 1+ dataset = json.loads((generation_skill / "evals" / "evals.json").read_text())+ assert len(dataset["evals"]) == 1+ assert dataset["generation"]["mode"] == "template_fallback"+ assert expected in dataset["generation"]["fallback_reason"]+ assert "private-response-content" not in dataset["generation"]["fallback_reason"]+ assert "private-endpoint" not in dataset["generation"]["fallback_reason"]def test_quiet_fallback_preserves_reason_in_returned_note(generation_skill, monkeypatch):diff --git a/tests/tier3/test_dataset_grounding.py b/tests/tier3/test_dataset_grounding.pynew file mode 100644index 00000000..2022deec--- /dev/null+++ b/tests/tier3/test_dataset_grounding.py@@ -0,0 +1,683 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++import asyncio+import hashlib+import json+from pathlib import Path+from types import SimpleNamespace++import pytest++from skillevaluator.evaluation import DatasetGenerationError+from skillevaluator.inference import client as inference_client+from skillevaluator.tier3 import generate_dataset+from skillevaluator.tier3.evals_spec import validate_tier3_source+++def _skill_dir(tmp_path: Path, *, guidance: str | None = None) -> Path:+ skill = tmp_path / "sample-skill"+ skill.mkdir()+ (skill / "SKILL.md").write_text(+ "---\nname: sample-skill\ndescription: Does useful work\n---\n# Skill\n",+ encoding="utf-8",+ )+ if guidance is not None:+ evals = skill / "evals"+ evals.mkdir()+ (evals / "EVAL.md").write_text(guidance, encoding="utf-8")+ return skill+++def _write_trace_results(+ skill: Path,+ results_root: Path,+ case_id: str,+ trajectory: dict,+) -> Path:+ run_id = "20260224_120000"+ run_dir = results_root / skill.name / run_id+ trial = run_dir / "claude-code" / "with-skill" / "trials" / case_id+ trial.mkdir(parents=True)+ trajectory_path = trial / "trajectory.json"+ trajectory_path.write_text(json.dumps(trajectory), encoding="utf-8")+ (run_dir / "run_config.json").write_text("{}", encoding="utf-8")+ (run_dir / "result.json").write_text(json.dumps({"run_id": run_id}), encoding="utf-8")+ latest = results_root / skill.name / "latest"+ if not latest.exists():+ latest.symlink_to(run_id)+ return trajectory_path+++def _invoice_trajectory() -> dict:+ return {+ "steps": [+ {+ "source": "agent",+ "tool_calls": [+ {+ "function_name": "read_file",+ "arguments": {"path": "/workspace/skills/sample-skill/SKILL.md"},+ }+ ],+ },+ {+ "source": "agent",+ "tool_calls": [+ {+ "function_name": "bash",+ "arguments": {"command": "python reconcile.py inv.csv"},+ }+ ],+ },+ {+ "source": "agent",+ "message": "Reconciled 42 invoices; three mismatches were written to mismatches.csv.",+ },+ ]+ }+++def test_intent_grounding_requires_author_guidance(tmp_path):+ skill = _skill_dir(tmp_path)++ with pytest.raises(DatasetGenerationError, match="requires author guidance"):+ generate_dataset.main([str(skill), "--no-llm", "--grounding", "intent"])+++def test_intent_records_eval_provenance_and_template_mode(tmp_path, capsys):+ guidance = "## Questions\n- Reconcile the invoice using the documented workflow.\n"+ skill = _skill_dir(tmp_path, guidance=guidance)++ result = generate_dataset.main([str(skill), "--no-llm", "--grounding", "intent"])++ generation = result.dataset["generation"]+ eval_input = next(record for record in generation["inputs"] if record["kind"] == "eval_md")+ assert eval_input == {+ "kind": "eval_md",+ "path": "evals/EVAL.md",+ "sha256": hashlib.sha256(guidance.encode()).hexdigest(),+ }+ assert generation["mode"] == "template_requested"+ assert generation["grounding"] == "intent"+ assert "Grounding: author intent from evals/EVAL.md" in capsys.readouterr().out+++def test_intent_case_002_keeps_all_authored_behaviors():+ cases = generate_dataset._generate_full(+ {+ "name": "sample-skill",+ "description": "Does useful work",+ "scripts": ["reconcile.py"],+ "grounding": "intent",+ "eval_prompt": (+ "## Behaviors\n"+ "- The agent validates the invoice total against the ledger\n"+ "- The agent reports each mismatched row\n"+ ),+ }+ )++ 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"]++[email protected]("existing_dataset", [False, True], ids=["generated-cases", "authored-cases"])+def test_main_trace_refines_real_trajectory_without_losing_authored_content(+ tmp_path,+ monkeypatch,+ existing_dataset,+):+ skill = _skill_dir(tmp_path)+ trajectory_path = _write_trace_results(+ skill,+ tmp_path / "results",+ "sample-skill-001",+ _invoice_trajectory(),+ )+ monkeypatch.setenv("SKILLEVALUATOR_RESULTS_DIR", str(tmp_path / "results"))++ if existing_dataset:+ evals_dir = skill / "evals"+ evals_dir.mkdir()+ _write_trace_results(+ skill,+ tmp_path / "results",+ "unmatched-case",+ {"steps": [{"source": "agent", "message": "This trajectory belongs to another case."}]},+ )+ (evals_dir / "evals.json").write_text(+ json.dumps(+ {+ "skill_name": "sample-skill",+ "evals": [+ {+ "id": "sample-skill-001",+ "prompt": "AUTHORED: reconcile these invoices",+ "expected_output": "AUTHORED: the ledger was reconciled",+ "assertions": ["AUTHORED: validate each ledger row"],+ "expected_skill": "sample-skill",+ }+ ],+ }+ ),+ encoding="utf-8",+ )++ result = generate_dataset.main([str(skill), "--no-llm", "--dry-run", "--grounding", "trace"])++ case = result.dataset["evals"][0]+ if existing_dataset:+ assert case["prompt"] == "AUTHORED: reconcile these invoices"+ assert case["expected_output"] == "AUTHORED: the ledger was reconciled"+ assert "AUTHORED: validate each ledger row" in case["assertions"]+ assert "agent answer differs from authored ground truth" in case["review"]["reasons"]+ else:+ assert case["expected_output"] == "Reconciled 42 invoices; three mismatches were written to mismatches.csv."+ 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"]+ 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+ assert trajectory_inputs[0]["sha256"] == hashlib.sha256(trajectory_path.read_bytes()).hexdigest()+++def test_trace_aborts_when_no_trajectory_id_matches_existing_cases(tmp_path, monkeypatch):+ skill = _skill_dir(tmp_path)+ evals_dir = skill / "evals"+ evals_dir.mkdir()+ output_path = evals_dir / "evals.json"+ original = json.dumps(+ {+ "skill_name": "sample-skill",+ "evals": [{"id": "authored-case", "prompt": "Do it", "expected_output": "Keep this"}],+ }+ ).encode()+ output_path.write_bytes(original)+ _write_trace_results(skill, tmp_path / "results", "unmatched-case", _invoice_trajectory())+ monkeypatch.setenv("SKILLEVALUATOR_RESULTS_DIR", str(tmp_path / "results"))++ with pytest.raises(DatasetGenerationError, match="--grounding trace found trajectories, but none matched"):+ generate_dataset.main([str(skill), "--no-llm", "--dry-run", "--grounding", "trace"])++ assert output_path.read_bytes() == original+++def test_trace_restores_authored_dataset_when_collection_fails(tmp_path, monkeypatch):+ skill = _skill_dir(tmp_path)+ evals_dir = skill / "evals"+ evals_dir.mkdir()+ output_path = evals_dir / "evals.json"+ original = json.dumps(+ {+ "skill_name": "sample-skill",+ "evals": [{"id": "authored-case", "prompt": "Do it", "expected_output": "Keep this"}],+ }+ ).encode()+ output_path.write_bytes(original)+ monkeypatch.setattr(generate_dataset, "_discover_trajectories", lambda *_args, **_kwargs: ({}, {}))++ def failed_collection(*_args, **_kwargs):+ output_path.write_text("temporary replacement", encoding="utf-8")+ raise DatasetGenerationError("Docker daemon is not running")++ monkeypatch.setattr(generate_dataset, "_run_agent_collect_trajectories", failed_collection)++ with pytest.raises(DatasetGenerationError, match="--grounding trace collection failed: Docker daemon"):+ generate_dataset.main([str(skill), "--no-llm", "--grounding", "trace"])++ assert output_path.read_bytes() == original+++def test_main_uses_collected_trajectory_sources_for_generation_inputs(tmp_path, monkeypatch):+ skill = _skill_dir(tmp_path)+ trajectory = _invoice_trajectory()+ trajectory_path = tmp_path / "collected-trajectory.json"+ trajectory_path.write_text(json.dumps(trajectory), encoding="utf-8")+ discoveries = iter([({}, {}), ({"sample-skill-001": trajectory}, {"sample-skill-001": trajectory_path})])+ monkeypatch.setattr(generate_dataset, "_discover_trajectories", lambda *_args, **_kwargs: next(discoveries))++ def collect(*_args, **kwargs):+ assert kwargs["return_sources"] is True+ return {"sample-skill-001": trajectory}, {"sample-skill-001": trajectory_path}++ monkeypatch.setattr(generate_dataset, "_run_agent_collect_trajectories", collect)++ result = generate_dataset.main([str(skill), "--no-llm", "--grounding", "trace"])++ trajectory_inputs = [entry for entry in result.dataset["generation"]["inputs"] if entry["kind"] == "trajectory"]+ assert len(trajectory_inputs) == 1+ assert trajectory_inputs[0]["sha256"] == hashlib.sha256(trajectory_path.read_bytes()).hexdigest()+++def test_main_llm_trace_uses_observed_answer_for_generated_cases(tmp_path, monkeypatch):+ skill = _skill_dir(tmp_path)+ _write_trace_results(+ skill,+ tmp_path / "results",+ "sample-skill-001",+ _invoice_trajectory(),+ )+ monkeypatch.setenv("SKILLEVALUATOR_RESULTS_DIR", str(tmp_path / "results"))++ async def generate_cases(skill, **_kwargs):+ return generate_dataset._generate_simple(skill)++ monkeypatch.setattr(generate_dataset, "_generate_with_llm", generate_cases)++ class FakeLLMClient:+ def __init__(self, **_kwargs):+ pass++ def completions(self, *_args):+ return json.dumps(+ [+ {+ "id": "sample-skill-001",+ "question": "Use sample-skill.",+ "ground_truth": "Generated placeholder answer",+ "expected_behavior": [],+ "expected_skill": "sample-skill",+ }+ ]+ )++ 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), "--dry-run", "--grounding", "trace"])++ case = result.dataset["evals"][0]+ assert case["expected_output"] == "Reconciled 42 invoices; three mismatches were written to mismatches.csv."+ assert "expected outcome taken from an observed run; confirm it is correct" in case["review"]["reasons"]+ assert "The agent used generated expectations" not in case["assertions"]+++def test_trace_preserves_authored_ground_truth_and_flags_mismatches():+ cases = [+ {+ "id": "case-1",+ "question": "Do the task",+ "ground_truth": "Authored expected answer",+ "expected_behavior": ["The agent uses the approved workflow"],+ "expected_skill": "sample-skill",+ }+ ]+ trajectories = {+ "case-1": {+ "steps": [+ {"source": "agent", "message": "Observed different answer from the run."},+ ]+ }+ }++ refined = generate_dataset._refine_from_trajectory_template(cases, trajectories)+ review = refined[0]["review"]++ assert refined[0]["ground_truth"] == "Authored expected answer"+ assert review["status"] == "needs_review"+ assert "agent answer differs from authored ground truth" in review["reasons"]+ assert "The agent uses the approved workflow" in refined[0]["expected_behavior"]+ assert not any(reason.startswith("refinement dropped authored step:") for reason in review["reasons"])+++def test_llm_refinement_restores_and_flags_dropped_authored_behavior(monkeypatch):+ class FakeLLMClient:+ def __init__(self, **_kwargs):+ pass++ def completions(self, *_args):+ return json.dumps(+ [+ {+ "id": "case-1",+ "question": "Do the task",+ "ground_truth": "Authored expected answer",+ "expected_behavior": ["The agent uses a refined workflow"],+ "expected_skill": "sample-skill",+ }+ ]+ )++ monkeypatch.setattr(+ "skillevaluator.provider_config.resolve_llm_provider",+ lambda: SimpleNamespace(+ provider="test",+ model="test",+ ),+ )+ monkeypatch.setattr(inference_client, "LLMClient", FakeLLMClient)+ cases = [+ {+ "id": "case-1",+ "question": "Do the task",+ "ground_truth": "Authored expected answer",+ "expected_behavior": ["The agent uses the approved workflow"],+ "expected_skill": "sample-skill",+ }+ ]++ refined = asyncio.run(+ generate_dataset._refine_with_llm(+ {"name": "sample-skill"},+ cases,+ {"case-1": {"steps": []}},+ )+ )++ assert refined[0]["expected_behavior"][:2] == [+ "The agent uses the approved workflow",+ "The agent uses a refined workflow",+ ]+ assert refined[0]["review"]["reasons"] == ["refinement dropped authored step: The agent uses the approved workflow"]+++def test_trace_proposes_unauthored_observed_answer_and_flags_review():+ cases = [{"id": "case-1", "question": "Do the task", "expected_behavior": [], "expected_skill": "sample-skill"}]+ trajectories = {+ "case-1": {"steps": [{"source": "agent", "message": "Observed answer that is longer than twenty characters."}]}+ }++ refined = generate_dataset._refine_from_trajectory_template(cases, trajectories)++ assert refined[0]["ground_truth"] == "Observed answer that is longer than twenty characters."+ assert refined[0]["review"]["status"] == "needs_review"+ assert "expected outcome taken from an observed run; confirm it is correct" in refined[0]["review"]["reasons"]+++def test_template_refinement_deduplicates_standard_behaviors_and_keeps_trajectory_actions():+ case = {+ "id": "case-1",+ "question": "Do the task",+ "ground_truth": "Authored answer",+ "expected_skill": "sample-skill",+ "expected_behavior": [+ "The agent uses the approved workflow",+ generate_dataset._FINAL_RESPONSE_BEHAVIOR,+ generate_dataset.SECURITY_BEHAVIOR,+ generate_dataset._FINAL_RESPONSE_BEHAVIOR,+ generate_dataset.SECURITY_BEHAVIOR,+ ],+ }+ trajectory = {+ "steps": [+ {+ "tool_calls": [+ {"function_name": "read_file", "arguments": {"path": "/tmp/SKILL.md"}},+ {"function_name": "bash", "arguments": {"command": "python reconcile.py inv.csv"}},+ ]+ }+ ]+ }++ refined = generate_dataset._refine_from_trajectory_template([case], {"case-1": trajectory})[0]++ behaviors = refined["expected_behavior"]+ assert behaviors[:3] == [+ "The agent uses the approved workflow",+ "The agent read SKILL.md before taking action",+ "The agent executed: python reconcile.py inv.csv",+ ]+ assert behaviors.count(generate_dataset._FINAL_RESPONSE_BEHAVIOR) == 1+ assert behaviors.count(generate_dataset.SECURITY_BEHAVIOR) == 1+ assert behaviors[-2:] == [generate_dataset._FINAL_RESPONSE_BEHAVIOR, generate_dataset.SECURITY_BEHAVIOR]+++def test_authored_restore_does_not_treat_generic_standard_lines_as_authored():+ case = {}++ restored = generate_dataset._restore_authored_behaviors(+ case,+ [generate_dataset._FINAL_RESPONSE_BEHAVIOR, generate_dataset.SECURITY_BEHAVIOR],+ [],+ )++ assert restored == []+ assert "review" not in case+++def test_llm_refinement_falls_back_and_flags_missing_case_ids(monkeypatch):+ prompts = []++ class FakeLLMClient:+ def __init__(self, **_kwargs):+ pass++ def completions(self, *_args):+ prompts.append(_args[-1])+ return json.dumps(+ [+ {+ "id": "case-1",+ "ground_truth": "Different answer",+ "expected_behavior": ["The agent uses a refined workflow"],+ },+ {+ "id": "case-2-renamed",+ "ground_truth": "Observed answer",+ "expected_behavior": [],+ },+ {+ "id": "case-3",+ "ground_truth": "Unobserved model answer",+ "expected_behavior": ["The agent records a result"],+ },+ ]+ )++ monkeypatch.setattr(+ "skillevaluator.provider_config.resolve_llm_provider",+ lambda: SimpleNamespace(provider="test", model="test"),+ )+ monkeypatch.setattr(inference_client, "LLMClient", FakeLLMClient)+ cases = [+ {+ "id": "case-1",+ "question": "Do the task",+ "ground_truth": "Authored answer",+ "expected_behavior": ["The agent uses the approved workflow"],+ "expected_skill": "sample-skill",+ },+ {+ "id": "case-2",+ "question": "Do the other task",+ "ground_truth": "Authored second answer",+ "expected_behavior": ["The agent reports every mismatch"],+ "expected_skill": "sample-skill",+ },+ {+ "id": "case-3",+ "question": "Do one more task",+ "ground_truth": "Authored third answer",+ "expected_behavior": ["The agent records the result"],+ "expected_skill": "sample-skill",+ },+ ]+ trajectories = {+ case_id: {+ "steps": [{"source": "agent", "message": f"Observed answer for {case_id} with enough detail to be used."}]+ }+ for case_id in ("case-1", "case-2")+ }++ refined = asyncio.run(+ generate_dataset._refine_with_llm(+ {"name": "sample-skill"},+ cases,+ trajectories,+ authored_case_ids={"case-1", "case-2", "case-3"},+ )+ )++ assert [case["id"] for case in refined] == ["case-1", "case-2", "case-3"]+ assert refined[0]["ground_truth"] == "Authored answer"+ assert refined[0]["review"]["reasons"] == [+ "refinement dropped authored step: The agent uses the approved workflow",+ "agent answer differs from authored ground truth",+ ]+ assert "refinement output did not return this case" in refined[1]["review"]["reasons"]+ assert refined[1]["ground_truth"] == "Authored second answer"+ assert refined[2]["ground_truth"] == "Authored third answer"+ assert "agent answer differs from authored ground truth" not in refined[2].get("review", {}).get("reasons", [])+ assert generate_dataset.SECURITY_BEHAVIOR in prompts[0]+++def test_default_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"])++ assert result.dataset["generation"]["grounding"] == "skill"+ assert result.dataset["generation"]["mode"] == "template_requested"+ assert result.dataset["evals"] == generate_dataset._to_agentskills_dataset("sample-skill", expected_cases)["evals"]+++def test_trace_grounding_fails_when_dry_run_has_no_trajectory(tmp_path, monkeypatch):+ skill = _skill_dir(tmp_path)+ monkeypatch.setattr(generate_dataset, "_discover_trajectories", lambda *_args, **_kwargs: ({}, {}))++ with pytest.raises(DatasetGenerationError, match="--grounding trace requires a trajectory"):+ generate_dataset.main([str(skill), "--no-llm", "--dry-run", "--grounding", "trace"])+++def test_validator_accepts_generation_and_case_review_metadata(tmp_path):+ skill = _skill_dir(tmp_path)+ evals = skill / "evals"+ evals.mkdir()+ (evals / "evals.json").write_text(+ json.dumps(+ {+ "skill_name": "sample-skill",+ "generation": {+ "mode": "template_requested",+ "grounding": "intent",+ "inputs": [{"kind": "skill_md", "path": "SKILL.md", "sha256": "0" * 64}],+ "generated_at": "2026-01-01T00:00:00+00:00",+ "review_state": "needs_review",+ },+ "evals": [+ {+ "id": "case-1",+ "prompt": "Do the task",+ "expected_output": "A result",+ "assertions": ["Use the approved workflow"],+ "review": {"status": "needs_review", "reasons": ["Check this case"]},+ }+ ],+ }+ ),+ encoding="utf-8",+ )++ source, checks = validate_tier3_source(skill)++ assert source == "evals_json"+ assert not [check for check in checks if check.status == "error"]+++def test_llm_generation_records_mode_and_trace_refinement_flag(tmp_path, monkeypatch):+ skill = _skill_dir(tmp_path)+ case = {+ "id": "case-1",+ "question": "Do the task",+ "expected_skill": "sample-skill",+ "expected_script": None,+ "ground_truth": "A useful result",+ "expected_behavior": ["The agent completes the task"],+ }++ async def generated(*_args, **_kwargs):+ return [case]++ monkeypatch.setattr(generate_dataset, "_generate_with_llm", generated)+ llm_result = generate_dataset.generate_one_case(skill, use_llm=True)+ llm_record = json.loads(llm_result.read_text())["generation"]+ assert llm_record["mode"] == "llm"+ assert llm_record["grounding"] == "skill"+ assert "refined" not in llm_record+++def test_template_fallback_records_safe_reason(tmp_path, monkeypatch):+ from skillevaluator.provider_config import ProviderConfigurationError++ skill = _skill_dir(tmp_path)++ def provider_unavailable():+ 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"])++ record = result.dataset["generation"]+ assert record["mode"] == "template_fallback"+ assert record["fallback_reason"] == "public LLM provider is not configured"+ assert "credential-value-that-must-not-leak" not in json.dumps(record)+++def test_trace_refinement_keeps_template_mode_and_records_refined(tmp_path, monkeypatch):+ skill = _skill_dir(tmp_path)+ case = {+ "id": "case-1",+ "question": "Do the task",+ "expected_skill": "sample-skill",+ "ground_truth": "A useful result",+ "expected_behavior": ["The agent completes the task"],+ }+ monkeypatch.setattr(generate_dataset, "_generate_simple", lambda _skill: [case])+ monkeypatch.setattr(+ generate_dataset,+ "_discover_trajectories",+ lambda *_args, **_kwargs: ({"case-1": {"steps": []}}, {}),+ )++ result = generate_dataset.main([str(skill), "--no-llm", "--grounding", "trace", "--dry-run"])++ record = result.dataset["generation"]+ assert record["mode"] == "template_requested"+ assert record["grounding"] == "trace"+ assert record["refined"] is True+++def test_autopilot_records_llm_and_template_fallback(tmp_path, monkeypatch):+ async def generated(*_args, **_kwargs):+ return [+ {+ "id": "case-1",+ "question": "Do the task",+ "expected_skill": "sample-skill",+ "expected_script": None,+ "ground_truth": "A useful result",+ "expected_behavior": ["The agent completes the task"],+ }+ ]++ monkeypatch.setattr(generate_dataset, "_generate_with_llm", generated)+ llm_skill = _skill_dir(tmp_path)+ llm_record = json.loads(generate_dataset.generate_one_case(llm_skill, use_llm=True).read_text())["generation"]+ assert llm_record["mode"] == "llm"+ assert llm_record["grounding"] == "skill"++ fallback_root = tmp_path / "fallback"+ fallback_root.mkdir()+ fallback_skill = _skill_dir(fallback_root)+ fallback_record = json.loads(+ generate_dataset.generate_one_case(+ fallback_skill,+ use_llm=False,+ fallback_reason="public LLM provider is not configured",+ ).read_text()+ )["generation"]+ assert fallback_record["mode"] == "template_fallback"+ assert fallback_record["grounding"] == "skill"+ assert fallback_record["fallback_reason"] == "public LLM provider is not configured"diff --git a/tests/tier3/test_generate_dataset_results.py b/tests/tier3/test_generate_dataset_results.pyindex 8cec358a..11188d4e 100644--- a/tests/tier3/test_generate_dataset_results.py+++ b/tests/tier3/test_generate_dataset_results.py@@ -300,26 +300,35 @@ def test_to_agentskills_dataset_preserves_aces_metadata():assert dataset["evals"][0]["expected_script"] == "main.py"-def test_dry_run_refine_does_not_write_dataset_when_no_trajectory(tmp_path, monkeypatch):+def test_dry_run_plain_refine_uses_generated_cases_without_a_trajectory(tmp_path):skill = tmp_path / "my-skill"skill.mkdir()(skill / "SKILL.md").write_text("---\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), "--no-llm", "--dry-run", "--refine"])- assert not (skill / "evals" / "evals.json").exists()assert result.status == "preview"assert result.cases_count == 1- assert result.dataset is not None+ assert not (skill / "evals" / "evals.json").exists()+++def test_plain_refine_keeps_generated_cases_when_collection_is_unavailable(tmp_path, monkeypatch):+ skill = tmp_path / "my-skill"+ skill.mkdir()+ (skill / "SKILL.md").write_text(+ "---\nname: my-skill\ndescription: Does useful work\n---\n",+ encoding="utf-8",+ )+ 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.status == "created"+ assert result.cases_count == 1+ assert result.dataset["evals"][0]["expected_output"].startswith("The agent used the my-skill skill")def test_main_invalid_skill_raises_domain_error_without_printing(tmp_path, capsys):@@ -435,10 +444,10 @@ def test_command_uses_explicit_argv_without_mutating_process_state(tmp_path, monoriginal_argv = sys.argv[:]monkeypatch.setattr(generate_dataset, "main", lambda argv=None: observed.append(list(argv or ())) or sentinel)- result = commands.create_dataset(tmp_path, no_llm=True, dry_run=True)+ result = commands.create_dataset(tmp_path, no_llm=True, dry_run=True, grounding="intent")assert result is sentinel- assert observed == [[str(tmp_path.resolve()), "--no-llm", "--dry-run"]]+ assert observed == [[str(tmp_path.resolve()), "--no-llm", "--dry-run", "--grounding", "intent"]]assert sys.argv == original_argv@@ -466,6 +475,35 @@ def test_concurrent_programmatic_generation_has_no_cross_talk(tmp_path):assert [result.dataset["skill_name"] for result in results] == ["alpha-skill", "beta-skill"]+def test_agent_collect_returns_discovered_trajectory_sources(tmp_path, monkeypatch):+ skill = tmp_path / "my-skill"+ skill.mkdir()+ cases = [{"id": "case-001", "question": "Use my-skill.", "expected_skill": "my-skill"}]+ trajectory = {"steps": [{"source": "agent", "message": "A sufficiently detailed observed response."}]}+ source_path = tmp_path / "trajectory.json"+ source_path.write_text(json.dumps(trajectory), encoding="utf-8")+ discovered = ({"case-001": trajectory}, {"case-001": source_path})++ monkeypatch.setattr("skillevaluator.utils.tool_runner.resolve_tool_path", lambda *_args: "/usr/bin/harbor")+ monkeypatch.setattr("shutil.which", lambda name: "/usr/bin/docker" if name == "docker" else None)+ monkeypatch.setattr(+ "skillevaluator.provider_config.resolve_llm_provider",+ lambda: SimpleNamespace(provider="test", model="test"),+ )+ monkeypatch.setattr(+ "skillevaluator.tier3.harbor.runner.run_harbor_eval",+ lambda **_kwargs: {"agents": {}},+ )+ monkeypatch.setattr(+ "skillevaluator.tier3.generate_dataset._discover_trajectories",+ lambda *_args, **_kwargs: discovered,+ )++ result = _run_agent_collect_trajectories(skill, cases, return_sources=True)++ assert result == discovered++def test_agent_collect_stages_agentskills_dataset(tmp_path, monkeypatch):skill = tmp_path / "my-skill"skill.mkdir()