Multi-tier framework for evaluating AI agent skills and plugins with quality gates, security scanning, harness compatibility checks, semantic overlap detection, synthetic evaluation dataset generation, and live agent evaluation that measures how skills affect agent behavior. Ships reusable CI templates that bring every check to any repository.
Python agent-evaluationagent-pluginsagent-securityagent-skillsagentic-aibenchmarkci-templatesclaude-codecodexevaluateevaluationharnesspluginplugin-evaluationsecurity-scannerskill-evalskill-evaluationskill-evaluatorskill-gap-analysisskills
fix(reporting): require complete tier evidence for publication (#77)
Narendran Raghavan75ce3f03041c
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex d05a0634..ce8abbc1 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -68,7 +68,7 @@ jobs:run: python scripts/check_oss_boundary.py --root . --allowlist config/oss_boundary_allowlist.json- name: Lint committed BENCHMARK.md fixtures for leak patternsif: ${{ needs.classify-changes.outputs.docs_only != 'true' }}- run: uv run python scripts/ci/check_public_benchmarks.py --require-files tests/golden+ run: uv run python scripts/ci/check_public_benchmarks.py --require-files tests/golden --require-source-provenance- name: Lintif: ${{ needs.classify-changes.outputs.docs_only != 'true' }}run: uv run ruff check .diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 38146912..76cd4b5b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -90,6 +90,25 @@ All notable changes to SkillEvaluator are documented in this file.- Exposed `kata` as the 24th Harbor 0.24 backend alongside local mode.`cua-cloud`, `opensandbox`, `hf-sandbox`, `podman`, `runta`, `prime`,`mosaic`, and `smol` remain disabled.+- The public benchmark gate (`scripts/ci/check_public_benchmarks.py`) now+ requires a `PASS` card to record its `Source digest` and `Tier 3 run ID`.+ `PASS` cards rendered by earlier releases fail the scan until they are+ regenerated; earlier `FAIL`, `NEUTRAL`, and `INCOMPLETE` cards without those+ lines are still accepted, and the lines are validated whenever present.+- Report output must be outside the publication target. An explicit+ `--output-dir` inside the evaluated skill is now rejected; use an external+ directory. A default in-target `reports/` location relocates to an+ authenticated sibling `<skill>-reports` (or `<catalog>-reports`), refuses+ unowned collisions, and is excluded from Tier 3 runtime staging. Report roots+ inside the target repository or an included-skill root are excluded from+ linked or full-repository context only after they are reserved or+ authenticated as generated output, so an authored subtree is never silently+ omitted.+- A custom Tier 3 `--results-dir` inside the evaluated skill is now rejected;+ use the canonical `evals/results` path or an external results root.+- `validate --block-on-agent-eval` now passes the exit gate only for a completed+ Tier 3 `PASS` verdict with complete attempt coverage. `NEUTRAL` and `FAIL`+ verdicts exit 1; previously any completed, scored run passed.### Fixed@@ -144,6 +163,41 @@ All notable changes to SkillEvaluator are documented in this file.budget and judge time-budget variables, and the Harbor process environment.The CLI reference adds `validate --workers`, the full `--env-mode` list, andthe exit codes the CLI actually returns (`0`, `1`, `2`).+- `BENCHMARK.md` publication verdicts now require completed Tier 1 and Tier 2+ execution evidence by default (Tier 1 must cover every default check that+ applies to the content type, so a run narrowed with `--checks` cannot+ certify publication), conservatively resolve conflicting peer+ policy and Tier 3 result metadata, bind every tier and policy claim to one+ versioned source-tree digest, preserve the Tier 3 run ID, persist an explicit+ publication status in JSON and HTML, and reject+ publication `PASS` cards whose decision evidence is missing, incomplete,+ linked, or hidden in raw HTML. Tier 3 evidence now cross-checks complete+ per-condition attempt and error records, and the public-card gate rejects+ ambiguous structural headings, browser-rendered decision-text aliases, and+ literal or entity-encoded Unicode control/format characters. The source+ identity is read without following links before and after each producer,+ follows the host filesystem's case aliases, and records a bounded+ source-change marker. Tier 3 runs that stage repository context, external+ reference or workspace skills, or task inputs with `.git`, `.venv`,+ `__pycache__`, or `node_modules` entries remain runnable but cannot certify+ publication, and neither can a target whose authored paths below the root+ use names that Tier 1 skips (such as `references/results/`).+- Clean and not-applicable License, Code Risk, Secrets, and Dependency Audit+ runs now record structured execution evidence, so legitimate built-in Tier 1+ results can satisfy publication without relying on findings or errors.+- Skip reasons are bounded, control-free, and escaped in reports and in the+ terminal, so oversized metadata, Rich markup, or terminal escape sequences+ cannot corrupt them. Reports show one line; the pipeline view keeps the+ reason's line breaks.+- SkillSpector issue paths with NUL bytes or lone surrogates now make the+ security scan incomplete instead of being accepted.+- The public benchmark gate rejects `PASS` cards with placeholder identities,+ malformed or future evaluation dates, a missing Tier 3 run ID, hostile+ benchmark-policy metadata, or environment-label substitutions in required+ proof fields.+- Hardened Tier 3 HTML and Markdown reporting against recursive or malformed+ display metadata, Markdown structure injection, and inline-JavaScript+ injection through untrusted agent or skill names.## 0.5.0 - 2026-10-06@@ -622,28 +676,11 @@ All notable changes to SkillEvaluator are documented in this file.conversion limit, preserves nonzero Wilson interval widths and paired-effectdirections at large case counts, and documents exact-rational omissionmarkers.-- `BENCHMARK.md` publication verdicts now require completed Tier 1 and Tier 2- execution evidence by default, conservatively resolve conflicting peer- policy and Tier 3 result metadata, bind every tier and policy claim to one- versioned source-tree digest, preserve the Tier 3 run ID, persist an explicit- publication status in JSON and HTML, and reject- publication `PASS` cards whose decision evidence is missing, incomplete,- linked, or hidden in raw HTML. Custom Tier 3 result roots inside the skill are- rejected; use the canonical `evals/results` path or an external results root.-- Publication source identity now seals forward, reverse, and final source reads,- normalizes filesystem case aliases, aligns Tier 1/Tier 2 and Tier 3 runtime- projections with the v2 generated-artifact exclusions, and carries a bounded- source-change marker through rerendered Tier 3 evidence.-- Report output is required outside the publication target. A default- in-target `reports/` location relocates to an authenticated sibling- `<skill>-reports` (or `<catalog>-reports`), refuses unowned collisions, and is- excluded from Tier 3 full-repository staging.-- Public benchmark provenance now rejects placeholder identities, malformed or- future calendar dates, missing duplicated run IDs, hostile benchmark-policy- metadata, and environment-label substitutions in required proof fields.-- Hardened Tier 3 HTML and Markdown reporting against recursive or malformed- display metadata, Markdown structure injection, and inline-JavaScript- injection through untrusted agent or skill names.+- Tier 3 now decodes bounded native Codex `exec` wrappers into their static+ tool calls. It preserves call order and outer-call provenance, maps an outer+ observation only when its rendered inner call is known, keeps ambiguous+ observations explicit, and reports unsupported or malformed JavaScript as+ untrusted instead of a clean security result.## 0.2.1 - 2026-08-24diff --git a/docs/benchmark-rollout.mdx b/docs/benchmark-rollout.mdxindex c896e513..ccdc29c0 100644--- a/docs/benchmark-rollout.mdx+++ b/docs/benchmark-rollout.mdx@@ -57,10 +57,12 @@ skillevaluator validate ./skills/example-skill \```Tier 1 is always publication-required. Tier 2 and Tier 3 are-publication-required by default. Omitting Tier 2 with `--no-dedup` or-`--tiers 1,3`, or omitting Tier 3 by leaving out `--agent-eval`, therefore-produces an `INCOMPLETE` card with the omitted tier marked `NOT RUN` and never a-publication recommendation. `--no-block-on-dedup` changes the command exit+publication-required by default, and Tier 3 runs by default for skills.+Excluding Tier 2 with `--no-dedup` or a `--tiers` selection without `2` (such+as `--tiers 1,3`), or excluding Tier 3 with `--no-tier3` or a `--tiers`+selection without `3`, therefore produces an `INCOMPLETE` card with the omitted+tier marked `NOT RUN` and never a publication recommendation.+`--no-block-on-dedup` changes the command exitgate; it is not a publication waiver.If a catalog intentionally makes Tier 2 or Tier 3 optional, its orchestration@@ -72,8 +74,9 @@ Do not reuse a prior live score while changing only its label or date. If abaseline was not run, keep the explicit “uplift unavailable” state.When an orchestrator combines tiers from separate jobs, merge the actual result-objects, including each result's `publication_target` and the built-in Tier 1-or Tier 2 `publication_evidence` producer marker, and preserve the explicit+objects, including each result's `publication_target`, the built-in Tier 1+or Tier 2 `publication_evidence` producer marker, and the Tier 1+`tier1_required_checks` lineup, and preserve the explicit`benchmark_policy` in the combined artifact. Every contributing result mustcarry the same exact NFC filesystem-entry name and`skill-evaluator-source-tree/2` digest. Completed Tier 3 evidence@@ -160,11 +163,22 @@ skillevaluator validate ./my-skill \--evaluator-container-revision ghcr.io/nvidia/skillevaluator@sha256:0117bc2e...```+A `PASS` card must also record its `Source digest` and `Tier 3 run ID`, so a+`PASS` card rendered by an earlier release fails the scan until it is+regenerated. Earlier `FAIL`, `NEUTRAL`, and `INCOMPLETE` cards without those+lines still pass; the lines are validated whenever they are present.+The linter rejects configured known leak patterns such as retired productidentities, any validation-profile metadata line, common absolute home paths,ambiguous legacy uplift cells, the old `Num` column, missing metadata/decisionsections, and a publication `PASS` without completed required Tier 1, Tier 2,or Tier 3 evidence.+Structural H1/H2 headings must be undecorated, root-level Markdown; raw HTML,+formatted, quoted, and list-nested headings are rejected as ambiguous. Decision+text is checked using its rendered form, including line breaks and image alt+text. Unicode category C, Zl, and Zp characters are rejected whether literal or+encoded as HTML character references, and confusable aliases of required+headings, metadata labels, tier-table structure, and decision text fail closed.A clean result means none of those configured patterns matched; it is a fixtureregression guard, not proof that a card is safe to publish. Keep human reviewand the repository's broader boundary and security checks in the promotiondiff --git a/docs/cli-reference.mdx b/docs/cli-reference.mdxindex 1f7ae661..37bec63c 100644--- a/docs/cli-reference.mdx+++ b/docs/cli-reference.mdx@@ -228,7 +228,7 @@ The following flags are forwarded to the live-eval engine when Tier 3 is enabled| Flag | Default | Effect || --- | --- | --- || `--tier3 / --no-tier3` | enabled for skills | Run or skip Tier 3 live agent evaluation. Accepts a supported YAML/JSON dataset or native Harbor source and validates it before execution. `--agent-eval` / `--no-agent-eval` are compatibility aliases. Explicit `--tiers` selection controls scope; `--no-tier3` also disables autopilot. |-| `--block-on-agent-eval / --no-block-on-agent-eval` | advisory | Choose whether Tier 3 findings, including missing or invalid selected task-source evidence, participate in the `validate` exit gate. This flag does not enable Tier 3 by itself. |+| `--block-on-agent-eval / --no-block-on-agent-eval` | advisory | Choose whether Tier 3 findings, including missing or invalid selected task-source evidence, participate in the `validate` exit gate. When blocking, only a completed `PASS` verdict with complete attempt coverage passes; `NEUTRAL` and `FAIL` exit 1. This flag does not enable Tier 3 by itself. || `--autopilot / --no-autopilot` | enabled for skills | Generate one starter case when no evaluation source exists, then run Tier 3. Existing sources are reused unchanged; invalid sources are reported. `--no-autopilot` requires an existing source. Explicit tier selection or `--no-tier3` can exclude Tier 3. || `-a, --agents TEXT` | provider-native | Comma-separated Harbor agents to evaluate. Defaults: NVIDIA Build=`opencode`, OpenAI=`codex`, Anthropic=`claude-code`. || `--env-mode` | `docker` | Harbor environment backend (full list under [tier3 evaluate](#tier3-evaluate)). |diff --git a/docs/environment-variables.mdx b/docs/environment-variables.mdxindex 59d0759f..4ef7e891 100644--- a/docs/environment-variables.mdx+++ b/docs/environment-variables.mdx@@ -147,7 +147,8 @@ execution environments are covered in| Variable | Default | Effect || --- | --- | --- || `SKILLEVALUATOR_RESULTS_DIR` | `<skill>/evals/results` | External root for run results. Precedence for writes: the `--results-dir` flag, then this variable, then the canonical in-skill location. Configured roots must remain outside the skill; `evals/results` is the only supported in-skill results root so generated output cannot change the skill's publication identity. Read commands (`view`, `compare`) honor the same order and also fall back to the legacy location so older runs stay visible. |-| `SKILLEVALUATOR_LOCAL_SANDBOX` | `require` | Local-mode sandbox policy. `require` fails closed when no OS sandbox backend (Bubblewrap on Linux, Seatbelt on macOS) is usable; `prefer` degrades to advisory-only guardrails with a loud warning; `off` skips sandbox probing entirely — for skills you fully trust. No value enables native Windows: local mode fails closed there before anything runs — use WSL2 or `--env-mode docker`. |+| `SKILLEVALUATOR_OUTPUT_PROVENANCE_KEY_FILE` | macOS: `~/Library/Application Support/skillevaluator/output-provenance.key`; Linux: `$XDG_STATE_HOME/skillevaluator/output-provenance.key` (`~/.local/state` when `XDG_STATE_HOME` is unset); Windows: `%LOCALAPPDATA%\skillevaluator\output-provenance.key` | Local key that authenticates the markers SkillEvaluator writes into its generated output directories; a directory is replaced only when its marker verifies for that path. The key is created on first use. It must be outside every evaluated skill and generated output tree. On macOS and Linux, the file and its directory must be owned by the current user and not accessible to group or other users. |+| `SKILLEVALUATOR_LOCAL_SANDBOX` | `require` | Local-mode sandbox policy. `require` fails closed when no OS sandbox backend (Bubblewrap on Linux, Seatbelt on macOS) is usable; `prefer` degrades to advisory-only guardrails with a loud warning; `off` skips sandbox probing entirely — for skills you fully trust. Any other value is rejected. No value enables native Windows: local mode fails closed there before anything runs — use WSL2 or `--env-mode docker`. || `SKILLEVALUATOR_LOCAL_ALLOW_NET` | `true` | Network egress for local-mode trials. Set to `0` to airgap a skill that must not reach the network. Incompatible with the `nv_build` provider — NVIDIA Build local agents require network access, so airgapped runs are rejected up front. || `SKILLEVALUATOR_LOCAL_STRICT_READS` | `false` | Tightens the sandbox's read-only view of the host system to a stricter path set. || `SKILLEVALUATOR_LOCAL_INHERIT_AGENT_KEYS` | `false` | When true, local-mode trials inherit the host's agent credential variables into their ambient environment. Off by default so a hostile skill command cannot read credentials — agents and verifiers receive credentials per-exec instead. |diff --git a/docs/reports.mdx b/docs/reports.mdxindex 60065724..3a8a929a 100644--- a/docs/reports.mdx+++ b/docs/reports.mdx@@ -32,10 +32,18 @@ same rule and relocates to `<catalog>-reports/`. An explicit in-target `-o` isrejected; choose an external directory instead. Existing nonempty siblingdirectories are reused only when their SkillEvaluator ownership marker isvalid, preventing the default from overwriting an unrelated directory.+For Tier 3, an output directory inside the target repository or an included+skill root must likewise be new, empty, or already carry a valid ownership+marker. This applies to linked-context staging as well as `--copy-repo`. A+nonempty unowned directory is rejected so selecting an authored subtree cannot+silently remove that subtree from the agent's runtime context.For compatibility, commands launched from a parent directory keep the familiar-layout: `skillevaluator validate ./my-skill` still writes to `./reports/`-because that directory is outside `./my-skill/`.+layout when the default output is safe to claim: `skillevaluator validate+./my-skill` writes to `./reports/` when that directory is absent, empty, or+already authenticated as SkillEvaluator output. If `./reports/` is nonempty+and unowned, the default relocates to `./my-skill-reports/` instead of writing+into unrelated content.For `validate`, that compact default is a pipeline view — a per-check tickerplus a summary. Pass `--verbose` to get the full per-check detail stream in@@ -104,7 +112,10 @@ incomplete still makes the card `INCOMPLETE` because malformed evidence cannotcertify publication. A default-passed result object is not sufficient. Tier 1and Tier 2 evidence must carry a valid `publication_evidence` marker written bya built-in command wrapper, and every recognized result must record a success,-finding, or positive check count that proves it executed. Legacy and custom+finding, or positive check count that proves it executed. Tier 1 must also+cover every default check that applies to the content type: schema, security,+PII, license, code integrity, and Unicode, plus version, quality, and lint for+skills. A run narrowed with `--checks` is reported but cannot certify Tier 1. Legacy and customresults remain visible, and their failures still block publication, but theycannot satisfy a required tier or create a waiver. Generic per-result `optional`metadata is not a publication waiver; only the resolved `benchmark_policy` from@@ -131,11 +142,22 @@ while excluding only known generated artifacts. In particular, authored`BENCHMARK.md`, `skill-card.md`, and `skill.oms.sig`. Filesystem case aliasesare treated according to the host filesystem, while a case-distinct authoredname on a case-sensitive filesystem remains covered. A same-named file below-another authored directory is still included. Tier 1, Tier 2, Tier 3 runtime-projection, and full `--copy-repo` staging omit the same generated inputs so-bytes outside the claimed identity cannot affect evaluation evidence. Split-job-results must match this identity exactly. Legacy anonymous results remain-readable, but their publication status is `INCOMPLETE`.+another authored directory is still included. Tier 3 runtime projection and+full `--copy-repo` staging omit the same generated inputs so excluded generated+bytes inside the target cannot affect evaluation evidence. Tier 1 and Tier 2+skip the generated-artifact names (`results`, `versions`, `evals`, their dot+variants, `BENCHMARK.md`, `skill-card.md`, and `skill.oms.sig`) at any depth.+When one of those names appears below the target root, the digest would certify+content that no scan read, so the Tier 1 run records the path and publication+stays `INCOMPLETE` until it is renamed. The root `evals/` directory holds Tier 3+inputs and is outside the Tier 1 scans by design.+Split-job results must match this identity exactly. Tier 3 runs that stage any+linked/full repository context or external reference/workspace skills, or task+inputs and custom environments that carry `.git`, `.venv`, `__pycache__`, or+`node_modules` entries, remain runnable but are marked `INCOMPLETE`, because+that projection is not fully determined by this target-only publication+identity. Legacy anonymous results+remain readable, but their publication status is `INCOMPLETE`.Built-in Tier 1 and Tier 2 results also carry a versioned`publication_evidence` object with exact `schema_version`, `producer`, `tier`,@@ -500,6 +522,13 @@ For CI and tooling, two JSON entry points matter:blocking with `--block-on-agent-eval`; Tier 2 is blocking for the exit codeby default and becomes advisory with `--no-block-on-dedup`. Those exit-codecontrols are separate from `benchmark_policy`.+- **The evaluated source identity**: every JSON report always carries a+ top-level `evaluated_source` object, resolved from every carrier the run+ recorded, so the JSON and `BENCHMARK.md` name the same source tree. It is+ `null` when the orchestration input supplied none. Carriers that name+ different sources abort the run before any report file is written, so a+ contradictory identity is never published in one format and reported in+ another.Both paths speak the same dialect: standalone `tier3 evaluate` and`validate --tier3` share one HTML renderer for `report.html`, and both embeddiff --git a/docs/superpowers/specs/2026-08-24-required-tier-publication-evidence-design.md b/docs/superpowers/specs/2026-08-24-required-tier-publication-evidence-design.mdindex 51b0c2a6..c99ce147 100644--- a/docs/superpowers/specs/2026-08-24-required-tier-publication-evidence-design.md+++ b/docs/superpowers/specs/2026-08-24-required-tier-publication-evidence-design.md@@ -42,8 +42,16 @@ the gap by validating only Tier 3 consistency.root generated state/result/version directories; `evals/results`; and thethree generated root publication files. Filesystem aliases follow actualfilesystem identity, and a same-named nested authored file remains covered.- Producer scans and Tier 3 agent-visible projections share this exclusion- contract. A missing, malformed, or different digest makes+ Tier 3 agent-visible projections share this exclusion contract. Producer+ scans skip generated-artifact names at any depth, so a Tier 1 run records any+ certified path below the root that they skipped, and publication stays+ INCOMPLETE until that path is renamed. A Tier 3 projection that actually adds linked/full repository+ context cannot certify publication until runtime context has its own+ versioned identity; full-mode selection can depend on excluded Git/operator+ state even when the repository root is the target. External reference or+ workspace skills have the same restriction. The run remains usable but+ carries a source-identity conflict and is `INCOMPLETE`. A missing, malformed,+ or different digest makespublication `INCOMPLETE` even when the visible target names match.- Completed Tier 3 evidence carries its run-owned `run_id` in both the payloadand summary. The runner persists the target identity at the executiondiff --git a/docs/tier3-live-evaluation.mdx b/docs/tier3-live-evaluation.mdxindex 4214e97e..00e3d08d 100644--- a/docs/tier3-live-evaluation.mdx+++ b/docs/tier3-live-evaluation.mdx@@ -222,7 +222,10 @@ nested, reference, or workspace skill into agent-visible copies. Runtime skillprojection and `--copy-repo` also omit every generated path excluded by theversioned publication-source digest. The active report directory and the wholecatalog report root are explicitly excluded from full repo context, preventing-a repeated run from exposing prior reports or Tier 3 evidence to the agent.+a repeated run from exposing prior reports or Tier 3 evidence to the agent. An+in-repository report directory is excluded only after SkillEvaluator reserves+or authenticates it as generated output; a nonempty unowned directory is+rejected instead of silently removing authored files from `--copy-repo`.Authenticated historical result roots remain excluded after the configuredoutput location is changed; a present marker that is copied, stale, or cannotbe authenticated fails staging closed instead of copying that tree. Custom result roots created@@ -238,6 +241,16 @@ dataset/configuration files, graders, developer eval guidance, benchmarkconversion reports, native Harbor tasks, custom environments, evaluator tests,or generated results.+Publication identity covers the evaluated skill tree itself. A Tier 3 run that+actually stages linked or full-repository context, or separately configured+external reference/workspace skills, still executes and remains available for+diagnosis, but its publication evidence fails closed as `INCOMPLETE`.+Full-repository selection also depends on Git/operator state excluded from the+skill digest, even when the repository root is the skill directory. Keep+publication-certifying runtime inputs inside the evaluated skill tree without+repository-context staging. Binding arbitrary repository projections under a+separate, versioned identity is not currently supported.+MCP declarations are read only from a bounded, stable, single-link regular`evals/environment/mcp_servers.toml` through a descriptor-anchored evaluatorroot. Linked configuration files or parents, hardlinks, reparse points, and@@ -449,7 +462,9 @@ cloud backend for untrusted code.Attached to `validate`, Tier 3 is advisory by default: its results appear in thecombined reports without changing the exit code. Add `--block-on-agent-eval`to make its findings gate, including evidence that the selected YAML/JSON-dataset or native Harbor source is missing or invalid. Autopilot is enabled+dataset or native Harbor source is missing or invalid. A blocking Tier 3 passes+only with a completed `PASS` verdict and complete attempt coverage; `NEUTRAL`+and `FAIL` verdicts exit 1. Autopilot is enabledby default for skills: it generates one starter case when no source exists andreuses valid existing sources unchanged. `--full` remains supported but isunnecessary. Use `--tiers 1,2` or `--no-tier3` to skip live evaluation;diff --git a/scripts/ci/check_public_benchmarks.py b/scripts/ci/check_public_benchmarks.pyindex a9b3a46b..2c7e733d 100644--- a/scripts/ci/check_public_benchmarks.py+++ b/scripts/ci/check_public_benchmarks.py@@ -26,7 +26,7 @@ from urllib.parse import unquote as url_unquotefrom markdown_it import MarkdownIt-from skillevaluator.publication_text import publication_identity_present+from skillevaluator.publication_text import publication_confusable_skeleton, publication_identity_presentif TYPE_CHECKING:from markdown_it.token import Token@@ -36,13 +36,16 @@ REQUIRED_MARKERS = ("- Evaluator version:","- Agents:","- Tasks:",- "- Source digest:","- Dataset digest:",- "- Tier 3 run ID:","- Attempts per task:","- Environment:","- Tier 3 evidence:",)+# Cards rendered before the publication identity contract have no Source+# digest or Tier 3 run ID lines. Those fields are validated whenever present,+# but only a PASS card must carry them (see _check_pass_source_identity and+# _check_pass_provenance), so earlier non-PASS cards still pass the scan.+_PASS_ONLY_METADATA_FIELDS = frozenset({"Source digest", "Tier 3 run ID"})_REQUIRED_HEADINGS = ((1, "Skill Benchmark:", True, "# Skill Benchmark:"),@@ -60,7 +63,7 @@ LINE_RULES = (("internal environment identity",re.compile(- r"(?:^\s*-\s*Environment:\s*`?astra`?\s*$|\bastra[\s_-]+sandbox\b)",+ r"(?:^\s*-\s*Environment:\s*`?astra(?:[^A-Za-z0-9]|$)|\bastra[\s_-]+sandbox\b)",flags=re.IGNORECASE,),),@@ -101,6 +104,9 @@ _OVERALL_VERDICT_FIELD = re.compile(r"^\s*(?:(?:✅|❌|⚠\ufe0f?)\s*)?Overall verdict:\s*(?P<value>.*)$",flags=re.IGNORECASE,)+_OVERALL_VERDICT_SKELETON_FIELD = re.compile(+ r"^\s*(?:(?:✅|❌|⚠\ufe0f?)\s*)?overall verdict:\s*(?P<value>.*)$",+)_INVISIBLE_IDENTITY_CHARACTERS = frozenset({"\u115f",@@ -124,19 +130,19 @@ _METADATA_FIELD_RULES = (),("Evaluation date",- re.compile(r"(?:\d{4}-\d{2}-\d{2}|not recorded\b.*)", flags=re.IGNORECASE).fullmatch,+ re.compile(r"(?:\d{4}-\d{2}-\d{2}|not recorded\b.*)", flags=re.IGNORECASE),),("Evaluator version",- re.compile(r"(?:`[^`\s][^`]*`|not recorded\b.*)", flags=re.IGNORECASE).fullmatch,+ re.compile(r"(?:`[^`\s][^`]*`|not recorded\b.*)", flags=re.IGNORECASE),),("Tasks",- re.compile(r"(?:[1-9]\d*\s+evaluation tasks?(?:\s+\(.*\))?|not recorded\b.*)", flags=re.IGNORECASE).fullmatch,+ re.compile(r"(?:[1-9]\d*\s+evaluation tasks?(?:\s+\(.*\))?|not recorded\b.*)", flags=re.IGNORECASE),),("Dataset digest",- re.compile(r"(?:`[^`\s][^`]*`(?:\s+\([^)]*\))?|not recorded\b.*)", flags=re.IGNORECASE).fullmatch,+ re.compile(r"(?:`[^`\s][^`]*`(?:\s+\([^)]*\))?|not recorded\b.*)", flags=re.IGNORECASE),),("Tier 3 run ID",@@ -144,17 +150,25 @@ _METADATA_FIELD_RULES = (),("Attempts per task",- re.compile(r"(?:[1-9]\d*|not recorded\b.*)", flags=re.IGNORECASE).fullmatch,+ re.compile(r"(?:[1-9]\d*|not recorded\b.*)", flags=re.IGNORECASE),),("Environment",- re.compile(r"(?:`[^`\s][^`]*`|not recorded\b.*)", flags=re.IGNORECASE).fullmatch,+ re.compile(r"(?:`[^`\s][^`]*`|not recorded\b.*)", flags=re.IGNORECASE),),("Tier 3 evidence",re.compile(r"(?:required for publication|optional by policy)"),),)+_METADATA_FIELD_NAMES = (+ *(field for field, _pattern in _METADATA_FIELD_RULES),+ "Tier 2 evidence",+ "Agents",+ "Evaluated source",+ "Evaluated source revision",+ "Evaluator container revision",+)_PASS_SOURCE_METADATA_FIELD_RULES = (("Source digest",@@ -162,20 +176,119 @@ _PASS_SOURCE_METADATA_FIELD_RULES = (),)_PASS_METADATA_FIELD_RULES = (- ("Evaluation date", re.compile(r"\d{4}-\d{2}-\d{2}").fullmatch),- ("Evaluator version", re.compile(r"`[^`\s][^`]*`").fullmatch),- ("Tasks", re.compile(r"[1-9]\d*\s+evaluation tasks?(?:\s+\(.*\))?", flags=re.IGNORECASE).fullmatch),+ ("Evaluation date", re.compile(r"\d{4}-\d{2}-\d{2}")),+ ("Evaluator version", re.compile(r"`[^`\s][^`]*`")),+ ("Tasks", re.compile(r"[1-9]\d*\s+evaluation tasks?(?:\s+\(.*\))?", flags=re.IGNORECASE)),("Dataset digest",re.compile(r"`sha256:[0-9a-f]{64}`\s+\(skill-evaluator-dataset-snapshot/1\)",flags=re.IGNORECASE,- ).fullmatch,+ ),),("Tier 3 run ID", re.compile(r"`[A-Za-z0-9][A-Za-z0-9._-]{0,159}`")),("Attempts per task", re.compile(r"[1-9]\d*")),("Environment", re.compile(r"`[^`\s][^`]*`")),)++# Evaluated-source provenance is opt-in. A card published before the identity+# contract existed cannot carry these fields, and the orchestration side has to+# supply them first, so the default scan stays byte-compatible with the previous+# behaviour and CI enables --require-source-provenance once the pipeline does.+_SOURCE_PROVENANCE_MARKERS = (+ "- Evaluated source:",+ "- Evaluated source revision:",+ "- Evaluator container revision:",+)+_SOURCE_REPOSITORY_VALUE = r"`[A-Za-z0-9][A-Za-z0-9._-]{0,38}/[A-Za-z0-9][A-Za-z0-9._-]{0,99}`"+# Mirrors ``skillevaluator.source_identity``: a full Git object id (SHA-1 or+# SHA-256), or a digest whose width matches the algorithm it names. A short+# prefix and an under-length digest are both rejected as ambiguous.+_SOURCE_REVISION_VALUE = r"`(?:[0-9a-f]{40}|[0-9a-f]{64}|sha256:[0-9a-f]{64}|sha384:[0-9a-f]{96}|sha512:[0-9a-f]{128})`"+_NOT_RECORDED_VALUE = re.compile(r"not recorded\b.*")+# Mirrors ``skillevaluator.source_identity`` character for character, including+# the path length, so the two sides cannot drift: an OCI reference is bounded+# component by component rather than as a whole string, because one cap over the+# whole reference counts the ``@sha256:`` suffix against the repository path and+# silently discards an ordinary name pinned by digest. The bound measures the+# path once the registry host has been split off it, which is where the+# reference grammar's RepositoryNameTotalLengthMax applies.+_CONTAINER_PATH_MAX = 255+# A first component is a registry host only where the reference grammar says so:+# it is ``localhost``, it carries a dot, or it carries a port. Anything else+# begins the path, whose components are lower case, while a host label is+# matched in either case because DNS is case-insensitive.+_CONTAINER_HOST_LABEL = r"[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?"+_CONTAINER_REFERENCE_PATTERN = (+ r"(?P<name>"+ rf"(?:(?:localhost|{_CONTAINER_HOST_LABEL}(?:\.{_CONTAINER_HOST_LABEL})+)(?::[0-9]+)?/"+ rf"|{_CONTAINER_HOST_LABEL}:[0-9]+/)?"+ r"(?P<path>"+ r"[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*"+ r"(?:/[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*)*"+ r")"+ r")"+ r"(?::(?P<tag>[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}))?"+ r"(?:@(?P<digest>sha256:[0-9a-f]{64}|sha384:[0-9a-f]{96}|sha512:[0-9a-f]{128}))?"+)+_CONTAINER_REFERENCE = re.compile(_CONTAINER_REFERENCE_PATTERN)+# Anchors included, so this is the same pattern text as ``_SOURCE_COMMIT`` and+# the drift test can compare the two strings rather than trusting the eye.+_GIT_OBJECT_ID = re.compile(r"^(?:[0-9a-f]{40}|[0-9a-f]{64})$")+++def _code_span_value(value: str) -> str | None:+ """Return what a metadata field renders inside its code span, or ``None``."""+ if len(value) > 2 and value.startswith("`") and value.endswith("`"):+ return value[1:-1]+ return None+++def _valid_container_reference(reference: str, *, require_digest: bool) -> bool:+ if _GIT_OBJECT_ID.fullmatch(reference):+ # An evaluator run from a source checkout names its implementation+ # revision instead of an image, and that revision is already immutable.+ return True+ match = _CONTAINER_REFERENCE.fullmatch(reference)+ if match is None or len(match["path"]) > _CONTAINER_PATH_MAX:+ return False+ # A bare name identifies a repository rather than the build that ran, so it+ # never records a revision on its own.+ return bool(match["digest"]) if require_digest else bool(match["tag"] or match["digest"])+++def _valid_container_revision(value: str) -> bool:+ """Accept a reference that names a revision, or the recorded absence."""+ if _NOT_RECORDED_VALUE.fullmatch(value):+ return True+ reference = _code_span_value(value)+ return reference is not None and _valid_container_reference(reference, require_digest=False)+++_SOURCE_METADATA_FIELD_RULES = (+ ("Evaluated source", re.compile(rf"(?:{_SOURCE_REPOSITORY_VALUE}|not recorded\b.*)").fullmatch),+ ("Evaluated source revision", re.compile(rf"(?:{_SOURCE_REVISION_VALUE}|not recorded\b.*)").fullmatch),+ ("Evaluator container revision", _valid_container_revision),+)+++def _valid_pass_container_revision(value: str) -> bool:+ """Require the digest of the build that ran, on the same grammar as above.++ A mutable tag can be repointed to a different build after the card is+ published, which leaves the reader unable to recover what actually ran, so a+ PASS has to pin the evaluator by digest or by a full implementation revision.+ """+ reference = _code_span_value(value)+ return reference is not None and _valid_container_reference(reference, require_digest=True)+++_PASS_SOURCE_PROVENANCE_RULES = (+ ("Evaluated source", re.compile(_SOURCE_REPOSITORY_VALUE).fullmatch),+ ("Evaluated source revision", re.compile(_SOURCE_REVISION_VALUE).fullmatch),+ ("Evaluator container revision", _valid_pass_container_revision),+)+_TIER_COMPLETION_STATUSES = {1: frozenset({"PASSED", "PASSED WITH OBSERVATIONS"}),2: frozenset({"PASSED", "PASSED WITH OBSERVATIONS"}),@@ -193,31 +306,200 @@ _MAX_BENCHMARK_BYTES = 128 * 1024_MAX_BENCHMARK_LINE_CHARACTERS = 32 * 1024_MARKDOWN = MarkdownIt("commonmark").enable("table")_NON_RENDERED_HTML_TAGS = frozenset({"noscript", "script", "style", "template"})+_STRUCTURAL_HTML_HEADING_TAGS = frozenset({"h1", "h2"})_VOID_HTML_TAGS = frozenset({"area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"})+_HTML_TEXT_SEPARATOR_TAGS = frozenset(+ {+ "address",+ "article",+ "aside",+ "blockquote",+ "dd",+ "details",+ "div",+ "dl",+ "dt",+ "fieldset",+ "figcaption",+ "figure",+ "footer",+ "form",+ "h1",+ "h2",+ "h3",+ "h4",+ "h5",+ "h6",+ "header",+ "hgroup",+ "hr",+ "li",+ "main",+ "nav",+ "ol",+ "p",+ "pre",+ "section",+ "summary",+ "table",+ "tbody",+ "td",+ "tfoot",+ "th",+ "thead",+ "tr",+ "ul",+ }+)+_AMBIGUOUS_HTML_RENDERING_TAGS = _NON_RENDERED_HTML_TAGS | frozenset(+ {+ "audio",+ "base",+ "bdi",+ "bdo",+ "button",+ "canvas",+ "dialog",+ "embed",+ "form",+ "iframe",+ "input",+ "link",+ "math",+ "meta",+ "meter",+ "noembed",+ "noframes",+ "object",+ "option",+ "optgroup",+ "output",+ "picture",+ "plaintext",+ "progress",+ "select",+ "source",+ "svg",+ "table",+ "textarea",+ "video",+ "xmp",+ }+)+_AMBIGUOUS_HTML_RENDERING_ATTRIBUTES = frozenset(+ {+ "align",+ "bgcolor",+ "class",+ "color",+ "dir",+ "face",+ "height",+ "hidden",+ "id",+ "inert",+ "size",+ "style",+ "width",+ }+)+++def _html_element_is_visually_hidden(tag: str, attrs: list[tuple[str, str | None]]) -> bool:+ """Return whether an HTML element is removed from visual rendering."""+ if tag.casefold() in _NON_RENDERED_HTML_TAGS:+ return True+ normalized_attrs = {name.casefold(): value for name, value in attrs}+ if "hidden" in normalized_attrs:+ return True+ style = normalized_attrs.get("style")+ if style is None:+ return False+ uncommented_style = re.sub(r"/\*.*?\*/", "", style, flags=re.DOTALL)+ declarations: dict[str, tuple[str, bool]] = {}+ for declaration in uncommented_style.split(";"):+ property_name, separator, value = declaration.partition(":")+ if not separator:+ continue+ normalized_property = property_name.strip().casefold()+ if normalized_property not in {"display", "visibility"}:+ continue+ important = re.search(r"!\s*important\s*$", value, flags=re.IGNORECASE) is not None+ normalized_value = re.sub(r"!\s*important\s*$", "", value, flags=re.IGNORECASE).strip().casefold()+ previous = declarations.get(normalized_property)+ if previous is not None and previous[1] and not important:+ continue+ declarations[normalized_property] = (normalized_value, important)+ display = declarations.get("display", ("", False))[0]+ visibility = declarations.get("visibility", ("", False))[0]+ return display == "none" or visibility in {"hidden", "collapse"}+++def _close_html_element_stack(stack: list[tuple[str, bool]], tag: str) -> int | None:+ """Pop one exactly nested element; ambiguous markup stays fail-closed."""+ if not stack or stack[-1][0] != tag:+ return None+ _name, is_hidden = stack.pop()+ return int(is_hidden)class _VisibleHTMLParser(HTMLParser):"""Collect rendered text while suppressing comments and control elements."""- def __init__(self) -> None:+ def __init__(self, *, suppress_visually_hidden: bool = True) -> None:super().__init__(convert_charrefs=True)+ self._suppress_visually_hidden = suppress_visually_hidden+ self._element_stack: list[tuple[str, bool]] = []self._hidden_depth = 0self._line_parts: dict[int, list[str]] = {}def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:- del attrs- if tag.casefold() in _NON_RENDERED_HTML_TAGS:- self._hidden_depth += 1+ normalized_tag = tag.casefold()+ is_hidden = normalized_tag in _NON_RENDERED_HTML_TAGS or (+ self._suppress_visually_hidden and _html_element_is_visually_hidden(normalized_tag, attrs)+ )+ if normalized_tag not in _VOID_HTML_TAGS:+ self._element_stack.append((normalized_tag, is_hidden))+ if is_hidden:+ if normalized_tag not in _VOID_HTML_TAGS:+ self._hidden_depth += 1+ return+ if self._hidden_depth:+ return+ if normalized_tag == "br" or normalized_tag in _HTML_TEXT_SEPARATOR_TAGS:+ self._append_visible(" ")+ elif normalized_tag == "img":+ alt = next((value for name, value in attrs if name.casefold() == "alt"), None)+ if alt is not None:+ self._append_visible(f" {alt} ")++ def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:+ # HTML slash syntax does not self-close non-void elements in browsers.+ self.handle_starttag(tag, attrs)def handle_endtag(self, tag: str) -> None:- if tag.casefold() in _NON_RENDERED_HTML_TAGS and self._hidden_depth:- self._hidden_depth -= 1+ normalized_tag = tag.casefold()+ if normalized_tag == "br":+ if not self._hidden_depth:+ # HTML5 treats the otherwise-invalid </br> token as <br>.+ self._append_visible(" ")+ return+ hidden_before = self._hidden_depth+ hidden_count = _close_html_element_stack(self._element_stack, normalized_tag)+ if hidden_count is None:+ return+ self._hidden_depth = max(0, self._hidden_depth - hidden_count)+ if not hidden_before and normalized_tag in _HTML_TEXT_SEPARATOR_TAGS:+ self._append_visible(" ")def handle_data(self, data: str) -> None:if self._hidden_depth:return+ self._append_visible(data)++ def _append_visible(self, data: str) -> None:start_line, _column = self.getpos()for offset, part in enumerate(data.split("\n")):self._line_parts.setdefault(start_line + offset, []).append(part)@@ -236,14 +518,50 @@ class _HTMLAttributeParser(HTMLParser):def __init__(self) -> None:super().__init__(convert_charrefs=True)self.values: list[str] = []+ self.image_alts: list[str] = []+ self.events: list[tuple[str, str, bool, str | None, int]] = []+ self.ambiguous_rendering_lines: list[int] = []def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:- del tag+ normalized_tag = tag.casefold()self.values.extend(value for _name, value in attrs if value is not None)+ alt = next((value for name, value in attrs if name.casefold() == "alt"), None)+ line = self.getpos()[0]+ self.events.append(("start", normalized_tag, _html_element_is_visually_hidden(normalized_tag, attrs), alt, line))+ attribute_names = {name.casefold() for name, _value in attrs}+ if (+ normalized_tag in _AMBIGUOUS_HTML_RENDERING_TAGS+ or attribute_names & _AMBIGUOUS_HTML_RENDERING_ATTRIBUTES+ or any(name.startswith("on") for name in attribute_names)+ ):+ self.ambiguous_rendering_lines.append(line)+ if normalized_tag == "img":+ self.image_alts.extend(value for name, value in attrs if name.casefold() == "alt" and value is not None)def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:self.handle_starttag(tag, attrs)+ def handle_endtag(self, tag: str) -> None:+ self.events.append(("end", tag.casefold(), False, None, self.getpos()[0]))+++class _RawStructuralHeadingParser(HTMLParser):+ """Locate raw HTML headings that cannot be trusted as card structure."""++ def __init__(self) -> None:+ super().__init__(convert_charrefs=True)+ self.lines: list[int] = []++ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:+ del attrs+ if tag.casefold() in _STRUCTURAL_HTML_HEADING_TAGS:+ self.lines.append(self.getpos()[0])++ def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:+ # A slash does not self-close h1/h2 in text/html, but the start still+ # creates ambiguous browser-visible structure and must be rejected.+ self.handle_starttag(tag, attrs)+class _HTMLStructureParser(HTMLParser):"""Collect real tag events/headings without regex-parsing quoted markup."""@@ -251,22 +569,42 @@ class _HTMLStructureParser(HTMLParser):def __init__(self) -> None:super().__init__(convert_charrefs=True)self.events: list[tuple[str, str]] = []- self.headings: list[tuple[int, str]] = []+ self.headings: list[tuple[int, int, str]] = []self._heading_level: int | None = None+ self._heading_line = 1self._heading_parts: list[str] = []+ self._element_stack: list[tuple[str, bool]] = []+ self._hidden_depth = 0self._in_noscript = Falsedef handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:- del attrsnormalized_tag = tag.casefold()if self._in_noscript:returnself.events.append(("start", normalized_tag))+ is_hidden = _html_element_is_visually_hidden(normalized_tag, attrs)+ if normalized_tag not in _VOID_HTML_TAGS:+ self._element_stack.append((normalized_tag, is_hidden))if normalized_tag == "noscript":self._in_noscript = True- if normalized_tag in {"h1", "h2"} and self._heading_level is None:+ if is_hidden:+ if normalized_tag not in _VOID_HTML_TAGS:+ self._hidden_depth += 1+ return+ if self._hidden_depth:+ return+ if normalized_tag in _STRUCTURAL_HTML_HEADING_TAGS and self._heading_level is None:self._heading_level = int(normalized_tag[1])+ self._heading_line = self.getpos()[0]self._heading_parts = []+ elif self._heading_level is not None and (+ normalized_tag == "br" or normalized_tag in _HTML_TEXT_SEPARATOR_TAGS+ ):+ self._heading_parts.append(" ")+ elif self._heading_level is not None and normalized_tag == "img":+ alt = next((value for name, value in attrs if name.casefold() == "alt"), None)+ if alt is not None:+ self._heading_parts.extend((" ", alt, " "))def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:# HTML slash syntax does not self-close non-void elements in browsers.@@ -274,24 +612,47 @@ class _HTMLStructureParser(HTMLParser):def handle_endtag(self, tag: str) -> None:normalized_tag = tag.casefold()+ if normalized_tag == "br":+ self.events.append(("end", normalized_tag))+ if not self._in_noscript and not self._hidden_depth and self._heading_level is not None:+ self._heading_parts.append(" ")+ returnif self._in_noscript:if normalized_tag != "noscript":returnself._in_noscript = Falseself.events.append(("end", normalized_tag))+ hidden_before = self._hidden_depth+ hidden_count = _close_html_element_stack(self._element_stack, normalized_tag)+ if hidden_count:+ self._hidden_depth = max(0, self._hidden_depth - hidden_count)+ if self._hidden_depth:+ return+ if (+ not hidden_before+ and self._heading_level is not None+ and normalized_tag in _HTML_TEXT_SEPARATOR_TAGS+ and normalized_tag != f"h{self._heading_level}"+ ):+ self._heading_parts.append(" ")if self._heading_level is not None and normalized_tag == f"h{self._heading_level}":title = " ".join("".join(self._heading_parts).split())- self.headings.append((self._heading_level, title))+ self.headings.append((self._heading_level, self._heading_line, title))self._heading_level = Noneself._heading_parts = []def handle_data(self, data: str) -> None:- if not self._in_noscript and self._heading_level is not None:+ if not self._in_noscript and not self._hidden_depth and self._heading_level is not None:self._heading_parts.append(data)@lru_cache(maxsize=256)-def _html_structure(content: str) -> tuple[tuple[tuple[str, str], ...], tuple[tuple[int, str], ...]]:+def _html_structure(+ content: str,+) -> tuple[+ tuple[tuple[str, str], ...],+ tuple[tuple[int, int, str], ...],+]:parser = _HTMLStructureParser()try:parser.feed(content)@@ -334,11 +695,15 @@ def scan_file(path: Path, *, require_source_provenance: bool = False) -> list[Ofreturn [Offender(path, 1, f"unreadable file ({type(error).__name__})")]offenders: list[Offender] = []- line_number = 1- for character in text:- if character == "\n":- line_number += 1- elif character not in {"\r", "\t"} and unicodedata.category(character) == "Cc":+ for line_number, line in enumerate(text.splitlines(keepends=True), 1):+ # Character references can render the same bidirectional and format+ # controls as literal Unicode. Reject both representations before any+ # semantic normalization removes them.+ encoded_surface = unescape(line.replace("\n", "").replace("\r", "").replace("\t", ""))+ if _contains_disallowed_category_c(line, allow_layout_whitespace=True) or _contains_disallowed_category_c(+ encoded_surface,+ allow_layout_whitespace=False,+ ):offenders.append(Offender(path, line_number, "benchmark contains disallowed control character"))break@@ -369,41 +734,76 @@ def scan_file(path: Path, *, require_source_provenance: bool = False) -> list[Ofrendered_surfaces = () if line_number in literal_code_lines else _rendered_inline_surfaces(line)semantic_lines = tuple(_semantic_text(surface) for surface in (line, *rendered_surfaces))for reason, pattern in LINE_RULES:- if any(pattern.search(semantic_line) for semantic_line in semantic_lines):+ candidate_lines = semantic_lines+ if reason in {"retired product identity", "internal environment identity"}:+ candidate_lines = (+ *candidate_lines,+ *(publication_confusable_skeleton(semantic_line) for semantic_line in semantic_lines),+ )+ if reason == "internal environment identity":+ for semantic_line in semantic_lines:+ environment_field = re.match(+ r"^\s*-\s*Environment:\s*(?P<value>.*)$",+ semantic_line,+ flags=re.IGNORECASE,+ )+ if environment_field is not None:+ candidate_lines = (+ *candidate_lines,+ "- Environment: "+ + publication_confusable_skeleton(environment_field.group("value")),+ )+ if any(pattern.search(candidate_line) for candidate_line in candidate_lines):offenders.append(Offender(path, line_number, reason))semantic_document = _semantic_text(text)for reason, pattern in LINE_RULES:if reason not in {"retired product identity", "internal environment identity"}:continue- if pattern.search(semantic_document) and not any(offender.reason == reason for offender in offenders):+ if (+ pattern.search(semantic_document)+ or pattern.search(publication_confusable_skeleton(semantic_document))+ ) and not any(offender.reason == reason for offender in offenders):offenders.append(Offender(path, 1, reason))_check_required_headings(path, text, offenders)- _check_metadata_semantics(path, text, offenders)- _check_verdict_tier_consistency(path, text, offenders)- if require_source_provenance and _PUBLISHED_PASS.search(text):- # Independent of the Tier 3 row: a card publishing a PASS must name the- # source it evaluated, including one skipped under an optional policy.- _check_source_provenance(path, text, offenders)+ _check_metadata_semantics(path, text, offenders, require_source_provenance=require_source_provenance)+ _check_verdict_tier_consistency(path, text, offenders, require_source_provenance=require_source_provenance)+ _check_untrusted_structural_headings(path, text, offenders)+ _check_html_rendering_safety(path, text, offenders)return offendersdef _check_required_headings(path: Path, text: str, offenders: list[Offender]) -> None:"""Require canonical headings in rendered Markdown structure."""headings = _heading_entries(text)+ for _index, level, line, title, _trusted in headings:+ structural_title = title.partition(":")[0] + ":" if level == 1 and ":" in title else title+ if level in {1, 2} and not structural_title.isascii():+ offenders.append(Offender(path, line, "non-ASCII structural heading"))for required_level, required_title, is_prefix, marker in _REQUIRED_HEADINGS:+ required_visual_key = _visual_text_key(required_title)+ required_canonical_key = _canonical_text_key(required_title)matching_headings = [(line, title, trusted)for _index, level, line, title, trusted in headingsif level == required_leveland (- _semantic_text(title).casefold().startswith(required_title.casefold())+ _visual_text_key(title).startswith(required_visual_key)if is_prefix- else _semantic_text(title).casefold() == required_title.casefold()+ else _visual_text_key(title) == required_visual_key+ )+ ]+ trusted_headings = [+ heading+ for heading in matching_headings+ if heading[2]+ and (+ _canonical_text_key(heading[1]).startswith(required_canonical_key)+ if is_prefix+ else _canonical_text_key(heading[1]) == required_canonical_key)]- trusted_headings = [heading for heading in matching_headings if heading[2]]trusted_prefix_identity = (trusted_headings[0][1][len(required_title) :]if trusted_headings and trusted_headings[0][1].casefold().startswith(required_title.casefold())@@ -415,23 +815,88 @@ def _check_required_headings(path: Path, text: str, offenders: list[Offender]) -offenders.append(Offender(path, matching_headings[1][0], f"duplicate required section: {marker}"))-def _check_metadata_semantics(path: Path, text: str, offenders: list[Offender]) -> None:+def _check_untrusted_structural_headings(path: Path, text: str, offenders: list[Offender]) -> None:+ """Require root h1/h2 structure to use unambiguous plain Markdown text."""+ duplicate_lines = {offender.line for offender in offenders if offender.reason.startswith("duplicate ")}+ for line_number in _untrusted_structural_heading_lines(text):+ if line_number not in duplicate_lines:+ offenders.append(Offender(path, line_number, "ambiguous structural heading markup"))+++def _check_html_rendering_safety(path: Path, text: str, offenders: list[Offender]) -> None:+ """Reject raw HTML whose browser presentation cannot be parsed safely."""+ stack: list[tuple[str, int]] = []+ ambiguous_lines: set[int] = set()++ def inspect_fragment(content: str, base_line: int) -> None:+ parser = _HTMLAttributeParser()+ try:+ parser.feed(content)+ parser.close()+ except (AssertionError, ValueError):+ ambiguous_lines.add(base_line)+ return+ ambiguous_lines.update(base_line + relative_line - 1 for relative_line in parser.ambiguous_rendering_lines)+ for event, tag, _visually_hidden, _alt, relative_line in parser.events:+ line = base_line + relative_line - 1+ if event == "start":+ if tag not in _VOID_HTML_TAGS:+ stack.append((tag, line))+ continue+ if tag == "br":+ # HTML5 defines </br> as a line break rather than a close.+ continue+ if not stack or stack[-1][0] != tag:+ ambiguous_lines.add(line)+ continue+ stack.pop()++ for token in _markdown_tokens(text):+ if token.map is None:+ continue+ if token.type == "html_block":+ inspect_fragment(token.content, token.map[0] + 1)+ elif token.type == "inline":+ for child in token.children or []:+ if child.type == "html_inline":+ inspect_fragment(child.content, token.map[0] + 1)++ ambiguous_lines.update(line for _tag, line in stack)+ for line in sorted(ambiguous_lines):+ offenders.append(Offender(path, line, "ambiguous HTML rendering semantics"))+++def _check_metadata_semantics(+ path: Path,+ text: str,+ offenders: list[Offender],+ *,+ require_source_provenance: bool = False,+) -> None:+ metadata_heading_lines = _section_heading_lines(text, "Evaluation Metadata")metadata_sections = _section_occurrences(text, "Evaluation Metadata")- if len(metadata_sections) > 1:- offenders.append(Offender(path, metadata_sections[1][0], "duplicate Evaluation Metadata section"))+ if len(metadata_heading_lines) > 1:+ offenders.append(Offender(path, metadata_heading_lines[1], "duplicate Evaluation Metadata section"))if not metadata_sections:returnfallback_line, section_tokens = metadata_sections[0]metadata_lines = _metadata_list_items(section_tokens)- rules = _METADATA_FIELD_RULES- if require_source_provenance:- rules += _SOURCE_METADATA_FIELD_RULES- for field, is_valid in rules:+ for line_number, source in metadata_lines:+ rendered = _rendered_inline_fragment(source)+ rendered_match = re.match(r"^\s*-\s*(?P<label>[^:]+?)\s*:", rendered or "")+ if rendered_match is not None and not rendered_match.group("label").isascii():+ offenders.append(Offender(path, line_number, "non-ASCII metadata field label"))++ for line_number, field in _confusable_metadata_field_aliases(metadata_lines):+ offenders.append(Offender(path, line_number, f"confusable metadata field: - {field}:"))++ for field, pattern in _METADATA_FIELD_RULES:matches = _metadata_field_matches(metadata_lines, field)marker = f"- {field}:"if not matches:- offenders.append(Offender(path, fallback_line, f"missing metadata field: {marker}"))+ if field not in _PASS_ONLY_METADATA_FIELDS:+ offenders.append(Offender(path, fallback_line, f"missing metadata field: {marker}"))continueline_number, value = matches[0]valid_value = pattern.fullmatch(value) is not None@@ -443,6 +908,17 @@ def _check_metadata_semantics(path: Path, text: str, offenders: list[Offender])if len(matches) > 1 or not valid_value:offenders.append(Offender(path, line_number, f"invalid metadata field: {marker}"))+ if require_source_provenance:+ for field, is_valid in _SOURCE_METADATA_FIELD_RULES:+ matches = _metadata_field_matches(metadata_lines, field)+ marker = f"- {field}:"+ if not matches:+ offenders.append(Offender(path, fallback_line, f"missing metadata field: {marker}"))+ continue+ line_number, value = matches[0]+ if len(matches) > 1 or not is_valid(value):+ offenders.append(Offender(path, line_number, f"invalid metadata field: {marker}"))+tier2_matches = _metadata_field_matches(metadata_lines, "Tier 2 evidence")if tier2_matches:line_number, value = tier2_matches[0]@@ -538,6 +1014,28 @@ def _metadata_field_matches(]+def _confusable_metadata_field_aliases(+ metadata_lines: list[tuple[int, str]],+) -> list[tuple[int, str]]:+ """Return visually canonical metadata labels that are not canonical text."""+ canonical_by_visual_key = {_visual_text_key(field): field for field in _METADATA_FIELD_NAMES}+ aliases: list[tuple[int, str]] = []+ for line_number, source in metadata_lines:+ rendered = _rendered_inline_fragment(source)+ if rendered is None:+ continue+ rendered_match = re.match(r"^\s*-\s*(?P<label>[^:]+?)\s*:", rendered)+ if rendered_match is None:+ continue+ canonical = canonical_by_visual_key.get(_visual_text_key(rendered_match.group("label")))+ if canonical is None:+ continue+ source_match = re.match(r"^\s*-\s*(?P<label>[^:]+?)\s*:", source)+ if source_match is None or _canonical_text_key(source_match.group("label")) != _canonical_text_key(canonical):+ aliases.append((line_number, canonical))+ return aliases++def _metadata_field_value(text: str, field: str) -> str | None:matches = _metadata_field_matches(_metadata_section_lines(text), field)return matches[0][1] if len(matches) == 1 else None@@ -547,23 +1045,38 @@ def _overall_verdict_fields(text: str) -> list[tuple[int, str, str]]:"""Return canonical and visibly callout-shaped verdict fields."""tokens = _markdown_tokens(text)fields: list[tuple[int, str, str]] = []+ seen_fields: set[tuple[int, str]] = set()def add_field(line_number: int, line: str, *, trusted: bool) -> None:semantic_line = _semantic_text(line)match = _OVERALL_VERDICT_FIELD.fullmatch(semantic_line)+ matched_confusable = Falseif match is None:- return+ skeleton_line = publication_confusable_skeleton(semantic_line)+ match = _OVERALL_VERDICT_SKELETON_FIELD.fullmatch(skeleton_line)+ if match is None:+ return+ matched_confusable = Truevalue = match.group("value").strip()- if value.casefold().startswith(("derived from", "pass only when every configured dimension passes")):+ value_skeleton = publication_confusable_skeleton(value)+ methodology_prefixes = tuple(+ publication_confusable_skeleton(prefix)+ for prefix in ("derived from", "pass only when every configured dimension passes")+ )+ if value_skeleton.startswith(methodology_prefixes):# This is the generated methodology definition, not a decision# field. Exact late PASS/FAIL/NEUTRAL/INCOMPLETE fields are still# counted so a second visible verdict cannot hide after metadata.return+ field_key = (line_number, publication_confusable_skeleton(semantic_line))+ if field_key in seen_fields:+ return+ seen_fields.add(field_key)status_match = re.match(r"(?P<status>[A-Za-z]+)\b", value)fields.append((line_number,- status_match.group("status").upper() if trusted and status_match else "",+ status_match.group("status").upper() if trusted and not matched_confusable and status_match else "",value,))@@ -571,8 +1084,12 @@ def _overall_verdict_fields(text: str) -> list[tuple[int, str, str]]:raw_container_stack: list[str] = []for token in tokens:if token.type == "html_block" and token.map is not None:- for relative_line, line in _visible_html_lines(token.content):- add_field(token.map[0] + relative_line, line, trusted=False)+ for suppress_visually_hidden in (True, False):+ for relative_line, line in _visible_html_lines(+ token.content,+ suppress_visually_hidden=suppress_visually_hidden,+ ):+ add_field(token.map[0] + relative_line, line, trusted=False)_update_raw_html_stack(token.content, raw_container_stack)continueif token.type != "inline" or token.map is None:@@ -580,8 +1097,15 @@ def _overall_verdict_fields(text: str) -> list[tuple[int, str, str]]:unsafe_markup = bool(raw_container_stack) or any(child.type in {"html_inline", "link_open", "image"} for child in token.children or [])- for offset, line in enumerate(_inline_visible_lines(token, include_code=False)):- add_field(token.map[0] + offset + 1, line, trusted=not unsafe_markup)+ for suppress_visually_hidden in (True, False) if unsafe_markup else (True,):+ for offset, line in enumerate(+ _inline_visible_lines(+ token,+ include_code=False,+ suppress_visually_hidden=suppress_visually_hidden,+ )+ ):+ add_field(token.map[0] + offset + 1, line, trusted=not unsafe_markup)return fields@@ -591,7 +1115,7 @@ def _section_occurrences(text: str, title: str) -> list[tuple[int, tuple[Token,headings = _heading_entries(text)sections: list[tuple[int, tuple[Token, ...]]] = []for token_index, level, start_line, heading_title, trusted in headings:- if not trusted or level != 2 or _semantic_text(heading_title).casefold() != title.casefold():+ if not trusted or level != 2 or _canonical_text_key(heading_title) != _canonical_text_key(title):continueend_index = len(tokens)# Even an untrusted linked/raw-markup heading ends the current section.@@ -610,6 +1134,16 @@ def _section_occurrences(text: str, title: str) -> list[tuple[int, tuple[Token,return sections+def _section_heading_lines(text: str, title: str) -> list[int]:+ """Return every matching level-two heading, including untrusted variants."""+ title_key = _visual_text_key(title)+ return [+ start_line+ for _token_index, level, start_line, heading_title, _trusted in _heading_entries(text)+ if level == 2 and _visual_text_key(heading_title) == title_key+ ]++@lru_cache(maxsize=128)def _markdown_tokens(text: str) -> tuple[Token, ...]:"""Parse Markdown once so structural checks use rendered block semantics."""@@ -624,9 +1158,10 @@ def _heading_entries(text: str) -> tuple[tuple[int, int, int, str, bool], ...]:raw_container_stack: list[str] = []for index, token in enumerate(tokens):if token.type == "html_block":- if not raw_container_stack and token.map is not None:+ if token.map is not None:headings.extend(- (index, level, token.map[0] + 1, title, False) for level, title in _html_structure(token.content)[1]+ (index, level, token.map[0] + relative_line, title, False)+ for level, relative_line, title in _html_structure(token.content)[1])_update_raw_html_stack(token.content, raw_container_stack)continue@@ -637,15 +1172,91 @@ def _heading_entries(text: str) -> tuple[tuple[int, int, int, str, bool], ...]:inline = tokens[index + 1] if index + 1 < len(tokens) else Noneif inline is None or inline.type != "inline":continue- trusted = not any(child.type in {"html_inline", "link_open", "image"} for child in inline.children or [])+ trusted = _is_plain_markdown_heading(inline)title = " ".join(_inline_visible_lines(inline, include_code=True)).strip()headings.append((index, int(token.tag.removeprefix("h")), token.map[0] + 1, title, trusted))return tuple(headings)-def _inline_visible_lines(token: Token, *, include_code: bool) -> list[str]:+@lru_cache(maxsize=256)+def _raw_structural_heading_relative_lines(content: str) -> tuple[int, ...]:+ """Return line numbers for every real raw-HTML h1/h2 start tag."""+ parser = _RawStructuralHeadingParser()+ try:+ parser.feed(content)+ parser.close()+ except (AssertionError, ValueError):+ # Malformed HTML is untrusted, but without a parsed start tag there is+ # no reliable structural-heading location to report here.+ return ()+ return tuple(parser.lines)+++@lru_cache(maxsize=128)+def _untrusted_structural_heading_lines(text: str) -> tuple[int, ...]:+ """Return root heading lines whose rendered structure is ambiguous."""+ lines: set[int] = set()+ raw_container_stack: list[str] = []+ tokens = _markdown_tokens(text)+ for index, token in enumerate(tokens):+ if token.map is None:+ continue+ if token.type == "html_block":+ lines.update(+ token.map[0] + relative_line for relative_line in _raw_structural_heading_relative_lines(token.content)+ )+ _update_raw_html_stack(token.content, raw_container_stack)+ continue+ if token.type == "heading_open" and token.tag in _STRUCTURAL_HTML_HEADING_TAGS:+ inline = tokens[index + 1] if index + 1 < len(tokens) else None+ if (+ token.level != 0+ or raw_container_stack+ or inline is None+ or inline.type != "inline"+ or not _is_plain_markdown_heading(inline)+ ):+ lines.add(token.map[0] + 1)+ continue+ if token.type != "inline":+ continue+ for child in token.children or []:+ if child.type == "html_inline":+ lines.update(+ token.map[0] + relative_line+ for relative_line in _raw_structural_heading_relative_lines(child.content)+ )+ return tuple(sorted(lines))+++def _is_plain_markdown_heading(inline: Token) -> bool:+ """Return whether a heading contains only undecorated rendered text."""+ return bool(inline.children) and all(child.type == "text" for child in inline.children)+++def _inline_visible_lines(+ token: Token,+ *,+ include_code: bool,+ suppress_visually_hidden: bool = True,+) -> list[str]:"""Flatten inline Markdown into visible lines while excluding inert markup."""+ return _inline_children_visible_lines(+ token.children or [],+ include_code=include_code,+ suppress_visually_hidden=suppress_visually_hidden,+ )+++def _inline_children_visible_lines(+ children: list[Token],+ *,+ include_code: bool,+ suppress_visually_hidden: bool,+) -> list[str]:+ """Flatten inline child tokens, including recursively rendered image alt text."""lines = [""]+ element_stack: list[tuple[str, bool]] = []hidden_html_depth = 0def append_text(content: str) -> None:@@ -653,30 +1264,56 @@ def _inline_visible_lines(token: Token, *, include_code: bool) -> list[str]:lines[-1] += parts[0]lines.extend(parts[1:])- for child in token.children or []:+ for child in children:if child.type == "html_inline":- events, _headings = _html_structure(child.content)- for event, tag in events:- if tag not in _NON_RENDERED_HTML_TAGS:- continue+ attribute_parser = _HTMLAttributeParser()+ try:+ attribute_parser.feed(child.content)+ attribute_parser.close()+ except (AssertionError, ValueError):+ continue+ for event, tag, visually_hidden, alt, _line in attribute_parser.events:if event == "end":- hidden_html_depth = max(0, hidden_html_depth - 1)- elif tag not in _VOID_HTML_TAGS:- hidden_html_depth += 1+ if tag == "br":+ if not hidden_html_depth:+ append_text(" ")+ continue+ hidden_before = hidden_html_depth+ hidden_count = _close_html_element_stack(element_stack, tag)+ if hidden_count:+ hidden_html_depth = max(0, hidden_html_depth - hidden_count)+ if not hidden_before and tag in _HTML_TEXT_SEPARATOR_TAGS:+ append_text(" ")+ continue+ is_hidden = tag in _NON_RENDERED_HTML_TAGS or (suppress_visually_hidden and visually_hidden)+ if tag not in _VOID_HTML_TAGS:+ element_stack.append((tag, is_hidden))+ if is_hidden:+ if tag not in _VOID_HTML_TAGS:+ hidden_html_depth += 1+ elif not hidden_html_depth and (tag == "br" or tag in _HTML_TEXT_SEPARATOR_TAGS):+ append_text(" ")+ elif not hidden_html_depth and tag == "img" and alt is not None:+ append_text(f" {alt} ")elif hidden_html_depth:continue- elif child.type == "text":+ elif child.type in {"text", "text_special"}:append_text(child.content)elif child.type == "code_inline":append_text(child.content if include_code else " ")elif child.type == "image":- alt_parts: list[str] = []- for alt_child in child.children or []:- if alt_child.type in {"text", "text_special", "code_inline"}:- alt_parts.append(alt_child.content)- elif alt_child.type in {"softbreak", "hardbreak"}:- alt_parts.append(" ")- append_text("".join(alt_parts) if child.children is not None else unescape(child.content))+ alt_text = (+ " ".join(+ _inline_children_visible_lines(+ child.children,+ include_code=True,+ suppress_visually_hidden=suppress_visually_hidden,+ )+ )+ if child.children is not None+ else unescape(child.content)+ )+ append_text(f" {alt_text} ")elif child.type in {"softbreak", "hardbreak"}:lines.append("")return [" ".join(line.split()) for line in lines]@@ -736,10 +1373,9 @@ def _update_raw_html_stack(content: str, stack: list[str]) -> None:stack.pop()continueif event == "end":- # Python's generic HTMLParser does not implement browser tree-- # builder insertion modes. Trust only properly nested closures;- # a mismatched close must not expose evidence that a browser keeps- # inside an outer container.+ # Trust only properly nested closures. A separate safety check+ # rejects ambiguous markup rather than guessing HTML5 insertion+ # modes that differ across raw-text/select/table contexts.if stack and stack[-1] == tag:stack.pop()continue@@ -751,9 +1387,13 @@ def _update_raw_html_stack(content: str, stack: list[str]) -> None:@lru_cache(maxsize=256)-def _visible_html_lines(content: str) -> tuple[tuple[int, str], ...]:+def _visible_html_lines(+ content: str,+ *,+ suppress_visually_hidden: bool = True,+) -> tuple[tuple[int, str], ...]:"""Return line-relative text that a raw HTML block would visibly render."""- parser = _VisibleHTMLParser()+ parser = _VisibleHTMLParser(suppress_visually_hidden=suppress_visually_hidden)try:parser.feed(content)parser.close()@@ -821,6 +1461,7 @@ def _tier_status_rows(section_tokens: tuple[Token, ...], tier: int) -> list[tuplcell_parts: list[str] | None = Nonetier_column: int | None = Nonestatus_column: int | None = None+ header_is_canonical = Falsecell_has_unsafe_markup = Falsecell_safety: list[bool] | None = Noneraw_container_stack: list[str] = []@@ -835,6 +1476,7 @@ def _tier_status_rows(section_tokens: tuple[Token, ...], tier: int) -> list[tuplin_root_table = Truetier_column = Nonestatus_column = None+ header_is_canonical = Falsecontinueif token.type == "table_close" and token.level == 0:in_root_table = False@@ -883,19 +1525,33 @@ def _tier_status_rows(section_tokens: tuple[Token, ...], tier: int) -> list[tuplif in_header:normalized_headers = [" ".join(cell.split()).casefold() for cell in cells]- tier_indexes = [index for index, header in enumerate(normalized_headers) if header == "tier"]- status_indexes = [index for index, header in enumerate(normalized_headers) if header == "status"]+ tier_indexes = [+ index for index, header in enumerate(normalized_headers) if _visual_text_key(header) == "tier"+ ]+ status_indexes = [+ index for index, header in enumerate(normalized_headers) if _visual_text_key(header) == "status"+ ]if len(tier_indexes) == len(status_indexes) == 1:tier_column = tier_indexes[0]status_column = status_indexes[0]+ assert cell_safety is not None+ header_is_canonical = bool(+ cell_safety[tier_column]+ and cell_safety[status_column]+ and normalized_headers[tier_column] == "tier"+ and normalized_headers[status_column] == "status"+ )elif in_body and tier_column is not None and status_column is not None:if max(tier_column, status_column) < len(cells):tier_label = " ".join(cells[tier_column].split())- if re.fullmatch(rf"Tier\s*{tier}", tier_label, flags=re.IGNORECASE):+ if _visual_text_key(tier_label) == _visual_text_key(f"Tier {tier}"):assert cell_safety is not Nonestatus = (" ".join(cells[status_column].split()).upper()- if cell_safety[tier_column] and cell_safety[status_column]+ if header_is_canonical+ and cell_safety[tier_column]+ and cell_safety[status_column]+ and re.fullmatch(rf"Tier\s*{tier}", tier_label, flags=re.IGNORECASE)else "")rows.append((row_line, status))@@ -905,17 +1561,120 @@ def _tier_status_rows(section_tokens: tuple[Token, ...], tier: int) -> list[tuplreturn rows+def _non_ascii_tier_identifier_lines(section_tokens: tuple[Token, ...]) -> list[int]:+ """Return rows whose Tier Status header or tier label is not ASCII.++ Generated cards use fixed ASCII identifiers. Restricting only those+ structural cells prevents Unicode lookalikes outside the deliberately+ small identity-confusables table from creating a second visible table or+ result row while leaving the canonical proof intact.+ """+ lines: list[int] = []+ in_root_table = False+ in_header = False+ in_body = False+ row_line = 1+ cells: list[str] | None = None+ cell_parts: list[str] | None = None+ raw_container_stack: list[str] = []++ for token in section_tokens:+ if token.type == "html_block":+ _update_raw_html_stack(token.content, raw_container_stack)+ continue+ if raw_container_stack:+ continue+ if token.type == "table_open" and token.level == 0:+ in_root_table = True+ continue+ if token.type == "table_close" and token.level == 0:+ in_root_table = False+ in_header = False+ in_body = False+ continue+ if not in_root_table:+ continue+ if token.type == "thead_open":+ in_header = True+ continue+ if token.type == "thead_close":+ in_header = False+ continue+ if token.type == "tbody_open":+ in_body = True+ continue+ if token.type == "tbody_close":+ in_body = False+ continue+ if token.type == "tr_open":+ row_line = token.map[0] + 1 if token.map is not None else 1+ cells = []+ continue+ if token.type in {"th_open", "td_open"} and cells is not None:+ cell_parts = []+ continue+ if token.type == "inline" and cell_parts is not None:+ cell_parts.extend(_inline_visible_lines(token, include_code=True))+ continue+ if token.type in {"th_close", "td_close"} and cells is not None and cell_parts is not None:+ cells.append(" ".join(cell_parts).strip())+ cell_parts = None+ continue+ if token.type != "tr_close" or cells is None:+ continue+ identifiers = cells if in_header else cells[:1] if in_body else []+ if any(not identifier.isascii() for identifier in identifiers):+ lines.append(row_line)+ cells = None+ cell_parts = None+ return lines+++_DECISION_ALIAS_SENTINEL = "\x00"+++@lru_cache(maxsize=8)+def _decision_alias_pattern(canonical_text: str) -> re.Pattern[str]:+ """Match one decision phrase while failing closed on unmapped lookalikes."""+ canonical = publication_confusable_skeleton(_semantic_text(canonical_text))+ parts: list[str] = []+ for character in canonical:+ if character.isspace():+ parts.append(r"\s+")+ elif character.isascii() and character.isalnum():+ parts.append(f"(?:{re.escape(character)}|{re.escape(_DECISION_ALIAS_SENTINEL)})")+ else:+ parts.append(re.escape(character))+ return re.compile("".join(parts))+++def _has_decision_text_alias(value: str, canonical_text: str) -> bool:+ """Return whether visible text contains a canonical or confusable decision phrase.++ The shared publication skeleton is intentionally limited to the alphabet+ needed by reserved identity placeholders. Decision prose has a wider+ alphabet, so any non-ASCII character left unmapped by that skeleton is a+ one-character wildcard for an ASCII letter in the protected phrase. This+ is deliberately fail-closed and applies only to known decision phrases.+ """+ skeleton = publication_confusable_skeleton(_semantic_text(value))+ surface = "".join(+ " " if character.isspace() else character if character.isascii() else _DECISION_ALIAS_SENTINEL+ for character in skeleton+ )+ return _decision_alias_pattern(canonical_text).search(surface) is not None++def _has_publication_recommendation(text: str) -> bool:"""Return whether rendered content recommends publication."""- needle = "recommended for publication"for token in _markdown_tokens(text):if token.type == "inline":visible = " ".join(_inline_visible_lines(token, include_code=False))- if needle in _semantic_text(visible).casefold():+ if _has_decision_text_alias(visible, "recommended for publication"):return Trueelif token.type == "html_block":visible = " ".join(line for _offset, line in _visible_html_lines(token.content))- if needle in _semantic_text(visible).casefold():+ if _has_decision_text_alias(visible, "recommended for publication"):return Truereturn False@@ -940,6 +1699,29 @@ def _semantic_text(value: str) -> str:)+def _canonical_text_key(value: str) -> str:+ """Normalize layout and case without accepting lookalike characters."""+ return " ".join(value.split()).casefold()+++def _visual_text_key(value: str) -> str:+ """Return a confusable-aware key used only to reject visual aliases."""+ semantic = " ".join(_semantic_text(value).split())+ return publication_confusable_skeleton(semantic)+++def _contains_disallowed_category_c(value: str, *, allow_layout_whitespace: bool) -> bool:+ """Return whether text contains a disallowed control or line separator."""+ return any(+ (not allow_layout_whitespace or character not in {"\n", "\r", "\t"})+ and (+ unicodedata.category(character).startswith("C")+ or unicodedata.category(character) in {"Zl", "Zp"}+ )+ for character in value+ )++def _identity_present(value: str) -> bool:"""Return whether public identity text contains recorded alphanumeric provenance."""return publication_identity_present(value)@@ -959,13 +1741,22 @@ def _backticked_identity_present(value: str) -> bool:return match is not None and _identity_present(match.group("identity"))-def _check_verdict_tier_consistency(path: Path, text: str, offenders: list[Offender]) -> None:+def _check_verdict_tier_consistency(+ path: Path,+ text: str,+ offenders: list[Offender],+ *,+ require_source_provenance: bool = False,+) -> None:tier_rows: dict[int, tuple[int, str]] = {}+ tier_heading_lines = _section_heading_lines(text, "Tier Status")tier_sections = _section_occurrences(text, "Tier Status")- if len(tier_sections) > 1:- offenders.append(Offender(path, tier_sections[1][0], "duplicate Tier Status section"))+ if len(tier_heading_lines) > 1:+ offenders.append(Offender(path, tier_heading_lines[1], "duplicate Tier Status section"))elif tier_sections:section_tokens = tier_sections[0][1]+ for line_number in _non_ascii_tier_identifier_lines(section_tokens):+ offenders.append(Offender(path, line_number, "non-ASCII Tier Status identifier"))for tier in _TIER_COMPLETION_STATUSES:rows = _tier_status_rows(section_tokens, tier)if not rows:@@ -993,9 +1784,12 @@ def _check_verdict_tier_consistency(path: Path, text: str, offenders: list[Offenif verdict_status not in _OVERALL_VERDICT_STATUSES:offenders.append(Offender(path, verdict_line, "invalid Overall verdict field"))return+ recommendation_heading_lines = _section_heading_lines(text, "Publication Recommendation")recommendation_sections = _section_occurrences(text, "Publication Recommendation")- if len(recommendation_sections) > 1:- offenders.append(Offender(path, recommendation_sections[1][0], "duplicate Publication Recommendation section"))+ if len(recommendation_heading_lines) > 1:+ offenders.append(+ Offender(path, recommendation_heading_lines[1], "duplicate Publication Recommendation section")+ )if verdict_status != "PASS":if _has_publication_recommendation(text) or recommendation_sections:recommendation_line = recommendation_sections[0][0] if recommendation_sections else verdict_line@@ -1003,6 +1797,13 @@ def _check_verdict_tier_consistency(path: Path, text: str, offenders: list[Offenreturn_check_pass_source_identity(path, text, offenders)+ if require_source_provenance:+ # Independent of the Tier 3 row: a card publishing a PASS must name the+ # source it evaluated, including one skipped under an optional policy.+ # The canonical verdict detector above already honours unquoted+ # backfill verdicts and ignores the methodology bullet, so the+ # provenance contract shares it instead of keeping a second detector.+ _check_source_provenance(path, text, offenders)for tier, row in tier_rows.items():line_number, status = rowcomplete = status in _TIER_COMPLETION_STATUSES[tier]@@ -1040,7 +1841,7 @@ def _check_pass_provenance(path: Path, text: str, offenders: list[Offender]) ->"""Reject PASS cards that replace required provenance with legacy placeholders."""metadata_lines = _metadata_section_lines(text)fallback_line = metadata_lines[0][0] if metadata_lines else 1- for field, is_valid in _PASS_METADATA_FIELD_RULES:+ for field, pattern in _PASS_METADATA_FIELD_RULES:matches = _metadata_field_matches(metadata_lines, field)line_number = matches[0][0] if matches else fallback_linevalid_value = len(matches) == 1 and pattern.fullmatch(matches[0][1]) is not Nonediff --git a/src/skillevaluator/cli.py b/src/skillevaluator/cli.pyindex 5f80e5c1..0a98cb3c 100644--- a/src/skillevaluator/cli.py+++ b/src/skillevaluator/cli.py@@ -32,6 +32,7 @@ from skillevaluator.reporting.console_ui import (check_ticker_row,detail_row,engine_feed_rows,+ sanitize_tier3_console_text,stage_hint_row,summarize_tier1,summarize_tier2,@@ -57,6 +58,7 @@ from skillevaluator.tier1.commands import ()from skillevaluator.tier3_environments import HARBOR_ENVIRONMENTSfrom skillevaluator.tier_group import TierGroup+from skillevaluator.utils.path_security import resolve_repo_context_rootfrom skillevaluator.utils.rich_markup import escape_markup, strip_terminal_controlsfrom skillevaluator.utils.tier2_paths import (is_link_or_reparse,@@ -403,14 +405,43 @@ def _resolve_report_output_location(target_path: Path, output_dir: Path) -> Pathresolved_output,resolved_target,)- if not output_is_in_target:- return output_dir-from click.core import ParameterSourcecontext = click.get_current_context(silent=True)parameter_source = context.get_parameter_source("output_dir") if context is not None else None- if parameter_source is ParameterSource.DEFAULT:+ output_is_default = parameter_source is ParameterSource.DEFAULT+ catalog_root = context.meta.get("skillevaluator_catalog_report_root") if context is not None else None+ catalog_child_output = False+ if isinstance(catalog_root, Path) and not output_is_in_target:+ try:+ output_dir.absolute().relative_to(catalog_root.absolute())+ catalog_child_output = True+ except ValueError:+ if catalog_root.exists():+ catalog_child_output = _path_is_within(output_dir, catalog_root)+ if not output_is_in_target and (not output_is_default or catalog_child_output):+ return output_dir++ if not output_is_in_target:+ from skillevaluator.tier3.output_provenance import (+ is_generated_output_root,+ mark_generated_output_root,+ )++ try:+ output_is_real_directory = output_dir.is_dir() and not is_link_or_reparse(output_dir)+ output_is_empty = output_is_real_directory and next(output_dir.iterdir(), None) is None+ if (not output_dir.exists() and not is_link_or_reparse(output_dir)) or output_is_empty:+ mark_generated_output_root(output_dir)+ return output_dir+ if output_is_real_directory and is_generated_output_root(output_dir):+ return output_dir+ except (OSError, RuntimeError, ValueError) as exc:+ raise click.ClickException(+ f"Cannot safely reserve default report output directory: {output_dir}"+ ) from exc++ if output_is_default:relocated = target_path.with_name(f"{target_path.name}-reports")try:if not _path_is_within(relocated, resolved_target):@@ -425,6 +456,96 @@ def _resolve_report_output_location(target_path: Path, output_dir: Path) -> Path)+def _resolve_file_report_output_location(+ target_path: Path,+ output_dir: Path,+ report_formats: tuple[str, ...],+) -> Path:+ """Resolve and reserve report storage only when a file reporter needs it."""+ if not any(report_format in _FILE_REPORT_EXTENSIONS for report_format in report_formats):+ return output_dir+ return _resolve_report_output_location(target_path, output_dir)+++def _reject_copy_repo_root_output(+ target_path: Path,+ output_dir: Path,+ *,+ copy_repo: bool,+ agent_eval: bool,+ include_skills: tuple[Path, ...] = (),+) -> None:+ """Reject or reserve report storage inside any Tier 3 repo context."""+ if not agent_eval:+ return+ mode_label = "--copy-repo" if copy_repo else "Tier 3 linked-context staging"+ try:+ context_roots = [(resolve_repo_context_root(target_path), "repository root")]+ context_roots.extend(+ (included_skill.resolve(strict=True), "runtime source root")+ for included_skill in include_skills+ )+ except (OSError, RuntimeError, ValueError) as exc:+ raise click.ClickException(f"Cannot validate {mode_label} report output directory: {output_dir}") from exc+ overlaps_context = False+ seen_roots: set[Path] = set()+ for context_root, root_label in context_roots:+ if context_root in seen_roots:+ continue+ seen_roots.add(context_root)+ try:+ output_is_context_root = paths_refer_to_same_location(output_dir, context_root)+ output_is_in_context = _path_is_within(output_dir, context_root)+ except (OSError, RuntimeError, ValueError) as exc:+ raise click.ClickException(f"Cannot validate {mode_label} report output directory: {output_dir}") from exc+ if output_is_context_root:+ raise click.UsageError(+ f"With {mode_label}, report output cannot be the {root_label}; "+ f"choose a dedicated path such as ./reports instead of: {output_dir}"+ )+ overlaps_context = overlaps_context or output_is_in_context+ if not overlaps_context:+ return++ # Tier 3 staging excludes this whole directory so prior reports cannot+ # influence the agent. Linked-context staging can follow authored files+ # anywhere in the repository, so it needs the same ownership check as a+ # full-repository copy before omitting a subtree wholesale.+ from skillevaluator.tier3.output_provenance import mark_generated_output_root++ try:+ mark_generated_output_root(output_dir)+ except (OSError, RuntimeError, ValueError) as exc:+ raise click.UsageError(+ f"With {mode_label}, an in-repository report output must be a dedicated "+ "SkillEvaluator generated-output directory; choose a new or authenticated "+ f"report directory instead of: {output_dir}"+ ) from exc+++_validate_json_report_var: ContextVar[str | None] = ContextVar(+ "_validate_json_report_var",+ default=None,+)+++def _effective_report_formats(report_formats: tuple[str, ...], *, quiet: bool) -> tuple[str, ...]:+ """Resolve the report formats ``validate`` will actually emit."""+ if quiet and not _report_formats_explicit():+ return tuple(dict.fromkeys([fmt for fmt in report_formats if fmt != "cli"] + ["html", "json"]))+ return report_formats+++def _record_validate_json_report(report_name: str | None) -> None:+ _validate_json_report_var.set(report_name)+++def _consume_validate_json_report() -> str | None:+ report_name = _validate_json_report_var.get()+ _validate_json_report_var.set(None)+ return report_name++def _report_formats_explicit() -> bool:"""True when the user passed ``-r``/``--report`` on the command line.@@ -655,6 +776,7 @@ def _run_agent_eval_or_skip(block_on_agent_eval: bool = False,validate_source: bool = True,repo_context_exclude_paths: tuple[Path, ...] = (),+ evaluated_source: dict[str, str] | None = None,progress_reporter=None,) -> ValidationResult:"""Run Tier 3 live agent evaluation and fold the result into the combined report.@@ -664,6 +786,11 @@ def _run_agent_eval_or_skip(describing why Tier 3 could not run. Tier 3 remains advisory by default,and callers can opt into blocking behavior."""+ from skillevaluator.publication_identity import publication_target_name++ # Persist the entry name that publication targets record, not a lexical+ # alias that a case- or normalization-insensitive filesystem accepted.+ skill_name = publication_target_name(target_path) or target_path.nameif validate_source:from skillevaluator.evaluation.tier3_report import dataset_required_resultfrom skillevaluator.tier3.evals_spec import validate_tier3_source@@ -675,7 +802,7 @@ def _run_agent_eval_or_skip(target_path / "evals" / "evals.json",source_errors,blocking=block_on_agent_eval,- skill_name=target_path.name,+ skill_name=skill_name,source_kind=source_kind,)@@ -704,6 +831,8 @@ def _run_agent_eval_or_skip(copy_repo=copy_repo,timeout_multiplier=timeout_multiplier,harbor_keep_jobs=harbor_keep_jobs,+ agent_runtime_preflight=agent_runtime_preflight,+ evaluated_source=evaluated_source,repo_context_exclude_paths=repo_context_exclude_paths,)try:@@ -718,7 +847,7 @@ def _run_agent_eval_or_skip(# decides whether this failure is advisory or blocking.return advisory_skip_result(f"Tier 3 live evaluation skipped: {exc}",- skill_name=target_path.name,+ skill_name=skill_name,)if failure := service.failure_reason(engine_result):@@ -733,7 +862,7 @@ def _run_agent_eval_or_skip(return partialreturn advisory_skip_result(f"Tier 3 live evaluation did not complete: {failure}",- skill_name=target_path.name,+ skill_name=skill_name,)try:@@ -746,12 +875,12 @@ def _run_agent_eval_or_skip(except Exception as exc:return advisory_skip_result(f"Tier 3 result normalization failed: {exc}",- skill_name=target_path.name,+ skill_name=skill_name,)if result is None:return advisory_skip_result("Tier 3 live evaluation produced no parseable results.",- skill_name=target_path.name,+ skill_name=skill_name,)return result@@ -1160,26 +1289,44 @@ def _validate_catalog(meta_key = "skillevaluator_catalog_report_root"previous_catalog_root = ctx.meta.get(meta_key)ctx.meta[meta_key] = output_dir+ skill_reports: dict[str, str | None] = {}try:for index, skill_dir in enumerate(skill_dirs, start=1):_print_catalog_divider(index, len(skill_dirs), skill_dir.name)+ skill_output = output_dir / skill_dir.nameoverrides = {**ctx.params,"target_path": skill_dir,"content_type": "skill",- "output_dir": output_dir / skill_dir.name,+ "output_dir": skill_output,}+ reason = ""try:ctx.invoke(validate, **overrides)except click.ClickException as exc:- failures.append((skill_dir.name, str(getattr(exc, "message", exc))))+ reason = str(getattr(exc, "message", exc))+ failures.append((skill_dir.name, reason))except Exception as exc: # unexpected: keep the catalog running, report it on the scoreboard- failures.append((skill_dir.name, f"unexpected error: {exc}"))+ reason = f"unexpected error: {exc}"+ failures.append((skill_dir.name, reason))+ skill_reports[skill_dir.name] = _consume_validate_json_report()finally:if previous_catalog_root is None:ctx.meta.pop(meta_key, None)else:ctx.meta[meta_key] = previous_catalog_root+ failure_map = dict(failures)+ skill_entries = [+ _catalog_skill_entry(+ skill_dir.name,+ output_dir / skill_dir.name,+ passed=skill_dir.name not in failure_map,+ reason=failure_map.get(skill_dir.name, ""),+ json_report_name=skill_reports.get(skill_dir.name),+ )+ for skill_dir in skill_dirs+ ]+ _write_catalog_summary(output_dir, skill_entries)_print_catalog_summary(len(skill_dirs), failures, output_dir)if failures:raise click.ClickException(@@ -1744,6 +1891,12 @@ def validate(if dedup:_reject_linked_tier2_root(target_path)target_path = target_path.resolve()+ from skillevaluator.publication_identity import publication_target_name++ # A case- or normalization-insensitive filesystem lets an alias such as+ # ``SIMPLE`` open the entry recorded as ``simple``. Every tier stamps the+ # recorded spelling, so reports must expect it instead of the alias.+ publication_name = publication_target_name(target_path) or target_path.nameevaluated_source = _evaluated_source_from_options(evaluated_source_repository,evaluated_source_revision,@@ -1801,16 +1954,33 @@ def validate(from skillevaluator.constants import CONTENT_TYPE_UNKNOWN- output_dir = _resolve_report_output_location(target_path, output_dir)-- # A directory of skills (no root SKILL.md) is a catalog: run the pipeline- # once per skill, each as its own job with its own reports.- if (+ is_catalog = (resolved_type in (CONTENT_TYPE_SKILL, CONTENT_TYPE_UNKNOWN)and target_path.is_dir()and not (target_path / "SKILL.md").exists()and any(target_path.glob("*/SKILL.md"))- ):+ )+ # Quiet (default) swaps the implicit CLI reporter for HTML+JSON, while an+ # explicit -r cli is a no-file contract. Skills and catalogs additionally+ # require storage for their compulsory BENCHMARK.md output.+ quiet = not verbose and not logging.getLogger().isEnabledFor(logging.DEBUG)+ file_report_required = any(report_format in _FILE_REPORT_EXTENSIONS for report_format in report_formats) or (+ quiet and not _report_formats_explicit()+ )+ report_output_required = resolved_type == CONTENT_TYPE_SKILL or is_catalog or file_report_required+ if report_output_required:+ output_dir = _resolve_report_output_location(target_path, output_dir)+ _reject_copy_repo_root_output(+ target_path,+ output_dir,+ copy_repo=copy_repo,+ agent_eval=agent_eval,+ include_skills=include_skills,+ )++ # A directory of skills (no root SKILL.md) is a catalog: run the pipeline+ # once per skill, each as its own job with its own reports.+ if is_catalog:_validate_catalog(click.get_current_context(),resolved_target=target_path,@@ -1821,7 +1991,6 @@ def validate(# Quiet (default) drives the compact pipeline view; --verbose keeps the# historical full-detail stream, as does DEBUG logging via the group -v.- quiet = not verbose and not logging.getLogger().isEnabledFor(logging.DEBUG)run_tier3 = agent_evalplanned_tiers = [(1, "Static & Security", "static & security")]tier2_index = tier3_index = None@@ -1853,15 +2022,25 @@ def validate(# for the later Tier 3 skip result and continue through Tier 1/2.autopilot_error: str | None = Noneautopilot_dataset_note: str | None = None+ view.start()if autopilot:+ # Generation now precedes Tier 1, so surface it on the first live block+ # instead of leaving the pipeline view blank while the dataset is prepared.+ view.tier_start(0)+ view.tier_progress(0, [stage_hint_row("status", "preparing evaluation dataset…")])try:- autopilot_dataset_note = _ensure_autopilot_dataset(target_path, quiet=quiet)+ autopilot_dataset_note = _ensure_autopilot_dataset(tier3_path, quiet=quiet)except (Exception, SystemExit) as exc:- autopilot_error = f"autopilot dataset generation failed: {getattr(exc, 'message', exc)}"+ try:+ error_detail = sanitize_tier3_console_text(str(exc), limit=72)+ except Exception:+ error_detail = type(exc).__name__+ autopilot_error = sanitize_tier3_console_text(+ f"autopilot dataset generation failed: {error_detail or type(exc).__name__}"+ )if not quiet:click.echo(f"Warning: {autopilot_error}", err=True)- view.start()view.tier_start(0)check_lineup = enabled_check_lineup(checks)checks_done: list[str] = []@@ -1960,7 +2139,7 @@ def validate(view.tier_progress(tier3_index, [*tier3_config_rows, *engine_feed_rows(lines)])reporter = ViewProgressReporter(_on_engine_tail) if quiet else None- repo_context_exclude_paths = [output_dir]+ repo_context_exclude_paths = [output_dir] if report_output_required else []catalog_report_root = click.get_current_context().meta.get("skillevaluator_catalog_report_root")if isinstance(catalog_report_root, Path) and not paths_refer_to_same_location(catalog_report_root,@@ -1996,10 +2175,14 @@ def validate(results.append(tier3_result)tier3_ran, tier3_ok, tier3_rows, tier3_skip = summarize_tier3(tier3_result)if autopilot_error and not tier3_ran:- tier3_skip = f"{autopilot_error}; {tier3_skip}"+ from skillevaluator.reporting.base import get_skip_reason++ tier3_result.metadata["skip_reason"] = f"{autopilot_error}; {tier3_skip}"+ report_skip_reason = get_skip_reason(tier3_result)# Reports read the skip reason from metadata, so the generation# failure must land there too, not only in the view's skip row.- tier3_result.metadata["skip_reason"] = tier3_skip+ tier3_result.metadata["skip_reason"] = report_skip_reason+ tier3_skip = sanitize_tier3_console_text(report_skip_reason)if tier3_ran:view.tier_done(tier3_index, failed=not tier3_ok, rows=[*tier3_config_rows[3:], *tier3_rows])else:@@ -2061,7 +2244,7 @@ def validate(basename=report_basename_value,policy=policy,target_path=target_display,- expected_skill_name=target_path.name,+ expected_skill_name=publication_name,content_label=content_label,announce_paths=not quiet,sarif_scan_root=target_path,@@ -2083,7 +2266,7 @@ def validate(# stays as the last line of defence: the renderer re-validates the# carriers it is handed, and a producer can record one after the fact.try:- BenchmarkReporter(skill_name=target_path.name).save(results, output_dir / BENCHMARK_FILENAME)+ BenchmarkReporter(skill_name=publication_name).save(results, output_dir / BENCHMARK_FILENAME)except EvaluatedSourceConflict as exc:# Publication fails closed on a contradictory identity, so report which# values disagreed rather than letting the card write a guess.@@ -2132,7 +2315,7 @@ validate.help_group_descriptions = {@_report_optionsdef quality_check(target_path: Path, min_score: int, report_formats: tuple[str, ...], output_dir: Path) -> None:"""Score skill quality across correctness, discoverability, reliability, and efficiency."""- output_dir = _resolve_report_output_location(target_path.resolve(), output_dir)+ output_dir = _resolve_file_report_output_location(target_path.resolve(), output_dir, report_formats)if not emit_reports(run_quality_check(target_path, min_score=min_score),report_formats=report_formats,@@ -2148,7 +2331,7 @@ def quality_check(target_path: Path, min_score: int, report_formats: tuple[str,@_report_optionsdef rubric_eval(target_path: Path, min_score: int, report_formats: tuple[str, ...], output_dir: Path) -> None:"""Run LLM-as-judge rubric evaluation for a skill."""- output_dir = _resolve_report_output_location(target_path.resolve(), output_dir)+ output_dir = _resolve_file_report_output_location(target_path.resolve(), output_dir, report_formats)if not emit_reports(run_rubric_eval(target_path, min_score=min_score),report_formats=report_formats,@@ -2167,7 +2350,7 @@ def security_scan(target_path: Path, llm: bool, llm_verify: bool, report_formats: tuple[str, ...], output_dir: Path) -> None:"""Scan for security vulnerabilities."""- output_dir = _resolve_report_output_location(target_path.resolve(), output_dir)+ output_dir = _resolve_file_report_output_location(target_path.resolve(), output_dir, report_formats)if not emit_reports(run_security_scan(target_path, use_llm=llm, llm_verify=llm_verify),report_formats=report_formats,@@ -2183,7 +2366,7 @@ def security_scan(@_report_optionsdef pii_scan(target_path: Path, llm_verify: bool, report_formats: tuple[str, ...], output_dir: Path) -> None:"""Scan for PII and local identifiers."""- output_dir = _resolve_report_output_location(target_path.resolve(), output_dir)+ output_dir = _resolve_file_report_output_location(target_path.resolve(), output_dir, report_formats)if not emit_reports(run_pii_scan(target_path, llm_verify=llm_verify),report_formats=report_formats,@@ -2198,7 +2381,7 @@ def pii_scan(target_path: Path, llm_verify: bool, report_formats: tuple[str, ...@_report_optionsdef lint_scripts(target_path: Path, report_formats: tuple[str, ...], output_dir: Path) -> None:"""Run advisory lint checks on skill scripts."""- output_dir = _resolve_report_output_location(target_path.resolve(), output_dir)+ output_dir = _resolve_file_report_output_location(target_path.resolve(), output_dir, report_formats)if not emit_reports(run_lint_scripts(target_path),report_formats=report_formats,@@ -2271,7 +2454,7 @@ def similarity_check(raise click.UsageError("--catalog and --save-catalog cannot be used together")_reject_linked_tier2_root(content_path)- output_dir = _resolve_report_output_location(content_path.resolve(), output_dir)+ output_dir = _resolve_file_report_output_location(content_path.resolve(), output_dir, report_formats)similarity_basename = report_basename("similarity")_reject_catalog_report_collisions(resolved_catalog,@@ -2326,7 +2509,7 @@ def context_optimization_check(from skillevaluator.tier2.commands import run_context_optimization_check_reject_linked_tier2_root(skill_path)- output_dir = _resolve_report_output_location(skill_path.resolve(), output_dir)+ output_dir = _resolve_file_report_output_location(skill_path.resolve(), output_dir, report_formats)results = run_context_optimization_check(skill_path, threshold=threshold, model=model, llm_model=llm_model)sanitize_tier2_results(results, skill_path)if not emit_reports(@@ -2356,7 +2539,7 @@ def dedup_scan(from skillevaluator.tier2.commands import run_dedup_scan_reject_linked_tier2_root(skill_path)- output_dir = _resolve_report_output_location(skill_path.resolve(), output_dir)+ output_dir = _resolve_file_report_output_location(skill_path.resolve(), output_dir, report_formats)results = run_dedup_scan(skill_path,threshold=threshold,@@ -2418,6 +2601,8 @@ def _tier1_workflow(profile=policy,previous_version=previous_version,)+ # Resolved after the run so configuration errors still leave no output.+ output_dir = _resolve_file_report_output_location(skill_path.resolve(), output_dir, report_formats)if not emit_reports(results,report_formats=report_formats,@@ -2478,10 +2663,20 @@ def _tier2_workflow(full_body=full_body,)sanitize_tier2_results(results, skill_path, catalog)+ # Resolved after the run so configuration errors still leave no output; a+ # relocated directory gets the same catalog-collision check before writing.+ resolved_output_dir = _resolve_file_report_output_location(skill_path.resolve(), output_dir, report_formats)+ if resolved_output_dir != output_dir:+ _reject_catalog_report_collisions(+ catalog,+ report_formats=report_formats,+ output_dir=resolved_output_dir,+ basename=basename,+ )if not emit_reports(results,report_formats=report_formats,- output_dir=output_dir,+ output_dir=resolved_output_dir,basename=basename,target_path=str(skill_path),):diff --git a/src/skillevaluator/evaluation/options.py b/src/skillevaluator/evaluation/options.pyindex 120ab002..a8861223 100644--- a/src/skillevaluator/evaluation/options.py+++ b/src/skillevaluator/evaluation/options.py@@ -47,6 +47,10 @@ class EvaluationOptions:override_memory_mb: int | None = Noneoverride_storage_mb: int | None = Nonerepo_context_exclude_paths: tuple[Path, ...] = ()+ environment_kwarg: tuple[str, ...] = ()+ # Supplied by the orchestration input, never inferred from repository state:+ # the tree that runs the evaluator is not the tree being evaluated.+ evaluated_source: dict[str, str] | None = Nonedef engine_kwargs(self) -> dict[str, Any]:"""Return keyword arguments (excluding ``skill_path``) for the engine."""diff --git a/src/skillevaluator/evaluation/tier3_report.py b/src/skillevaluator/evaluation/tier3_report.pyindex 16e0158c..feb3b64a 100644--- a/src/skillevaluator/evaluation/tier3_report.py+++ b/src/skillevaluator/evaluation/tier3_report.py@@ -50,6 +50,12 @@ VERDICT_NEUTRAL = "neutral"_AGENT_EVAL_VALIDATOR = "AGENT_EVAL"_AGENT_EVAL_DESCRIPTION = "Tier 3: Live Agent Evaluation (Harbor)"_PUBLICATION_TARGET_CONFLICT_MARKER = "source changed during evaluation"+_RUNTIME_CONTEXT_CONFLICT_REASON_CODE = "runtime_context_outside_publication_target"+_RUNTIME_CONTEXT_CONFLICT_MARKER = "runtime context is not bound to publication target"+_PUBLICATION_TARGET_CONFLICT_MARKERS = (+ _PUBLICATION_TARGET_CONFLICT_MARKER,+ _RUNTIME_CONTEXT_CONFLICT_MARKER,+)_DIMENSION_IDS = list(DIMENSION_MAPPING.keys())@@ -486,6 +492,7 @@ def agent_eval_result_from_directory(run_id=run_truth.get("run_id"),publication_target=publication_target,publication_target_conflict=run_truth.get("publication_target_conflict"),+ evaluated_source=evaluated_source,use_llm_judge=use_llm_judge,)return _validation_result_from_payload(payload)@@ -559,11 +566,15 @@ def render_agent_eval_html_report(}target = output_path.expanduser().resolve() if output_path is not None else run_dir / "report.html"+ from skillevaluator.publication_identity import publication_target_name+reporter = HTMLReporter(target_path=str(skill_path),content_label="Skill",tabs=[{"id": "tier3", "label": "Tier 3: Live Agent Evaluation"}],- expected_skill_name=skill_path.name,+ # The run records the filesystem entry name, which a lexical alias+ # on a case- or normalization-insensitive filesystem need not match.+ expected_skill_name=publication_target_name(skill_path) or skill_path.name,)reporter.save([result], target)return target@@ -590,6 +601,7 @@ def build_agent_eval_payload(run_id: str | None = None,publication_target: dict[str, str] | None = None,publication_target_conflict: str | None = None,+ evaluated_source: dict[str, Any] | None = None,use_llm_judge: bool = True,) -> dict[str, Any] | None:"""Assemble the canonical Tier 3 ``agent_eval`` payload from loaded agent data.@@ -704,6 +716,7 @@ def build_agent_eval_payload("dataset_digest_algorithm": effective_dataset_digest_algorithm,"run_id": run_id,"publication_target": dict(publication_target) if isinstance(publication_target, dict) else None,+ "evaluated_source": effective_evaluated_source,"verdict_policy": verdict_policy,"execution_status": execution_status,"execution_errors": execution_errors,@@ -713,8 +726,8 @@ def build_agent_eval_payload(),"scored_attempts": sum(_as_nonnegative_int(agent.get("scored_attempts")) for agent in agent_payloads.values()),}- if publication_target_conflict == _PUBLICATION_TARGET_CONFLICT_MARKER:- summary["publication_target_conflict"] = _PUBLICATION_TARGET_CONFLICT_MARKER+ if publication_target_conflict in _PUBLICATION_TARGET_CONFLICT_MARKERS:+ summary["publication_target_conflict"] = publication_target_conflictif harbor_summary:summary["harbor_viewer"] = {key: harbor_summary[key] for key in ("job_url", "analysis_url") if harbor_summary.get(key)@@ -769,6 +782,7 @@ def build_agent_eval_payload("dataset_digest_algorithm": effective_dataset_digest_algorithm,"run_id": run_id,"publication_target": dict(publication_target) if isinstance(publication_target, dict) else None,+ "evaluated_source": effective_evaluated_source,"verdict_policy": verdict_policy,"agents": agent_payloads,"dimensions": best_dimensions,@@ -797,8 +811,8 @@ def build_agent_eval_payload(detail_priority=detail_priority,),}- if publication_target_conflict == _PUBLICATION_TARGET_CONFLICT_MARKER:- payload["publication_target_conflict"] = _PUBLICATION_TARGET_CONFLICT_MARKER+ if publication_target_conflict in _PUBLICATION_TARGET_CONFLICT_MARKERS:+ payload["publication_target_conflict"] = publication_target_conflictif harbor_summary:payload["harbor_viewer"] = harbor_summary@@ -970,6 +984,58 @@ def _bounded_raw_metric_mapping(value: dict[Any, Any], report_budget: _ReportBudreturn bounded+def _compact_agent_conditions(agent: dict[str, Any]) -> bool:+ """Bound condition diagnostics while preserving publication truth fields."""+ conditions = agent.get("conditions")+ if not isinstance(conditions, dict):+ return False++ def bounded_count(condition: dict[str, Any], key: str) -> int:+ value = condition.get(key)+ return (+ value+ if isinstance(value, int) and not isinstance(value, bool) and 0 <= value <= 2**63 - 1+ else 0+ )++ compact: dict[str, dict[str, Any]] = {}+ canonical_names = {"with_skill", "without_skill"}+ for condition_name in ("with_skill", "without_skill"):+ condition = conditions.get(condition_name)+ if not isinstance(condition, dict):+ continue+ raw_errors = condition.get("execution_errors")+ if isinstance(raw_errors, list) and not raw_errors:+ bounded_errors: list[str] | None = []+ elif isinstance(raw_errors, list):+ bounded_errors = [+ error[:1024] if isinstance(error, str) else "Malformed condition execution error"+ for error in raw_errors[:16]+ ] or ["Condition execution errors were omitted"]+ else:+ bounded_errors = None+ raw_status = condition.get("execution_status")+ compact[condition_name] = {+ "execution_status": raw_status if isinstance(raw_status, str) and len(raw_status) <= 16 else None,+ "execution_errors": bounded_errors,+ "expected_attempts": bounded_count(condition, "expected_attempts"),+ "scored_attempts": bounded_count(condition, "scored_attempts"),+ }+ if set(conditions) - canonical_names:+ # Preserve invalidity without retaining attacker-controlled keys or+ # values. Publication validation requires exactly the two canonical+ # condition names, so compaction must never repair malformed evidence.+ compact["invalid_condition_shape"] = {+ "execution_status": None,+ "execution_errors": None,+ "expected_attempts": 0,+ "scored_attempts": 0,+ }+ changed = compact != conditions+ agent["conditions"] = compact+ return changed++def _prune_non_best_agent_details(payload: dict[str, Any], report_budget: _ReportBudget) -> None:"""Drop duplicated lower-priority details before touching best-agent evidence."""best_agent = str(payload.get("best_agent") or "")@@ -988,9 +1054,8 @@ def _prune_non_best_agent_details(payload: dict[str, Any], report_budget: _Reporif isinstance(items, list) and items:omitted += len(items)agent[key] = []- if agent.get("conditions"):+ if _compact_agent_conditions(agent):omitted += 1- agent["conditions"] = {}if isinstance(raw_rewards, dict):items = raw_rewards.get(name)if isinstance(items, list) and items:@@ -1088,8 +1153,7 @@ def _enforce_report_payload_budget(payload: dict[str, Any], report_budget: _Repoif isinstance(items, list) and items:omitted_items += len(items)agent[key] = []- if agent.get("conditions"):- agent["conditions"] = {}+ if _compact_agent_conditions(agent):omitted_items += 1report_budget.omit("dataset_and_trial_items", omitted_items)refresh_signal()@@ -2820,7 +2884,14 @@ def _run_truth_metadata(if isinstance(run_id, str) and run_id == run_dir.name:truth["run_id"] = run_idif "publication_target_conflict" in identity_source:- truth["publication_target_conflict"] = _PUBLICATION_TARGET_CONFLICT_MARKER+ conflict = identity_source.get("publication_target_conflict")+ marker = (+ _RUNTIME_CONTEXT_CONFLICT_MARKER+ if isinstance(conflict, dict)+ and conflict.get("reason_code") == _RUNTIME_CONTEXT_CONFLICT_REASON_CODE+ else _PUBLICATION_TARGET_CONFLICT_MARKER+ )+ truth["publication_target_conflict"] = markerelif isinstance(publication_target, dict):truth["publication_target"] = dict(publication_target)return truthdiff --git a/src/skillevaluator/evidence.py b/src/skillevaluator/evidence.pyindex 526f6618..b7c62a7d 100644--- a/src/skillevaluator/evidence.py+++ b/src/skillevaluator/evidence.py@@ -12,6 +12,7 @@ from typing import Anydef evidence_ref_identity(ref: Mapping[str, Any]) -> str:"""Return the most specific stable location carried by an evidence ref."""for key in ("evidence_id", "json_pointer", "path"):- if value := str(ref.get(key) or "").strip():- return value+ value = ref.get(key)+ if isinstance(value, str) and (normalized := value.strip()):+ return normalizedreturn ""diff --git a/src/skillevaluator/publication_evidence.py b/src/skillevaluator/publication_evidence.pyindex f8faab6f..8c3f6e99 100644--- a/src/skillevaluator/publication_evidence.py+++ b/src/skillevaluator/publication_evidence.py@@ -40,6 +40,15 @@ _RECOGNIZED_CHECKS_BY_TIER = {}_PRODUCER_BY_TIER = {tier: f"skillevaluator.tier{tier}" for tier in _RECOGNIZED_CHECKS_BY_TIER}+# Tier 1 checks a default run executes for every content type, and the checks+# it adds for skills. ``--checks`` may narrow a run, but publication requires the+# whole applicable lineup, which built-in Tier 1 producers record on each result.+TIER1_PUBLICATION_CORE_CHECKS = frozenset({"schema", "security", "pii", "license", "code-integrity", "unicode"})+TIER1_PUBLICATION_SKILL_CHECKS = frozenset({"version", "quality", "lint"})+TIER1_REQUIRED_CHECKS_KEY = "tier1_required_checks"+# Certified source paths below the target root that Tier 1 skipped by name.+TIER1_UNSCANNED_PATHS_KEY = "tier1_unscanned_paths"+@dataclass(frozen=True)class PublicationEvidenceIdentity:@@ -123,13 +132,50 @@ def stamp_publication_evidence(result.metadata["publication_evidence"] = dict(marker)+def tier1_required_checks(*, skill_like: bool) -> list[str]:+ """Return the Tier 1 checks publication requires for one content type."""+ required = TIER1_PUBLICATION_CORE_CHECKS | (TIER1_PUBLICATION_SKILL_CHECKS if skill_like else frozenset())+ return sorted(required)+++def declared_tier1_required_checks(value: object) -> frozenset[str]:+ """Parse a recorded Tier 1 lineup, failing closed to the full skill lineup.++ A declaration can omit only the skill-only checks, so a malformed or+ narrowed claim can never waive a core check.+ """+ full = TIER1_PUBLICATION_CORE_CHECKS | TIER1_PUBLICATION_SKILL_CHECKS+ if not isinstance(value, list) or any(not isinstance(item, str) for item in value):+ return full+ declared = frozenset(value)+ if len(declared) != len(value) or not declared >= TIER1_PUBLICATION_CORE_CHECKS or not declared <= full:+ return full+ return declared+++def stamp_tier1_required_checks(results: Iterable[ValidationResult], *, skill_like: bool) -> None:+ """Record the applicable Tier 1 lineup on results from a built-in Tier 1 run."""+ required = tier1_required_checks(skill_like=skill_like)+ for result in results:+ if not isinstance(result.metadata, dict):+ result.metadata = {}+ result.metadata[TIER1_REQUIRED_CHECKS_KEY] = list(required)++__all__ = ["PUBLICATION_EVIDENCE_SCHEMA_VERSION",+ "TIER1_PUBLICATION_CORE_CHECKS",+ "TIER1_PUBLICATION_SKILL_CHECKS",+ "TIER1_REQUIRED_CHECKS_KEY",+ "TIER1_UNSCANNED_PATHS_KEY","PublicationEvidenceIdentity",+ "declared_tier1_required_checks","publication_evidence_dict","publication_evidence_identity","result_has_publication_evidence","result_publication_evidence","result_publication_evidence_dict","stamp_publication_evidence",+ "stamp_tier1_required_checks",+ "tier1_required_checks",]diff --git a/src/skillevaluator/publication_identity.py b/src/skillevaluator/publication_identity.pyindex c7679cb5..cd090bc4 100644--- a/src/skillevaluator/publication_identity.py+++ b/src/skillevaluator/publication_identity.py@@ -19,12 +19,12 @@ import hashlibimport osimport statimport unicodedata-from collections.abc import Iterable+from collections.abc import Collection, Iterablefrom dataclasses import dataclassfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any-from skillevaluator.utils.path_security import canonicalize_trusted_root_alias+from skillevaluator.utils.path_security import canonicalize_trusted_root_alias, matches_filesystem_nameif TYPE_CHECKING:from skillevaluator.models.result import ValidationResult@@ -37,6 +37,8 @@ PUBLICATION_TARGET_DIGEST_ALGORITHM = "skill-evaluator-source-tree/2"# Authored Tier 3 inputs under ``evals/`` are deliberately included; only the# generated ``evals/results/`` subtree is omitted._PUBLICATION_EXCLUDED_DIR_NAMES = frozenset({".git", ".venv", "__pycache__", "node_modules"})+# Public alias for staging layers that must recognize these any-depth names.+PUBLICATION_ANY_DEPTH_EXCLUDED_NAMES = _PUBLICATION_EXCLUDED_DIR_NAMES_PUBLICATION_EXCLUDED_ROOT_DIRS = frozenset({".evals", ".results", ".versions", "results", "versions"})_PUBLICATION_EXCLUDED_DIR_PATHS = frozenset({("evals", "results")})_PUBLICATION_EXCLUDED_ROOT_FILES = frozenset({"BENCHMARK.md", "skill-card.md", "skill.oms.sig"})@@ -180,6 +182,29 @@ def publication_source_entry_is_excluded(source: Path, candidate: Path) -> bool:return False+def publication_source_link_is_generated(source: Path, candidate: Path) -> bool:+ """Return whether a link entry uses a name that v2 excludes at its position.++ The digest refuses trees that contain links, but runtime projections still+ skip a linked ``.git``, ``results`` or similar generated entry instead of+ failing on it, because it never holds author-owned skill content.+ """+ try:+ root = _absolute_lexical(source.expanduser())+ path = _absolute_lexical(candidate.expanduser())+ parts = path.relative_to(root).parts+ if not parts or not _is_link(path.lstat()):+ return False+ except (OSError, RuntimeError, ValueError):+ return False+ name = parts[-1]+ return bool(+ name in _PUBLICATION_EXCLUDED_DIR_NAMES+ or (len(parts) == 1 and (name in _PUBLICATION_EXCLUDED_ROOT_DIRS or name in _PUBLICATION_EXCLUDED_ROOT_FILES))+ or parts in _PUBLICATION_EXCLUDED_DIR_PATHS+ )++def publication_source_path_is_excluded(source: Path, candidate: Path) -> bool:"""Return whether a path is at or below an entry excluded by v2."""try:@@ -193,6 +218,57 @@ def publication_source_path_is_excluded(source: Path, candidate: Path) -> bool:)+def publication_paths_skipped_by_scan(+ source: Path,+ excluded_dirs: Collection[str],+ excluded_files: Collection[str],+ *,+ limit: int = 20,+) -> list[str]:+ """Return digest-covered paths that a name-based producer scan skips.++ Tier 1 and Tier 2 skip generated-artifact names (``results``, ``versions``,+ ``evals``, ``BENCHMARK.md``, ...) at any depth, while the v2 digest and the+ Tier 3 projection exclude most of them only at the target root. A deeper+ entry with such a name is therefore certified and agent-visible but never+ scanned. The root ``evals/`` directory holds Tier 3 inputs and is outside+ the producer scans by design, so it is not reported.+ """+ root = _absolute_lexical(source.expanduser())+ try:+ if _is_link(root.lstat()) or not root.is_dir():+ return []+ except OSError:+ return []+ skipped: list[str] = []+ for dirpath, dirnames, filenames in os.walk(root, followlinks=False):+ base = Path(dirpath)+ kept: list[str] = []+ for name in sorted(dirnames):+ candidate = base / name+ parts = candidate.relative_to(root).parts+ if (+ candidate.is_symlink()+ or publication_source_entry_is_excluded(root, candidate)+ or (len(parts) == 1 and _matches_generated_name(candidate, "evals"))+ ):+ continue+ if matches_filesystem_name(candidate, excluded_dirs):+ skipped.append("/".join(parts))+ continue+ kept.append(name)+ dirnames[:] = kept+ for name in sorted(filenames):+ candidate = base / name+ if candidate.is_symlink() or publication_source_entry_is_excluded(root, candidate):+ continue+ if matches_filesystem_name(candidate, excluded_files):+ skipped.append("/".join(candidate.relative_to(root).parts))+ if len(skipped) >= limit:+ break+ return sorted(skipped)[:limit]++def _hash_descriptor(descriptor: int) -> str:digest = hashlib.sha256()os.lseek(descriptor, 0, os.SEEK_SET)@@ -597,6 +673,24 @@ def _canonical_directory_entry_name(path: Path) -> str:raise ValueError(f"publication source directory entry is ambiguous: {path}")+def publication_target_name(target_path: Path) -> str | None:+ """Return the NFC entry name that publication targets record for a path.++ On a case- or normalization-insensitive filesystem a lexical alias such as+ ``SIMPLE`` can open the entry recorded as ``simple``. Every tier stamps the+ recorded spelling, so report expectations must use it instead of the alias.+ """+ try:+ target = _absolute_lexical(target_path.expanduser())+ skill_name = unicodedata.normalize("NFC", _canonical_directory_entry_name(target))+ if not skill_name:+ return None+ skill_name.encode("utf-8", errors="strict")+ except (OSError, RuntimeError, UnicodeError, ValueError):+ return None+ return skill_name++def publication_target_from_path(target_path: Path) -> dict[str, str] | None:"""Return the canonical publication target for one source snapshot."""try:@@ -719,11 +813,15 @@ def stamp_publication_target(__all__ = [+ "PUBLICATION_ANY_DEPTH_EXCLUDED_NAMES","PUBLICATION_TARGET_DIGEST_ALGORITHM","PublicationTargetConflictError","finalize_publication_target",+ "publication_paths_skipped_by_scan","publication_source_digest",+ "publication_source_link_is_generated","publication_target_from_path",+ "publication_target_name","stamp_publication_identity","stamp_publication_target",]diff --git a/src/skillevaluator/publication_text.py b/src/skillevaluator/publication_text.pyindex ccc1b8f9..3168ecfb 100644--- a/src/skillevaluator/publication_text.py+++ b/src/skillevaluator/publication_text.py@@ -354,6 +354,30 @@ def publication_semantic_text(value: object, *, strip_marks: bool = False) -> streturn "".join(semantic)+# Line feed, carriage return and tab are ordinary layout in free text such as+# prompts, judge explanations and suggestions. JSON escapes them losslessly.+_LAYOUT_WHITESPACE = frozenset({"\t", "\n", "\r"})+++def publication_free_text(value: object) -> str:+ """Normalize free text like :func:`publication_semantic_text`, keeping layout whitespace.++ Every other control, format, or invisible identity character is still+ removed, so terminal escapes and spoofing characters are still detected+ by callers that compare this projection with the raw text.+ """+ text = _safe_text(value)+ segments: list[str] = []+ start = 0+ for index, character in enumerate(text):+ if character in _LAYOUT_WHITESPACE:+ segments.append(publication_semantic_text(text[start:index]))+ segments.append(character)+ start = index + 1+ segments.append(publication_semantic_text(text[start:]))+ return "".join(segments)++def publication_confusable_skeleton(value: object) -> str:"""Return the pinned UTS #39 skeleton subset needed by reserved identities."""# The embedded values already contain the effective result of the UTS #39@@ -392,6 +416,7 @@ __all__ = ["UNICODE_CONFUSABLES_SUBSET_SOURCE_COUNT","UNICODE_CONFUSABLES_VERSION","publication_confusable_skeleton",+ "publication_free_text","publication_identity_present","publication_semantic_text",]diff --git a/src/skillevaluator/reporting/base.py b/src/skillevaluator/reporting/base.pyindex 6a846aa3..e43f200a 100644--- a/src/skillevaluator/reporting/base.py+++ b/src/skillevaluator/reporting/base.py@@ -37,10 +37,20 @@ from skillevaluator.constants import (DIMENSION_VERDICT_NEUTRAL_THRESHOLD,DIMENSION_VERDICT_PASS_THRESHOLD,)-from skillevaluator.publication_evidence import result_publication_evidence+from skillevaluator.publication_evidence import (+ TIER1_REQUIRED_CHECKS_KEY,+ TIER1_UNSCANNED_PATHS_KEY,+ declared_tier1_required_checks,+ result_publication_evidence,+)from skillevaluator.publication_identity import PUBLICATION_TARGET_DIGEST_ALGORITHM-from skillevaluator.publication_text import publication_identity_present, publication_semantic_text+from skillevaluator.publication_text import (+ publication_free_text,+ publication_identity_present,+ publication_semantic_text,+)from skillevaluator.utils.path_security import canonicalize_trusted_root_alias+from skillevaluator.utils.rich_markup import strip_terminal_controls_AGENT_EVAL_MAX_FUTURE_CLOCK_SKEW = timedelta(minutes=5)@@ -103,6 +113,8 @@ _AGENT_EVAL_RUN_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,159}")_PUBLICATION_TARGET_SKILL_NAME_MAX_BYTES = 1024_PUBLICATION_TARGET_CONFLICT_MAX_BYTES = 256_PUBLICATION_TARGET_CONFLICT_FALLBACK = "publication target identity conflict"+_RUNTIME_CONTEXT_CONFLICT_MARKER = "runtime context is not bound to publication target"+_SKIP_REASON_MAX_CHARS = 1024class UnsafeReportPathError(click.ClickException, ValueError):@@ -428,23 +440,52 @@ def is_cleanly_skipped(result: ValidationResult) -> bool:def get_skip_reason(result: ValidationResult) -> str:- """Return a stable human-readable reason for a skipped result."""+ """Return a bounded, single-line reason safe for downstream renderers."""metadata = result.metadata if isinstance(result.metadata, dict) else {}- reason = metadata.get("skip_reason")+ reason = _safe_skip_reason_text(metadata.get("skip_reason"))if reason:- return str(reason)+ return reasonpayload = metadata.get("agent_eval")provenance = payload.get("provenance") if isinstance(payload, dict) else None- advisory_message = provenance.get("message") if isinstance(provenance, dict) else None+ advisory_message = _safe_skip_reason_text(provenance.get("message")) if isinstance(provenance, dict) else ""if advisory_message:- return str(advisory_message)+ return advisory_messageif result.warnings:- return str(result.warnings[0])+ warning = _safe_skip_reason_text(result.warnings[0])+ if warning:+ return warningreturn "Prerequisite unavailable"+def _safe_skip_reason_text(value: object) -> str:+ """Normalize one untrusted reason without changing identity-safe text rules."""+ sample_truncated = False+ if isinstance(value, str):+ sample_limit = _SKIP_REASON_MAX_CHARS * 4+ sample_truncated = len(value) > sample_limit+ raw = value[:sample_limit].encode("utf-8", errors="replace").decode("utf-8")+ else:+ raw = _agent_eval_safe_text(value)+ if not raw:+ return ""+ # Drop whole terminal escape sequences (OSC hyperlinks and titles, CSI+ # styling) before flattening, so their payloads never reach a report.+ raw = strip_terminal_controls(raw)+ flattened = " ".join(+ "".join(+ " " if character.isspace() or unicodedata.category(character) in {"Cc", "Cf"} else character+ for character in raw+ ).split()+ )+ if not flattened:+ return ""+ if not sample_truncated and len(flattened) <= _SKIP_REASON_MAX_CHARS:+ return flattened+ return flattened[: _SKIP_REASON_MAX_CHARS - 1] + "…"++def is_tier2_validator_name(validator_name: str | None) -> bool:"""Return whether a normalized validator name belongs to Tier 2."""normalized = " ".join((validator_name or "").casefold().replace("_", " ").replace("-", " ").split())@@ -461,6 +502,11 @@ def agent_eval_report_text_limit() -> int:return AGENT_EVAL_REPORT_MAX_TEXT_BYTES+# Tier 3 identity subtrees whose text must survive emission exactly. Other+# payload strings are free text that may contain layout whitespace.+AGENT_EVAL_EXACT_TEXT_KEYS = frozenset({"publication_target", "skill_name"})++def agent_eval_report_serialization_issue(value: object) -> str | None:"""Return why Tier 3 cannot be emitted losslessly within report limits."""if not isinstance(value, dict):@@ -471,11 +517,11 @@ def agent_eval_report_serialization_issue(value: object) -> str | None:max_depth, max_nodes = agent_eval_report_serialization_limits()max_text_bytes = agent_eval_report_text_limit()active_containers: set[int] = set()- stack: list[tuple[object, int, bool]] = [(value, 0, False)]+ stack: list[tuple[object, int, bool, bool]] = [(value, 0, False, False)]nodes = 0text_bytes = 0while stack:- current, depth, exiting = stack.pop()+ current, depth, exiting, exact_text = stack.pop()if exiting:active_containers.remove(id(current))continue@@ -491,7 +537,9 @@ def agent_eval_report_serialization_issue(value: object) -> str | None:if len(current) > max_text_bytes - text_bytes:return f"The Tier 3 payload exceeds the {max_text_bytes:,}-byte report text limit."utf8_safe = current.encode("utf-8", errors="replace").decode("utf-8")- normalized = publication_semantic_text(current)+ # Free text keeps line breaks and tabs; identity text and every+ # other control, format, or invisible character stay rejected.+ normalized = publication_semantic_text(current) if exact_text else publication_free_text(current)if utf8_safe != current or normalized != unicodedata.normalize("NFKC", utf8_safe):return "The Tier 3 payload contains text that cannot be emitted losslessly."text_bytes += len(normalized.encode("utf-8"))@@ -517,7 +565,7 @@ def agent_eval_report_serialization_issue(value: object) -> str | None:if container_id in active_containers:return "The Tier 3 payload contains a recursive container."active_containers.add(container_id)- stack.append((current, depth, True))+ stack.append((current, depth, True, exact_text))if isinstance(current, dict):safe_keys: set[str] = set()for key in current:@@ -535,11 +583,11 @@ def agent_eval_report_serialization_issue(value: object) -> str | None:if text_bytes > max_text_bytes:return f"The Tier 3 payload exceeds the {max_text_bytes:,}-byte report text limit."safe_keys.add(safe_key)- children = current.values()+ children = [(child, exact_text or key in AGENT_EVAL_EXACT_TEXT_KEYS) for key, child in current.items()]else:- children = current- for child in reversed(children):- stack.append((child, depth + 1, False))+ children = [(child, exact_text) for child in current]+ for child, child_exact_text in reversed(children):+ stack.append((child, depth + 1, False, child_exact_text))return None@@ -836,6 +884,29 @@ def _agent_eval_has_publication_target_conflict(payload: dict[str, Any] | None)return "publication_target_conflict" in payload or "publication_target_conflict" in summary+def _agent_eval_publication_target_conflict_markers(payload: dict[str, Any] | None) -> set[str]:+ """Return bounded conflict markers from both canonical Tier 3 copies."""+ if not isinstance(payload, dict):+ return set()+ summary = payload.get("summary") if isinstance(payload.get("summary"), dict) else {}+ return {+ publication_target_conflict_marker(container.get("publication_target_conflict"))+ for container in (payload, summary)+ if "publication_target_conflict" in container+ }+++def _result_publication_target_conflict_markers(result: ValidationResult) -> set[str]:+ """Return bounded direct and nested conflict markers for one result."""+ metadata = result.metadata if isinstance(result.metadata, dict) else {}+ markers = _agent_eval_publication_target_conflict_markers(+ metadata.get("agent_eval") if isinstance(metadata.get("agent_eval"), dict) else None+ )+ if "publication_target_conflict" in metadata:+ markers.add(publication_target_conflict_marker(metadata.get("publication_target_conflict")))+ return markers++def agent_eval_publication_target(payload: dict[str, Any] | None) -> PublicationTargetIdentity | None:"""Return the duplicated Tier 3 target claim only when both copies agree."""if not isinstance(payload, dict):@@ -931,23 +1002,41 @@ def _agent_eval_agents(payload: dict[str, Any] | None) -> dict[str, dict[str, Anreturn agents-def _agent_eval_attempt_coverage_complete(payload: dict[str, Any] | None) -> bool:+def _agent_eval_attempt_coverage_complete(+ payload: dict[str, Any] | None,+ *,+ require_baseline: bool = True,+) -> bool:"""Return whether succeeded Tier 3 evidence proves positive attempt coverage."""expected_attempts = _agent_eval_consistent_count_field(payload, "expected_attempts")scored_attempts = _agent_eval_consistent_count_field(payload, "scored_attempts")+ dataset_tasks = _agent_eval_dataset_count(payload) if isinstance(payload, dict) else 0+ attempt_policy = payload.get("attempt_policy") if isinstance(payload, dict) else None+ max_attempts = _agent_eval_count(attempt_policy.get("max_attempts")) if isinstance(attempt_policy, dict) else 0+ stop_on_pass = attempt_policy.get("stop_on_pass") if isinstance(attempt_policy, dict) else None+ pass_threshold = (+ _agent_eval_finite_score(attempt_policy.get("pass_threshold")) if isinstance(attempt_policy, dict) else None+ )if (expected_attempts is Noneor scored_attempts is Noneor expected_attempts <= 0or scored_attempts <= 0- or scored_attempts > expected_attempts+ or scored_attempts != expected_attempts+ or dataset_tasks <= 0+ or max_attempts <= 0+ or not isinstance(stop_on_pass, bool)+ or pass_threshold is None+ or (stop_on_pass and max_attempts <= 1)):return False- scored_agents = 0summed_expected = 0summed_scored = 0- for agent in _agent_eval_agents(payload).values():+ agents = _agent_eval_agents(payload)+ if not agents:+ return False+ for agent in agents.values():raw_expected = agent.get("expected_attempts")raw_scored = agent.get("scored_attempts")if (@@ -959,19 +1048,106 @@ def _agent_eval_attempt_coverage_complete(payload: dict[str, Any] | None) -> booreturn Falseagent_expected = _agent_eval_count(agent.get("expected_attempts"))agent_scored = _agent_eval_count(agent.get("scored_attempts"))- if agent_scored > agent_expected:+ if (+ _agent_eval_safe_text(agent.get("execution_status")).casefold() != "succeeded"+ or agent_expected <= 0+ or agent_scored != agent_expected+ or not _agent_eval_condition_attempt_coverage_complete(+ agent,+ expected_attempts=agent_expected,+ scored_attempts=agent_scored,+ dataset_tasks=dataset_tasks,+ max_attempts=max_attempts,+ stop_on_pass=stop_on_pass,+ require_baseline=require_baseline,+ )+ ):return Falsesummed_expected += agent_expectedsummed_scored += agent_scored- if _agent_eval_safe_text(agent.get("execution_status")).casefold() != "succeeded":+ return summed_expected == expected_attempts and summed_scored == scored_attempts+++def _agent_eval_condition_attempt_coverage_complete(+ agent: dict[str, Any],+ *,+ expected_attempts: int,+ scored_attempts: int,+ dataset_tasks: int,+ max_attempts: int,+ stop_on_pass: bool,+ require_baseline: bool,+) -> bool:+ """Validate the two canonical conditions against one agent aggregate."""+ conditions = agent.get("conditions")+ if not isinstance(conditions, dict) or set(conditions) != {"with_skill", "without_skill"}:+ return False++ summed_expected = 0+ summed_scored = 0+ for condition_name, condition in conditions.items():+ if not isinstance(condition, dict):+ return False+ raw_expected = condition.get("expected_attempts")+ raw_scored = condition.get("scored_attempts")+ if (+ isinstance(raw_expected, bool)+ or not isinstance(raw_expected, int)+ or isinstance(raw_scored, bool)+ or not isinstance(raw_scored, int)+ ):+ return False+ condition_expected = _agent_eval_count(raw_expected)+ condition_scored = _agent_eval_count(raw_scored)+ status = _agent_eval_safe_text(condition.get("execution_status")).casefold()+ full_attempt_count = dataset_tasks * max_attempts+ expected_count_is_valid = (+ dataset_tasks <= condition_expected <= full_attempt_count+ if stop_on_pass+ else condition_expected == full_attempt_count+ )+ if condition_name == "without_skill" and not require_baseline and status == "skipped":+ if condition_expected != 0 or condition_scored != 0:+ return False+ continue+ if status != "succeeded" or not expected_count_is_valid or condition_scored != condition_expected:+ return False+ summed_expected += condition_expected+ summed_scored += condition_scored++ return summed_expected == expected_attempts and summed_scored == scored_attempts+++def _agent_eval_execution_errors_clear(payload: dict[str, Any] | None) -> bool:+ """Return whether succeeded Tier 3 evidence contains no execution errors."""+ if not isinstance(payload, dict):+ return False+ summary = payload.get("summary") if isinstance(payload.get("summary"), dict) else {}+ agents = _agent_eval_agents(payload)+ containers = [payload, summary, *agents.values()]+ for agent in agents.values():+ if "conditions" not in agent:continue- if agent_expected <= 0 or agent_scored <= 0:+ conditions = agent.get("conditions")+ if not isinstance(conditions, dict):+ return False+ for condition in conditions.values():+ if not isinstance(condition, dict) or "execution_errors" not in condition:+ return False+ containers.append(condition)+ for container in containers:+ errors = container.get("execution_errors")+ if not isinstance(errors, list) or errors:return False- scored_agents += 1- return bool(scored_agents > 0 and summed_expected == expected_attempts and summed_scored == scored_attempts)+ return True-def _agent_eval_dimension_scores(agent: dict[str, Any]) -> list[float] | None:+def _agent_eval_dimension_scores(+ agent: dict[str, Any],+ *,+ require_baseline: bool,+) -> list[float] | None:+ """Return with-skill scores only when matching baseline evidence exists."""raw_dimensions = agent.get("dimensions")if not isinstance(raw_dimensions, list):return None@@ -985,19 +1161,55 @@ def _agent_eval_dimension_scores(agent: dict[str, Any]) -> list[float] | None:dimensions[dimension_id] = raw_dimensionscores: list[float] = []+ baselines: list[float] = []for dimension_id in DIMENSION_MAPPING:dimension = dimensions.get(dimension_id)if dimension is None:return Nonevalue = dimension.get("with_skill") if "with_skill" in dimension else dimension.get("score")score = _agent_eval_finite_score(value)- if score is None:+ baseline = _agent_eval_finite_score(dimension.get("baseline"))+ if score is None or (require_baseline and baseline is None):return None+ if require_baseline:+ assert baseline is not None+ lift = _agent_eval_finite_number(dimension.get("lift"))+ if lift is None or not math.isclose(lift, score - baseline, rel_tol=1e-9, abs_tol=5e-4):+ return None+ baselines.append(baseline)scores.append(score)++ agent_score = _agent_eval_finite_score(agent.get("with_skill", agent.get("overall_score")))+ if agent_score is None or not math.isclose(+ agent_score,+ sum(scores) / len(scores),+ rel_tol=1e-9,+ abs_tol=5e-4,+ ):+ return None+ if require_baseline:+ agent_baseline = _agent_eval_finite_score(agent.get("baseline"))+ agent_lift = _agent_eval_finite_number(agent.get("lift"))+ if (+ agent_baseline is None+ or agent_lift is None+ or not math.isclose(+ agent_baseline,+ sum(baselines) / len(baselines),+ rel_tol=1e-9,+ abs_tol=5e-4,+ )+ or not math.isclose(agent_lift, agent_score - agent_baseline, rel_tol=1e-9, abs_tol=5e-4)+ ):+ return Nonereturn scores-def agent_eval_dimension_verdict(payload: dict[str, Any] | None) -> str | None:+def agent_eval_dimension_verdict(+ payload: dict[str, Any] | None,+ *,+ require_baseline: bool = True,+) -> str | None:"""Recompute a Tier 3 verdict from complete supported-agent dimensions."""supported_agents = [agent@@ -1010,7 +1222,7 @@ def agent_eval_dimension_verdict(payload: dict[str, Any] | None) -> str | None:verdicts: list[str] = []has_partial_evidence = Falsefor agent in supported_agents:- scores = _agent_eval_dimension_scores(agent)+ scores = _agent_eval_dimension_scores(agent, require_baseline=require_baseline)if scores is None:has_partial_evidence = Truecontinue@@ -1053,6 +1265,106 @@ def _agent_eval_dataset_count(payload: dict[str, Any]) -> int:return len(task_ids)+def _agent_eval_publication_aggregates_consistent(+ payload: dict[str, Any],+ agents: dict[str, dict[str, Any]],+) -> bool:+ """Require duplicated publication summaries to match the selected agent."""+ summary = payload.get("summary")+ if not isinstance(summary, dict):+ return False++ raw_best_names = (payload.get("best_agent"), summary.get("best_agent"))+ if (+ any(not isinstance(name, str) or not name or name != name.strip() for name in raw_best_names)+ or raw_best_names[0] != raw_best_names[1]+ ):+ return False+ assert isinstance(raw_best_names[0], str)+ best_name = publication_semantic_text(raw_best_names[0]).strip()+ if best_name not in agents:+ return False++ raw_agents = payload.get("agents")+ if not isinstance(raw_agents, dict) or any(not isinstance(name, str) for name in raw_agents):+ return False+ canonical_agent_names = [publication_semantic_text(name).strip() for name in sorted(raw_agents)]+ if len(canonical_agent_names) != len(agents) or any(name not in agents for name in canonical_agent_names):+ return False++ eligible_agents: list[tuple[str, float, float]] = []+ for name in canonical_agent_names:+ agent = agents[name]+ if _agent_eval_safe_text(agent.get("execution_status")).casefold() != "succeeded":+ continue+ score = _agent_eval_finite_score(agent.get("with_skill"))+ if score is None:+ continue+ lift = _agent_eval_finite_number(agent.get("lift"))+ eligible_agents.append((name, score, lift or 0.0))+ if not eligible_agents or max(eligible_agents, key=lambda item: (item[1], item[2]))[0] != best_name:+ return False++ expected_agents = canonical_agent_names+ raw_agents_run: list[list[str]] = []+ for container in (payload, summary):+ agents_run = container.get("agents_run")+ if (+ not isinstance(agents_run, list)+ or any(not isinstance(name, str) for name in agents_run)+ ):+ return False+ raw_agents_run.append(agents_run)+ if raw_agents_run[0] != raw_agents_run[1] or [+ publication_semantic_text(name).strip() for name in raw_agents_run[0]+ ] != expected_agents:+ return False++ best_agent = agents[best_name]+ if (+ _agent_eval_safe_text(best_agent.get("execution_status")).casefold() != "succeeded"+ or _agent_eval_dimension_scores(best_agent, require_baseline=True) is None+ ):+ return False+ best_score = _agent_eval_finite_score(best_agent.get("with_skill", best_agent.get("overall_score")))+ best_lift = _agent_eval_finite_number(best_agent.get("lift"))+ if best_score is None or best_lift is None or not -1.0 <= best_lift <= 1.0:+ return False++ for key, expected, validator in (+ ("overall_score", best_score, _agent_eval_finite_score),+ ("overall_lift", best_lift, _agent_eval_finite_number),+ ):+ root_value = validator(payload.get(key))+ summary_value = validator(summary.get(key))+ if (+ root_value is None+ or summary_value is None+ or not math.isclose(root_value, summary_value, rel_tol=1e-9, abs_tol=5e-4)+ or not math.isclose(root_value, expected, rel_tol=1e-9, abs_tol=5e-4)+ ):+ return False++ try:+ root_dimensions = json.dumps(+ payload.get("dimensions"),+ allow_nan=False,+ ensure_ascii=False,+ separators=(",", ":"),+ sort_keys=True,+ )+ agent_dimensions = json.dumps(+ best_agent.get("dimensions"),+ allow_nan=False,+ ensure_ascii=False,+ separators=(",", ":"),+ sort_keys=True,+ )+ except (TypeError, ValueError):+ return False+ return root_dimensions == agent_dimensions++def agent_eval_publication_evidence_complete(payload: dict[str, Any] | None) -> bool:"""Return whether a payload carries the minimum publication Tier 3 evidence."""if not isinstance(payload, dict):@@ -1075,7 +1387,9 @@ def agent_eval_publication_evidence_complete(payload: dict[str, Any] | None) ->truth_consistentand verdict in {"pass", "neutral", "fail"}and execution_status == "succeeded"+ and _agent_eval_execution_errors_clear(payload)and agent_eval_dimension_verdict(payload) is not None+ and _agent_eval_publication_aggregates_consistent(payload, agents)and agent_eval_publication_evaluated_at(payload) is not Noneand publication_identity_present(evaluator_version)and agent_eval_publication_dataset_provenance(payload) is not None@@ -1600,6 +1914,69 @@ def is_tier2_result(result: ValidationResult) -> bool:)+def missing_tier1_publication_checks(results: list[ValidationResult]) -> tuple[str, ...]:+ """Return applicable built-in Tier 1 checks that no executed result covers.++ Built-in Tier 1 producers record the content type's whole lineup, so a run+ narrowed with ``--checks`` cannot certify Tier 1 with a subset of checks.+ """+ executed = [+ (result, producer)+ for result in results+ if (producer := result_publication_evidence(result)) is not None+ and producer.tier == 1+ and not is_cleanly_skipped(result)+ ]+ declarations = [+ result.metadata[TIER1_REQUIRED_CHECKS_KEY]+ for result, _producer in executed+ if isinstance(result.metadata, dict) and TIER1_REQUIRED_CHECKS_KEY in result.metadata+ ]+ if not declarations:+ return ()+ required = frozenset().union(*(declared_tier1_required_checks(value) for value in declarations))+ covered = {producer.check_id for _result, producer in executed}+ return tuple(sorted(required - covered))+++def tier1_unscanned_publication_paths(results: list[ValidationResult]) -> tuple[str, ...]:+ """Return certified source paths that recognized Tier 1 runs skipped by name.++ A malformed record fails closed with a placeholder entry.+ """+ paths: list[str] = []+ for result in results:+ producer = result_publication_evidence(result)+ metadata = result.metadata if isinstance(result.metadata, dict) else {}+ if (+ producer is None+ or producer.tier != 1+ or is_cleanly_skipped(result)+ or TIER1_UNSCANNED_PATHS_KEY not in metadata+ ):+ continue+ value = metadata[TIER1_UNSCANNED_PATHS_KEY]+ if not isinstance(value, list) or any(not isinstance(item, str) or not item for item in value):+ paths.append("(unreadable Tier 1 scan scope)")+ continue+ paths.extend(value)+ return tuple(dict.fromkeys(paths))+++def unrecognized_tier2_results(results: list[ValidationResult]) -> list[ValidationResult]:+ """Return executed Tier 2 results that lack a recognized built-in producer.++ Optional Tier 2 evidence may be absent or cleanly skipped. A present,+ executed Tier 2 result whose producer marker is missing or invalid is+ malformed evidence, not absence, so a waiver cannot hide it.+ """+ return [+ result+ for result in results+ if result_publication_evidence(result) is None and is_tier2_result(result) and not is_cleanly_skipped(result)+ ]++def _publication_identity_key(value: object) -> str | None:"""Normalize canonical aliases without folding filesystem distinctions."""if not publication_identity_present(value):@@ -1669,10 +2046,10 @@ def assess_tier3_evidence(selected_payload,"Tier 3 scanner evidence is incomplete.",)- if any(- not result.passed and (serialization_issue is not None or not is_cleanly_skipped(result))- for result in tier3_results- ):+ # A cleanly skipped advisory result is non-passing by construction. When+ # its payload cannot be emitted losslessly, the serialization branch below+ # decides between an explicit failure and incomplete evidence.+ if any(not result.passed and not is_cleanly_skipped(result) for result in tier3_results):return Tier3EvidenceAssessment("fail",False,@@ -1681,16 +2058,22 @@ def assess_tier3_evidence(selected_payload,"A Tier 3 validator failed.",)- if _agent_eval_has_publication_target_conflict(selected_payload) or any(- _result_has_publication_target_conflict(result) for result in tier3_results- ):+ conflict_markers = _agent_eval_publication_target_conflict_markers(selected_payload)+ for result in tier3_results:+ conflict_markers.update(_result_publication_target_conflict_markers(result))+ if conflict_markers:+ reason = (+ "Tier 3 runtime context is not bound to the publication target."+ if conflict_markers == {_RUNTIME_CONTEXT_CONFLICT_MARKER}+ else "Tier 3 source identity changed during evaluation."+ )return Tier3EvidenceAssessment("incomplete",False,execution_status or "incomplete",raw_verdict or "incomplete",selected_payload,- "Tier 3 source identity changed during evaluation.",+ reason,)if run_id_issue := next((issue for result in tier3_results if (issue := _result_agent_eval_run_id_issue(result)) is not None),@@ -1815,7 +2198,7 @@ def assess_tier3_evidence(_agent_eval_safe_text(agent.get("execution_status")).lower() == "succeeded"and (_agent_eval_finite_score(agent.get("with_skill", agent.get("overall_score"))) is not None- or bool(_agent_eval_dimension_scores(agent))+ or bool(_agent_eval_dimension_scores(agent, require_baseline=False)))and max(payload_attempts, _agent_eval_count(agent.get("scored_attempts"))) > 0for agent in _agent_eval_agents(selected_payload).values()@@ -1967,6 +2350,13 @@ def assess_publication(reasons.append("Recognized built-in Tier 1 evidence is missing.")elif any(not result_has_execution_evidence(result) for result in executed_tier1):reasons.append("Tier 1 lacks trustworthy execution evidence.")+ if missing_checks := missing_tier1_publication_checks(results):+ reasons.append(f"Tier 1 did not run every required check: {', '.join(missing_checks)}.")+ if unscanned_paths := tier1_unscanned_publication_paths(results):+ reasons.append(+ f"Tier 1 skipped {len(unscanned_paths)} certified source path(s) that use generated-artifact names "+ "below the skill root."+ )require_bound_evidence(executed_tier1, "Tier 1")executed_tier2 = [result for result in tier2_results if not is_cleanly_skipped(result)]@@ -1974,6 +2364,8 @@ def assess_publication(reasons.append("Tier 2 lacks trustworthy execution evidence.")elif policy["tier2_required"] and not executed_tier2:reasons.append("Required recognized built-in Tier 2 evidence is missing.")+ if unrecognized_tier2_results(results):+ reasons.append("Tier 2 evidence lacks a recognized built-in producer identity.")require_bound_evidence(executed_tier2, "Tier 2")executed_tier3 = [result for result in tier3_results if not is_cleanly_skipped(result)]@@ -2006,10 +2398,10 @@ def passes_required_gate(result: ValidationResult) -> bool:and truth_consistentand verdict == "pass"and execution_status == "succeeded"- and agent_eval_dimension_verdict(payload) == "pass"+ and agent_eval_dimension_verdict(payload, require_baseline=False) == "pass"and isinstance(payload, dict)and _agent_eval_dataset_count(payload) > 0- and _agent_eval_attempt_coverage_complete(payload)+ and _agent_eval_attempt_coverage_complete(payload, require_baseline=False))return bool(result.passed)return bool(result.passed or is_advisory_agent_eval_skip(result))diff --git a/src/skillevaluator/reporting/benchmark.py b/src/skillevaluator/reporting/benchmark.pyindex 08f57ecd..44eb7534 100644--- a/src/skillevaluator/reporting/benchmark.py+++ b/src/skillevaluator/reporting/benchmark.py@@ -22,6 +22,7 @@ from skillevaluator.constants import (TIER3_LIFT_PASS_THRESHOLD,)from skillevaluator.publication_evidence import result_has_publication_evidence, result_publication_evidence+from skillevaluator.publication_text import publication_confusable_skeletonfrom skillevaluator.reporting.base import (PublicationTargetIdentity,ReporterBase,@@ -37,6 +38,7 @@ from skillevaluator.reporting.base import (is_cleanly_skipped,is_tier2_result,is_tier3_result,+ missing_tier1_publication_checks,publication_identity_present,publication_semantic_text,publication_target_for_results,@@ -44,7 +46,10 @@ from skillevaluator.reporting.base import (result_has_execution_evidence,result_matches_publication_target,select_agent_eval_payload,+ tier1_unscanned_publication_paths,+ unrecognized_tier2_results,)+from skillevaluator.source_identity import evaluated_source_revision, recorded_evaluated_sourcefrom skillevaluator.tier3_environments import HARBOR_ENV_MODESif TYPE_CHECKING:@@ -101,6 +106,12 @@ _PUBLIC_USER_PATH = re.compile()_MARKDOWN_INLINE_SPECIAL = re.compile(r"([\\*_\[\]~])")_MARKDOWN_BLOCK_PREFIX = re.compile(r"^(?:#{1,6}|>|[+*-]|\d+[.)])(?=\s|$)")+# The public benchmark gate rejects a non-PASS card whose visible text contains+# this decision phrase, matching confusable aliases by treating each non-ASCII+# character as a wildcard for one letter. Untrusted text is screened the same way.+_DECISION_ALIAS_SENTINEL = "\x00"+_PUBLICATION_DECISION_PHRASE = "recommended for publication"+_PLAIN_DECISION_PHRASE = re.compile(r"recommended\s+for\s+publication", flags=re.IGNORECASE)_MARKDOWN_THEMATIC_BREAK = re.compile(r"^(?:\s*[-*_]){3,}\s*$")_PUBLICATION_URL_SCHEME = re.compile(r"(?P<scheme>https?|ftp)://", flags=re.IGNORECASE)_PUBLICATION_WWW_PREFIX = re.compile(r"\bwww\.", flags=re.IGNORECASE)@@ -136,8 +147,16 @@ class BenchmarkReporter(ReporterBase):def render_all(self, results: list[ValidationResult]) -> str:ae = _agent_eval_payload(results)- expected_skill_name = self.skill_name or _skill_name(results, ae)- skill_name = _publication_safe_skill_name(expected_skill_name)+ publication_target = publication_target_for_results(+ results,+ ae,+ expected_skill_name=self.skill_name,+ )+ expected_skill_name = self.skill_name or (+ publication_target.skill_name if publication_target is not None else None+ )+ display_skill_name = self.skill_name or _skill_name(results, ae) or expected_skill_name or "skill"+ skill_name = _publication_safe_skill_name(display_skill_name)private_labels = _private_environment_labels(ae)policy = _benchmark_policy(results, ae, expected_skill_name=expected_skill_name)status = _overall_status(results, ae, policy, expected_skill_name=expected_skill_name)@@ -320,8 +339,11 @@ class BenchmarkReporter(ReporterBase):lines.append("- Dataset digest: not recorded (legacy or non-live result)")tier3_run_id = agent_eval_publication_run_id(ae)+ # The accessor admits only `[A-Za-z0-9][A-Za-z0-9._-]*`, which is inert in a+ # code span. Markdown escaping would put literal backslashes into runner IDs+ # such as `20261016_081505_4821_3f9c2a1b7d4e`.lines.append(- f"- Tier 3 run ID: `{_publication_safe_inline(tier3_run_id)}`"+ f"- Tier 3 run ID: `{tier3_run_id}`"if tier3_run_idelse "- Tier 3 run ID: not recorded (Tier 3 did not complete)")@@ -666,6 +688,14 @@ class BenchmarkReporter(ReporterBase):def _agent_eval_payload(results: list[ValidationResult]) -> dict[str, Any] | None:+ """Return the payload the score and run-detail lines describe.++ A card reports one live evaluation, so one payload is rendered: the+ strongest Tier 3 payload, selected independently of result order. That+ choice is safe for scores, which belong to a single run, but not for the+ evaluated-source identity: see ``_evaluated_source``, which folds every+ carrier instead so a second payload cannot be silently dropped.+ """return select_agent_eval_payload(results)@@ -743,7 +773,7 @@ def _verdict_callout(status: str) -> str:return f"> {labels.get(status, f'**Overall verdict: {status}**')}"-def _skill_name(results: list[ValidationResult], ae: dict[str, Any] | None) -> str:+def _skill_name(results: list[ValidationResult], ae: dict[str, Any] | None) -> str | None:if ae:summary = _mapping(ae.get("summary"))candidate = ae.get("skill_name") or summary.get("skill_name")@@ -753,7 +783,7 @@ def _skill_name(results: list[ValidationResult], ae: dict[str, Any] | None) -> squality = result.metadata.get("quality_scores") if isinstance(result.metadata, dict) else Noneif isinstance(quality, dict) and (candidate := _safe_scalar_text(quality.get("skill_name")).strip()):return candidate- return "skill"+ return Nonedef _safe_scalar_text(value: object) -> str:@@ -1102,6 +1132,11 @@ def _tier_status(]if not publication_results:return "INCOMPLETE", f"No recognized built-in {tier} producer evidence was recorded"+ if tier == "Tier 2" and (unrecognized := unrecognized_tier2_results(results)):+ validator_names = list(+ dict.fromkeys(result.validator_name or "Tier 2 validator" for result in unrecognized)+ )+ return "INCOMPLETE", f"Unrecognized Tier 2 producer evidence from {', '.join(validator_names)}"unbound_results = [result@@ -1120,6 +1155,13 @@ def _tier_status()return "INCOMPLETE", f"Missing trustworthy execution evidence from {', '.join(validator_names)}"+ if tier == "Tier 1" and (missing_checks := missing_tier1_publication_checks(publication_results)):+ return "INCOMPLETE", f"Required Tier 1 checks did not run: {', '.join(missing_checks)}"++ if tier == "Tier 1" and (unscanned_paths := tier1_unscanned_publication_paths(publication_results)):+ shown = ", ".join(unscanned_paths[:5]) + (", ..." if len(unscanned_paths) > 5 else "")+ return "INCOMPLETE", f"Tier 1 skipped certified paths with generated-artifact names: {shown}"+skipped = [result for result in publication_results if is_cleanly_skipped(result)]if tier in {"Tier 1", "Tier 2"} and skipped:reasons = "; ".join(_skip_reasons(skipped))@@ -1328,6 +1370,15 @@ def _publication_safe_inline(text = _PUBLICATION_WWW_PREFIX.sub(lambda match: f"{match.group(0)[:-1]}.", text)text = text.replace("@", "@")text = _MARKDOWN_INLINE_SPECIAL.sub(r"\\\1", text)+ if _contains_publication_decision_phrase(text):+ # Validator output or skill content must not carry the card's decision+ # wording, or a legitimate non-PASS card would fail the public gate.+ # Join the phrase itself first, then the whole value, then withhold it.+ text = _PLAIN_DECISION_PHRASE.sub(lambda match: "-".join(match.group(0).split()), text)+ if _contains_publication_decision_phrase(text):+ text = "-".join(text.split())+ if _contains_publication_decision_phrase(text):+ text = "[text withheld: it contains publication decision wording]"if _MARKDOWN_BLOCK_PREFIX.match(text) or _MARKDOWN_THEMATIC_BREAK.fullmatch(text):marker_end = text.find(" ")marker_end = len(text) if marker_end < 0 else marker_end@@ -1338,6 +1389,34 @@ def _publication_safe_inline(return text+def _decision_phrase_surface(value: str) -> str:+ """Project text the way the public gate does before matching decision wording."""+ skeleton = publication_confusable_skeleton(publication_semantic_text(value, strip_marks=True))+ return "".join(+ " " if character.isspace() else character if character.isascii() else _DECISION_ALIAS_SENTINEL+ for character in skeleton+ )+++_PUBLICATION_DECISION_PATTERN = re.compile(+ "".join(+ r"\s+"+ if character.isspace()+ else f"(?:{re.escape(character)}|{re.escape(_DECISION_ALIAS_SENTINEL)})"+ if character.isascii() and character.isalnum()+ else re.escape(character)+ for character in publication_confusable_skeleton(+ publication_semantic_text(_PUBLICATION_DECISION_PHRASE, strip_marks=True)+ )+ )+)+++def _contains_publication_decision_phrase(value: str) -> bool:+ """Return whether text would read as a publication decision to the public gate."""+ return _PUBLICATION_DECISION_PATTERN.search(_decision_phrase_surface(value)) is not None++def _normalized_publication_text(value: object) -> str:"""Canonicalize text and discard invisible controls before publication decisions."""return " ".join(publication_semantic_text(value).split())diff --git a/src/skillevaluator/reporting/cli.py b/src/skillevaluator/reporting/cli.pyindex dfdd2bbd..2682c1d0 100644--- a/src/skillevaluator/reporting/cli.py+++ b/src/skillevaluator/reporting/cli.py@@ -33,7 +33,13 @@ from skillevaluator.constants import (DIMENSION_VERDICT_NEUTRAL_THRESHOLD,DIMENSION_VERDICT_PASS_THRESHOLD,)-from skillevaluator.reporting.base import ReporterBase, is_advisory_agent_eval_skip, passes_required_gate+from skillevaluator.reporting.base import (+ ReporterBase,+ additional_errors,+ get_skip_reason,+ is_advisory_agent_eval_skip,+ passes_required_gate,+)from skillevaluator.reporting.harbor_viewer import (harbor_evidence_link_text,normalize_harbor_viewer_for_display,@@ -45,6 +51,9 @@ if TYPE_CHECKING:from skillevaluator.models import Finding, ValidationResult+_SKIP_REASON_MAX_CHARS = 1024++def _related_paths(finding: Finding) -> list[str]:"""Return distinct path-like string values carried in finding metadata."""metadata = finding.metadata if isinstance(finding.metadata, dict) else {}@@ -58,6 +67,14 @@ def _related_paths(finding: Finding) -> list[str]:return paths+def _rich_skip_reason(result: ValidationResult) -> str:+ """Return one bounded, single-line skip reason inert to Rich markup."""+ reason = " ".join(get_skip_reason(result).replace("\r\n", "\n").replace("\r", "\n").split())+ if len(reason) > _SKIP_REASON_MAX_CHARS:+ reason = reason[: _SKIP_REASON_MAX_CHARS - 1] + "…"+ return escape_markup(reason)++class CLIReporter(ReporterBase):"""Terminal-based reporter with Rich formatting.@@ -554,9 +571,7 @@ class CLIReporter(ReporterBase):static_test_evidence = self._static_test_evidence_message(result)if advisory_skip:- agent_eval = result.metadata.get("agent_eval", {})- provenance = agent_eval.get("provenance", {}) if isinstance(agent_eval, dict) else {}- details = escape_markup(str(provenance.get("message") or "Live evaluation did not run"))+ details = _rich_skip_reason(result)elif result.is_incomplete:scanners = escape_markup(", ".join(result.incomplete_scans))details = f"[bold yellow]{scanners} did not complete[/bold yellow]"diff --git a/src/skillevaluator/reporting/console_ui.py b/src/skillevaluator/reporting/console_ui.pyindex e8f0b78a..3375f0ea 100644--- a/src/skillevaluator/reporting/console_ui.py+++ b/src/skillevaluator/reporting/console_ui.py@@ -26,8 +26,10 @@ consoles are created with ``emoji=False`` so ``:name:`` codes print literally.from __future__ import annotations+import mathimport sysimport time+import unicodedatafrom dataclasses import dataclass, fieldfrom typing import TYPE_CHECKING, TextIO@@ -37,6 +39,7 @@ from rich.live import Livefrom rich.panel import Panelfrom rich.text import Text+from skillevaluator.reporting.base import get_skip_reasonfrom skillevaluator.utils.rich_markup import strip_terminal_controlsif TYPE_CHECKING:@@ -64,6 +67,12 @@ WIDTH = 98LABEL = 12DUR = 8BAR = 10+_SKIP_REASON_MAX_CHARS = 110+# Setup instructions in a skip reason span several short lines (provider+# variables, a docs link, the flag that skips the tier); keep them readable.+_SKIP_REASON_MAX_LINES = 12+_SKIP_REASON_SOURCE_MAX_CHARS = 4096+_TIER3_TEXT_MAX_CHARS = 110SPIN = "◐◓◑◒"PENDING = "pending"@@ -288,7 +297,9 @@ class ValidateView:returnblock = self.blocks[index]block.status = SKIP- block.rows = [TierRow("skipped", [(reason, MUTED)])]+ # Multi-line reasons (setup instructions) continue on unlabeled rows.+ lines = reason.split("\n") or [""]+ block.rows = [TierRow("skipped" if index == 0 else "", [(line, MUTED)]) for index, line in enumerate(lines)]self._refresh()self._flush_static()@@ -516,14 +527,117 @@ def _is_skipped(result: ValidationResult) -> bool:"""True when a validator was recorded without executing (OSS conventions)."""if bool(getattr(result, "skipped", False)):return True- meta = result.metadata or {}+ meta = result.metadata if isinstance(result.metadata, dict) else {}if meta.get("skipped") or meta.get("execution_status") == "skipped":return True- payload = meta.get("agent_eval") or {}- summary = payload.get("summary") or {}+ payload = meta.get("agent_eval")+ if not isinstance(payload, dict):+ return False+ summary = payload.get("summary")+ if not isinstance(summary, dict):+ summary = {}return payload.get("execution_status") == "skipped" or summary.get("execution_status") == "skipped"+def _bounded_console_line(line: str) -> str:+ """Flatten one line of untrusted text and bound it for the compact view."""+ flattened = " ".join(+ "".join(+ " " if character.isspace() or unicodedata.category(character).startswith("C") else character+ for character in line+ ).split()+ )+ if len(flattened) <= _SKIP_REASON_MAX_CHARS:+ return flattened+ return flattened[: _SKIP_REASON_MAX_CHARS - 1] + "…"+++def _raw_skip_reason(result: ValidationResult) -> str:+ """Return the untrusted reason text that ``get_skip_reason`` would select."""+ metadata = result.metadata if isinstance(result.metadata, dict) else {}+ payload = metadata.get("agent_eval")+ provenance = payload.get("provenance") if isinstance(payload, dict) else None+ candidates = (+ metadata.get("skip_reason"),+ provenance.get("message") if isinstance(provenance, dict) else None,+ result.warnings[0] if result.warnings else None,+ )+ for candidate in candidates:+ if candidate is None:+ continue+ if not isinstance(candidate, str):+ # Non-text metadata keeps the shared single-line projection.+ return ""+ if _bounded_console_line(strip_terminal_controls(candidate)):+ return candidate+ return ""+++def _skip_reason(result: ValidationResult) -> str:+ """Return a bounded, terminal-safe reason that keeps its line structure.++ Each line is flattened and bounded separately, and at most+ ``_SKIP_REASON_MAX_LINES`` lines are kept, so setup instructions stay+ readable while escapes, controls, and oversized text cannot reach the+ terminal.+ """+ raw = _raw_skip_reason(result)+ if not raw:+ return _bounded_console_line(get_skip_reason(result))+ sample = strip_terminal_controls(raw[:_SKIP_REASON_SOURCE_MAX_CHARS])+ lines = [+ bounded+ for line in sample.replace("\r\n", "\n").replace("\r", "\n").split("\n")+ if (bounded := _bounded_console_line(line))+ ]+ truncated = len(raw) > _SKIP_REASON_SOURCE_MAX_CHARS or len(lines) > _SKIP_REASON_MAX_LINES+ lines = lines[:_SKIP_REASON_MAX_LINES]+ if truncated and lines and not lines[-1].endswith("…"):+ lines[-1] = lines[-1][: _SKIP_REASON_MAX_CHARS - 1] + "…"+ return "\n".join(lines)+++def sanitize_tier3_console_text(value: object, *, limit: int = _TIER3_TEXT_MAX_CHARS) -> str:+ """Project untrusted Tier 3 text into one bounded terminal-safe line."""+ if not isinstance(value, str) or limit <= 0:+ return ""+ sample_limit = max(limit, limit * 4)+ sample = value[:sample_limit]+ flattened = " ".join(+ "".join(+ " "+ if character.isspace() or unicodedata.category(character).startswith("C")+ else character+ for character in sample+ ).split()+ )+ truncated = len(value) > len(sample) or len(flattened) > limit+ if not truncated:+ return flattened+ if limit == 1:+ return "…"+ return flattened[: limit - 1] + "…"+++def _tier3_string_list(value: object, *, max_items: int = 16) -> list[str]:+ """Return a small list of safe strings from a canonical JSON array."""+ if not isinstance(value, list):+ return []+ projected = [sanitize_tier3_console_text(item, limit=64) for item in value[:max_items]]+ return [item for item in projected if item]+++def _tier3_finite_number(value: object) -> float | None:+ """Return a finite display number without overflowing on huge integers."""+ if isinstance(value, bool) or not isinstance(value, (int, float)):+ return None+ try:+ number = float(value)+ except (OverflowError, ValueError):+ return None+ return number if math.isfinite(number) else None++_VALIDATOR_CHECK_KEYS = (("schema", "schema"),("security scan", "security"),@@ -662,12 +776,7 @@ def summarize_tier2(results: list[ValidationResult]) -> tuple[bool, bool, list[Treturn False, True, [], "no deduplication results returned"skipped = [r for r in results if _is_skipped(r)]if skipped and len(skipped) == len(results):- first = skipped[0]- reason = str(- (first.metadata or {}).get("skip_reason")- or (first.warnings[0] if first.warnings else "prerequisite unavailable")- )- return False, True, [], reason+ return False, True, [], _skip_reason(skipped[0])failed = [r for r in results if not r.passed and not _is_skipped(r)]advisories = sum(len(r.findings) for r in results if r.passed)rows: list[TierRow] = []@@ -720,32 +829,44 @@ def _tier2_finding_is_scan_failure(finding: object) -> bool:def summarize_tier3(result: ValidationResult) -> tuple[bool, bool, list[TierRow], str]:"""Return (ran, passed, rows, skip_reason) for the agent-eval result."""- if _is_skipped(result) or (not result.passed and not (result.metadata or {}).get("agent_eval", {}).get("summary")):- reason = str(- (result.metadata or {}).get("skip_reason")- or (result.warnings[0] if result.warnings else "prerequisite unavailable")- )- return False, True, [], reason- payload = (result.metadata or {}).get("agent_eval") or {}- summary = payload.get("summary") or payload- agents = summary.get("agents_run") or payload.get("agents_run") or []- agent_segments: list[tuple[str, str]] = [(", ".join(agents) or "n/a", TEXT)]- case_list = payload.get("cases") or []- if case_list:+ metadata = result.metadata if isinstance(result.metadata, dict) else {}+ raw_payload = metadata.get("agent_eval")+ payload = raw_payload if isinstance(raw_payload, dict) else {}+ raw_summary = payload.get("summary")+ has_summary = isinstance(raw_summary, dict) and bool(raw_summary)+ if _is_skipped(result) or (not result.passed and not has_summary):+ return False, True, [], _skip_reason(result)+ summary = raw_summary if has_summary else payload+ raw_agents = summary.get("agents_run")+ if not isinstance(raw_agents, list) or not raw_agents:+ raw_agents = payload.get("agents_run")+ agents = _tier3_string_list(raw_agents)+ agent_label = sanitize_tier3_console_text(", ".join(agents)) or "n/a"+ agent_segments: list[tuple[str, str]] = [(agent_label, TEXT)]+ case_list = payload.get("cases")+ if isinstance(case_list, list) and case_list:# A plain count: per-case pass/fail lives in the report, and rendering# a fabricated N/N ratio here would overstate what we measured.agent_segments.append((f" eval cases {len(case_list)}", MUTED))rows = [TierRow("agent", agent_segments)]- lift = summary.get("overall_lift")- with_score = summary.get("overall_score")- if isinstance(lift, (int, float)) and isinstance(with_score, (int, float)):- baseline = max(0.0, min(1.0, float(with_score) - float(lift)))- rows.append(lift_row(float(lift), float(with_score), baseline))+ lift = _tier3_finite_number(summary.get("overall_lift"))+ with_score = _tier3_finite_number(summary.get("overall_score"))+ if (+ lift is not None+ and -1.0 <= lift <= 1.0+ and with_score is not None+ and 0.0 <= with_score <= 1.0+ ):+ baseline = with_score - lift+ if 0.0 <= baseline <= 1.0:+ rows.append(lift_row(lift, with_score, baseline))exec_status = payload.get("execution_status") or summary.get("execution_status")ok = bool(result.passed) and exec_status in (None, "succeeded")if not ok:- errors = list(payload.get("execution_errors") or []) or list(result.errors)- reason = str(errors[0]) if errors else "execution reported errors"+ errors = _tier3_string_list(payload.get("execution_errors"), max_items=1)+ if not errors:+ errors = _tier3_string_list(result.errors, max_items=1)+ reason = errors[0] if errors else "execution reported errors"rows.append(TierRow("error",diff --git a/src/skillevaluator/reporting/html.py b/src/skillevaluator/reporting/html.pyindex d8a22b1a..82182d34 100644--- a/src/skillevaluator/reporting/html.py+++ b/src/skillevaluator/reporting/html.py@@ -42,7 +42,9 @@ from skillevaluator import __version__from skillevaluator.constants import TIER3_LIFT_FAIL_THRESHOLD, TIER3_LIFT_PASS_THRESHOLDfrom skillevaluator.publication_evidence import result_publication_evidence_dictfrom skillevaluator.reporting.base import (+ AGENT_EVAL_EXACT_TEXT_KEYS,ReporterBase,+ additional_errors,agent_eval_publication_evidence_complete,agent_eval_report_serialization_issue,agent_eval_report_serialization_limits,@@ -55,6 +57,7 @@ from skillevaluator.reporting.base import (is_tier2_result,is_tier3_result,passes_required_gate,+ publication_free_text,publication_identity_present,publication_semantic_text,publication_target_conflict_marker,@@ -72,6 +75,10 @@ if TYPE_CHECKING:from skillevaluator.models import ValidationResult+# SkillSpector reports ``metadata.skillspector_version`` as a bare semantic+# version. Anything else is dropped rather than echoed into the report.+_SKILLSPECTOR_VERSION_RE = re.compile(r"\d{1,6}\.\d{1,6}\.\d{1,6}(?:[-+][0-9A-Za-z.-]{1,64})?")+# Tier 3 already enforces a 2 MiB canonical payload limit. HTML needs a# separate bound because script-safe escaping (``<`` -> ``\u003c``), pretty# diagnostics, and visible dataset fields can otherwise multiply that payload@@ -202,7 +209,9 @@ def _json_safe_tier3_value(truncated[0] = Truereturn Noneutf8_safe_value = value.encode("utf-8", errors="replace").decode("utf-8")- safe_value = _json_safe_tier3_text(value)+ # Free text keeps line breaks and tabs, which JSON escapes losslessly;+ # identity text keeps the strict projection used for publication keys.+ safe_value = _json_safe_tier3_text(value) if _preserve_exact_text else publication_free_text(utf8_safe_value)if utf8_safe_value != value or safe_value != unicodedata.normalize("NFKC", utf8_safe_value):truncated[0] = Trueelif _preserve_exact_text and unicodedata.normalize("NFC", utf8_safe_value) == utf8_safe_value:@@ -309,7 +318,7 @@ def _json_safe_tier3_value(_remaining_text_bytes=remaining_text_bytes,_truncated=truncated,_max_depth=max_depth,- _preserve_exact_text=_preserve_exact_text or safe_key in {"publication_target", "skill_name"},+ _preserve_exact_text=_preserve_exact_text or safe_key in AGENT_EVAL_EXACT_TEXT_KEYS,)if remaining_nodes[0] <= 0 and processed_keys < total_keys:truncated[0] = True@@ -860,12 +869,20 @@ def _sanitize_tier3_trial(value: dict[str, Any]) -> dict[str, Any]:trial["scores"] = _score_mapping(trial.get("scores"))trial["baseline_scores"] = _score_mapping(trial.get("baseline_scores"))trial["lift_scores"] = _score_mapping(trial.get("lift_scores"), minimum=-1.0, maximum=1.0)- tokens = trial.get("tokens") if isinstance(trial.get("tokens"), dict) else {}- trial["tokens"] = {- "prompt": _nonnegative_count(tokens.get("prompt")),- "completion": _nonnegative_count(tokens.get("completion")),- }- trial["steps"] = _nonnegative_count(trial.get("steps"))+ # Unavailable telemetry stays absent rather than becoming zero, so the+ # template can omit charts and show "—" instead of reporting no usage.+ raw_tokens = trial.pop("tokens", None)+ tokens = raw_tokens if isinstance(raw_tokens, dict) else {}+ prompt_tokens = _strict_nonnegative_count(tokens.get("prompt"))+ completion_tokens = _strict_nonnegative_count(tokens.get("completion"))+ if prompt_tokens is not None and completion_tokens is not None:+ trial["tokens"] = {"prompt": prompt_tokens, "completion": completion_tokens}+ cached_tokens = _strict_nonnegative_count(tokens.get("cached"))+ if cached_tokens is not None:+ trial["tokens"]["cached"] = cached_tokens+ steps = _strict_nonnegative_count(trial.pop("steps", None))+ if steps is not None:+ trial["steps"] = stepstrial["warnings"] = _string_list(trial.get("warnings"))recovery = trial.get("error_recovery") if isinstance(trial.get("error_recovery"), dict) else {}recovery["details"] = _string_list(recovery.get("details"))@@ -1144,6 +1161,17 @@ def _bounded_tier3_preview(payload: dict[str, Any] | None) -> tuple[dict[str, Anreturn preview, notice+def _skillspector_versions(results: list[ValidationResult]) -> list[str]:+ """Return the distinct SkillSpector versions recorded on ``results``, in first-seen order."""+ versions: dict[str, None] = {}+ for result in results:+ metadata = result.metadata if isinstance(result.metadata, dict) else {}+ raw_version = metadata.get("skillspector_version")+ if isinstance(raw_version, str) and _SKILLSPECTOR_VERSION_RE.fullmatch(raw_version.strip()):+ versions.setdefault(raw_version.strip(), None)+ return list(versions)++def _related_paths(finding: object) -> list[str]:"""Return distinct path-like string values carried in finding metadata."""metadata = finding.get("metadata", {}) if isinstance(finding, dict) else getattr(finding, "metadata", {})@@ -2389,10 +2417,16 @@ class HTMLReporter(ReporterBase):# payload make the decision only more conservative. Display shaping# must never invent a successful run or erase a persisted waiver.raw_publication = assess_publication(results, expected_skill_name=self.expected_skill_name)- emitted_publication = assess_publication(- results,- tier3_data,- expected_skill_name=self.expected_skill_name,+ # Without a persisted payload, tier3_data is a synthesized display+ # fallback rather than evidence, so only the raw assessment applies.+ emitted_publication = (+ assess_publication(+ results,+ tier3_data,+ expected_skill_name=self.expected_skill_name,+ )+ if select_agent_eval_candidate(tier3_results) is not None+ else raw_publication)publication = max((raw_publication, emitted_publication),@@ -2650,6 +2684,7 @@ class HTMLReporter(ReporterBase):"reason": publication.tier3.reason,},},+ "skillspector_versions": tier1_skillspector_versions,}report_json = (json.dumps(report_data, indent=2, allow_nan=False)diff --git a/src/skillevaluator/reporting/json_reporter.py b/src/skillevaluator/reporting/json_reporter.pyindex 71cb558c..31bb2bf0 100644--- a/src/skillevaluator/reporting/json_reporter.py+++ b/src/skillevaluator/reporting/json_reporter.py@@ -30,6 +30,7 @@ from skillevaluator.reporting.base import (result_publication_target_dict,select_agent_eval_payload,)+from skillevaluator.source_identity import recorded_evaluated_sourceif TYPE_CHECKING:from skillevaluator.models import ValidationResult@@ -331,6 +332,16 @@ class JSONReporter(ReporterBase):if publication_evidence is not None:data["publication_evidence"] = publication_evidence+ workflow = result.metadata.get("workflow")+ if isinstance(workflow, dict):+ data["workflow"] = workflow++ # Tier 2 records bounded provider diagnostics and completed/failed+ # cluster counts independently of duplicate-content findings.+ llm_analysis = result.metadata.get("llm_analysis")+ if isinstance(llm_analysis, dict):+ data["llm_analysis"] = llm_analysis+return datadef get_file_extension(self) -> str:diff --git a/src/skillevaluator/reporting/markdown.py b/src/skillevaluator/reporting/markdown.pyindex 4d6d4f84..3e968346 100644--- a/src/skillevaluator/reporting/markdown.py+++ b/src/skillevaluator/reporting/markdown.py@@ -20,8 +20,10 @@ import unicodedatafrom datetime import UTC, datetimefrom typing import TYPE_CHECKING+from skillevaluator.evidence import evidence_ref_identityfrom skillevaluator.reporting.base import (ReporterBase,+ additional_errors,assess_publication,get_skip_reason,is_advisory_agent_eval_skip,@@ -39,9 +41,24 @@ if TYPE_CHECKING:from skillevaluator.models import Finding, ValidationResult+_SKIP_REASON_MAX_CHARS = 1024+++def _markdown_safe_characters(value: str, *, preserve_newlines: bool = False) -> str:+ """Remove control and separator characters from untrusted Markdown text."""+ safe: list[str] = []+ for character in value.replace("\r\n", "\n").replace("\r", "\n"):+ category = unicodedata.category(character)+ if category.startswith("C") or category in {"Zl", "Zp"}:+ safe.append("\n" if preserve_newlines and character == "\n" else " ")+ else:+ safe.append(character)+ return "".join(safe)++def _markdown_table_cell(value: object) -> str:"""Return one safe physical Markdown table cell."""- normalized = str(value).replace("\r\n", "\n").replace("\r", "\n")+ normalized = _markdown_safe_characters(str(value), preserve_newlines=True)escaped = html.escape(normalized, quote=False)return escaped.replace("|", "|").replace("`", "`").replace("\n", "<br>")@@ -75,7 +92,7 @@ def _markdown_inline_text(value: object, *, limit: int | None = None) -> str:text = str(value)else:return ""- flattened = " ".join(text.replace("\r\n", "\n").replace("\r", "\n").split())+ flattened = " ".join(_markdown_safe_characters(text).split())if limit is not None:flattened = flattened[:limit]escaped = html.escape(flattened, quote=False)@@ -93,6 +110,16 @@ def _markdown_inline_text(value: object, *, limit: int | None = None) -> str:return escaped+def _markdown_code_text(value: object, *, limit: int | None = None) -> str:+ """Flatten untrusted metadata for a code span without obscuring paths."""+ if not isinstance(value, str):+ return ""+ flattened = " ".join(_markdown_safe_characters(value).split())+ if limit is not None:+ flattened = flattened[:limit]+ return html.escape(flattened, quote=False).replace("`", "`")++def _mapping(value: object) -> dict:return value if isinstance(value, dict) else {}@@ -351,9 +378,9 @@ class MarkdownReporter(ReporterBase):label = _markdown_inline_text(harbor_evidence_link_text(harbor_evidence)) or "Evidence"lines.append(f" - Evidence: [{label}]({url})")for ref in _dict_items(suggestion.get("evidence_refs"))[:3]:- pointer = _markdown_inline_text(ref.get("json_pointer") or ref.get("path"))+ pointer = _markdown_code_text(evidence_ref_identity(ref))excerpt = _markdown_inline_text(ref.get("excerpt") or ref.get("label"), limit=120)- kind = _markdown_inline_text(ref.get("kind")) or "evidence"+ kind = _markdown_code_text(ref.get("kind")) or "evidence"lines.append(f" - Evidence: `{kind}` `{pointer}` {excerpt}")lines.append("")elif recommendations := _dict_items(ae.get("recommendations")):@@ -423,7 +450,9 @@ class MarkdownReporter(ReporterBase):if result.is_incomplete:self._render_incomplete(result, lines)elif clean_skip:- lines.append(f"- Skip reason: {get_skip_reason(result)}")+ lines.append(+ f"- Skip reason: {_markdown_inline_text(get_skip_reason(result), limit=_SKIP_REASON_MAX_CHARS)}"+ )elif result.passed:self._render_success(result, lines)if result.findings:diff --git a/src/skillevaluator/reporting/templates/report.html.j2 b/src/skillevaluator/reporting/templates/report.html.j2index 162fa4bc..269a3f60 100644--- a/src/skillevaluator/reporting/templates/report.html.j2+++ b/src/skillevaluator/reporting/templates/report.html.j2@@ -1950,6 +1950,15 @@Checks for redundant content within one skill and semantic overlap across skills or local catalog entries.</p>{% for result in tier2_results %}+ {% set execution_errors = result | additional_errors %}+ {% if execution_errors %}+ <div style="background:var(--bg-secondary);border:1px solid var(--border-color);border-radius:8px;padding:1rem;margin:0.75rem 0;">+ <strong>{{ 'Execution errors' if result.is_incomplete else 'Errors' }}</strong>+ <ul style="margin:0.5rem 0 0;padding-left:1.25rem;">+ {% for error in execution_errors %}<li style="white-space:pre-line;">{{ error }}</li>{% endfor %}+ </ul>+ </div>+ {% endif %}{% if result | cleanly_skipped %}<div style="background:var(--bg-secondary);border:1px solid var(--warning-color);border-radius:8px;padding:1rem;margin:0.75rem 0;"><strong style="color:var(--warning-color);">Skip reason:</strong> {{ result | skip_reason }}diff --git a/src/skillevaluator/tier1/commands.py b/src/skillevaluator/tier1/commands.pyindex f346bd8c..ddc1b77b 100644--- a/src/skillevaluator/tier1/commands.py+++ b/src/skillevaluator/tier1/commands.py@@ -17,11 +17,21 @@ from skillevaluator.constants import (CONTENT_TYPE_SKILL,CONTENT_TYPE_UNKNOWN,CONTENT_TYPE_WORKFLOWS,+ SCAN_EXCLUDED_DIRS,+ SCAN_EXCLUDED_FILES,)from skillevaluator.models.result import ValidationResult-from skillevaluator.publication_evidence import stamp_publication_evidence-from skillevaluator.publication_identity import finalize_publication_target, publication_target_from_path-from skillevaluator.reporting import CLIReporter, HTMLReporter, JSONReporter, MarkdownReporter+from skillevaluator.publication_evidence import (+ TIER1_UNSCANNED_PATHS_KEY,+ stamp_publication_evidence,+ stamp_tier1_required_checks,+)+from skillevaluator.publication_identity import (+ finalize_publication_target,+ publication_paths_skipped_by_scan,+ publication_target_from_path,+)+from skillevaluator.reporting import CLIReporter, HTMLReporter, JSONReporter, MarkdownReporter, SARIFReporterfrom skillevaluator.reporting.html import is_tier2_validator_namefrom skillevaluator.reporting.naming import DEFAULT_REPORT_BASENAMEfrom skillevaluator.utils.rich_markup import escape_markup@@ -78,6 +88,13 @@ REPORTERS = {}+def _stamp_tier1_scan_scope(results: list[ValidationResult], target: Path) -> None:+ """Record certified source paths that the Tier 1 scans skipped by name."""+ skipped = publication_paths_skipped_by_scan(target, SCAN_EXCLUDED_DIRS, SCAN_EXCLUDED_FILES)+ for result in results:+ result.metadata[TIER1_UNSCANNED_PATHS_KEY] = list(skipped)++def _as_result(name: str,description: str,@@ -86,6 +103,7 @@ def _as_result(*,publication_check_id: str,bind_publication_target: bool = True,+ skill_like: bool = True,) -> ValidationResult:initial_target = publication_target_from_path(target) if bind_publication_target else Noneresult = validator(target)@@ -94,7 +112,11 @@ def _as_result(if not result.validator_description:result.validator_description = descriptionstamp_publication_evidence([result], tier=1, check_id=publication_check_id)+ # Record the whole applicable lineup, so a run narrowed with --checks (or a+ # standalone single-check command) cannot certify Tier 1 by itself.+ stamp_tier1_required_checks([result], skill_like=skill_like)if bind_publication_target:+ _stamp_tier1_scan_scope([result], target)finalize_publication_target([result], target, initial_target)return result@@ -198,6 +220,7 @@ def run_validation(target_path,publication_check_id=check_id,bind_publication_target=False,+ skill_like=skill_like,)def _schema_results() -> list[ValidationResult]:@@ -289,6 +312,7 @@ def run_validation()if fail_fast and not continue_on_failure and any(not r.passed for r in results):+ _stamp_tier1_scan_scope(results, target_path)finalize_publication_target(results, target_path, initial_target)return results@@ -301,6 +325,7 @@ def run_validation(result.add_error(f"Unknown Tier 1 check(s): {', '.join(sorted(unknown))}")results.insert(0, result)+ _stamp_tier1_scan_scope(results, target_path)finalize_publication_target(results, target_path, initial_target)return results@@ -439,6 +464,11 @@ def emit_reports(tabs=html_tabs,expected_skill_name=expected_skill_name,)+ elif fmt == "sarif":+ reporter = reporter_cls(+ workspace_root=sarif_repository_root,+ scan_root=sarif_scan_root,+ )else:reporter = reporter_cls(expected_skill_name=expected_skill_name)output_path = output_dir / f"{basename}{reporter.get_file_extension()}"diff --git a/src/skillevaluator/tier2/commands.py b/src/skillevaluator/tier2/commands.pyindex bb8e6c93..d40e5040 100644--- a/src/skillevaluator/tier2/commands.py+++ b/src/skillevaluator/tier2/commands.py@@ -83,17 +83,15 @@ def run_context_optimization_check(model: str | None = None,llm_model: str | None = None,) -> list[ValidationResult]:- validator = IntraSkillValidator(- threshold=threshold,- embedding_model=model,- llm_model=llm_model,- )- return _guarded_result(- "Context Deduplication",- skill_path,- lambda: validator.validate(skill_path),- check_id="context-optimization",- )+ def _run() -> ValidationResult:+ validator = IntraSkillValidator(+ threshold=threshold,+ embedding_model=model,+ llm_model=llm_model,+ )+ return validator.validate(skill_path)++ return _guarded_result("Context Deduplication", skill_path, _run, check_id="context-optimization")def run_dedup_scan(diff --git a/src/skillevaluator/tier3/__init__.py b/src/skillevaluator/tier3/__init__.pyindex 283a83f6..4dc7de9b 100644--- a/src/skillevaluator/tier3/__init__.py+++ b/src/skillevaluator/tier3/__init__.py@@ -25,11 +25,14 @@ __all__ = [def __getattr__(name: str) -> Any:"""Load public command exports without making Harbor an eager dependency."""+ # CLI registration and help must work without the optional Harbor runtime.if name not in __all__:raise AttributeError(f"module {__name__!r} has no attribute {name!r}")- return getattr(import_module("skillevaluator.tier3.commands"), name)+ value = getattr(import_module("skillevaluator.tier3.commands"), name)+ globals()[name] = value+ return valuedef __dir__() -> list[str]:"""Expose lazy command exports to interactive callers and documentation."""- return sorted((*globals(), *__all__))+ return sorted({*globals(), *__all__})diff --git a/src/skillevaluator/tier3/commands.py b/src/skillevaluator/tier3/commands.pyindex e49aae82..312aa212 100644--- a/src/skillevaluator/tier3/commands.py+++ b/src/skillevaluator/tier3/commands.py@@ -655,6 +655,7 @@ def evaluate(override_memory_mb: int | None,override_storage_mb: int | None,repo_context_exclude_paths: tuple[Path, ...] = (),+ evaluated_source: dict[str, str] | None = None,progress_reporter: ProgressReporter | None = None,) -> dict[str, Any]:"""Run Harbor live-agent evaluation for a skill."""diff --git a/src/skillevaluator/tier3/harbor/adapter.py b/src/skillevaluator/tier3/harbor/adapter.pyindex c3286c30..6d8e12d7 100644--- a/src/skillevaluator/tier3/harbor/adapter.py+++ b/src/skillevaluator/tier3/harbor/adapter.py@@ -36,9 +36,16 @@ from urllib.parse import unquotefrom skillevaluator.publication_identity import (publication_source_entry_is_excluded,+ publication_source_link_is_generated,publication_source_path_is_excluded,)-from skillevaluator.tier3.case_ids import safe_child, validate_case_ids, validate_output_directory_path+from skillevaluator.tier3.case_ids import (+ safe_child,+ validate_case_id,+ validate_case_ids,+ validate_output_directory_path,+)+from skillevaluator.tier3.harbor import DEFAULT_LLM_VERIFIER_TIMEOUT_SECfrom skillevaluator.tier3.harbor.secure_copy import (copy_file_secure,copytree_secure,@@ -53,6 +60,10 @@ from skillevaluator.tier3.output_provenance import (write_generated_output_marker,)from skillevaluator.tier3.toml_utils import extract_toml_metadata_entry_id, toml_quote+from skillevaluator.utils.path_security import (+ find_git_repo_root,+ resolve_repo_context_root,+)from skillevaluator.utils.process_environment import child_process_envfrom skillevaluator.utils.redaction import is_sensitive_key, redact_sensitive_textfrom skillevaluator.utils.secure_fs import SecurePathError, SecureRoot@@ -390,40 +401,6 @@ def _verifier_env_block(runtime_env: dict[str, str] | None = None, indent: str =return "\n".join(f'{indent}{name} = "${{{name}}}"' for name in _verifier_env_vars(runtime_env))-def _find_repo_root(path: Path) -> Path | None:- """Return the git repo root for *path*, falling back to parent .git search."""- try:- result = subprocess.run(- ["git", "-C", str(path), "rev-parse", "--show-toplevel"],- capture_output=True,- text=True,- timeout=5,- check=False,- )- if result.returncode == 0 and result.stdout.strip():- return Path(result.stdout.strip()).resolve()- except Exception:- pass-- current = path.resolve()- if current.is_file():- current = current.parent- for parent in (current, *current.parents):- if (parent / ".git").exists():- return parent- return None---def _repo_context_root(path: Path) -> Path:- """Return the exact source root used by repo-context staging."""- try:- repo_root = _find_repo_root(path)- resolved = path.resolve()- return repo_root or resolved.parent- except (OSError, RuntimeError) as exc:- raise ValueError(f"Cannot resolve repository context root for: {path}") from exc--def validate_output_provenance_key_location(skill_path: Path,output_dir: Path,@@ -435,7 +412,7 @@ def validate_output_provenance_key_location(protected_roots = [skill_path, output_dir, *workspace_skill_paths]if reference_skills_dir is not None:protected_roots.append(reference_skills_dir)- repo_root = _find_repo_root(skill_path)+ repo_root = find_git_repo_root(skill_path)if repo_root is not None:protected_roots.append(repo_root)for protected_root in protected_roots:@@ -858,6 +835,7 @@ def _runtime_skill_copy_ignore(skill_root: Path, excluded_roots: Sequence[Path]candidate = current / nameif (publication_source_entry_is_excluded(skill_root, candidate)+ or publication_source_link_is_generated(skill_root, candidate)or _is_skill_evals_path(candidate, skill_root)or _path_is_excluded(candidate, excluded_roots)or _authenticated_generated_output_ancestor(@@ -1281,7 +1259,7 @@ def _stage_repo_context(source_skill_path = source_skill_path.resolve()skill_md = _skill_manifest(source_skill_path)- repo_root = _repo_context_root(source_skill_path)+ repo_root = resolve_repo_context_root(source_skill_path)authenticated_output_roots: set[Path] = set()if (_authenticated_generated_output_ancestor(diff --git a/src/skillevaluator/tier3/harbor/runner.py b/src/skillevaluator/tier3/harbor/runner.pyindex 275aaa5e..24e9a5fb 100644--- a/src/skillevaluator/tier3/harbor/runner.py+++ b/src/skillevaluator/tier3/harbor/runner.py@@ -24,7 +24,7 @@ import tempfileimport threadingimport timeimport tomllib-from collections.abc import Mapping, Sequence+from collections.abc import Iterable, Iterator, Mapping, Sequencefrom concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, as_completed, waitfrom contextlib import ExitStack, contextmanager, suppressfrom dataclasses import dataclass, field@@ -51,8 +51,21 @@ from skillevaluator.provider_config import (is_claude_5_5_or_later,resolve_llm_provider,)-from skillevaluator.publication_identity import publication_target_from_path-from skillevaluator.tier3.evals_config import EvalsConfigError, load_evals_config+from skillevaluator.publication_identity import (+ PUBLICATION_ANY_DEPTH_EXCLUDED_NAMES,+ publication_source_path_is_excluded,+ publication_target_from_path,+)+from skillevaluator.source_identity import normalized_evaluated_source+from skillevaluator.tier3.case_ids import validate_case_ids+from skillevaluator.tier3.eval_core.llm_judge import JUDGE_REASONING_EFFORT+from skillevaluator.tier3.evals_config import (+ MAX_HARBOR_TIMEOUT_MULTIPLIER,+ EvalsConfigError,+ encode_environment_kwarg,+ load_evals_config,+ validate_environment_kwargs,+)from skillevaluator.tier3.harbor.adapter import (_RUNTIME_PROCESS_CONTROL_ENV_NAMES,_RUNTIME_PROCESS_CONTROL_ENV_PREFIXES,@@ -62,6 +75,7 @@ from skillevaluator.tier3.harbor.adapter import (_VERIFIER_RETRY_ENV_VARS,_native_entry_id,_prevalidate_baseline_skill_candidates,+ _read_regular_evals_file,build_eval_base_image,find_evals_file,generate_harbor_tasks,@@ -130,10 +144,150 @@ from skillevaluator.tier3_environments import (HARBOR_VERSION,harbor_environment_type,)+from skillevaluator.utils.path_security import matches_filesystem_namefrom skillevaluator.utils.redaction import is_sensitive_key, redact_sensitive_textfrom skillevaluator.utils.secure_fs import SecurePathError, SecureRootlogger = logging.getLogger(__name__)+_MAX_REPO_CONTEXT_METADATA_BYTES = 16 * 1024 * 1024+++def _runtime_source_is_bound_to_target(source: Path, target: Path) -> bool:+ """Return whether one staged runtime source is covered by the target digest."""+ try:+ source.absolute().relative_to(target.absolute())+ metadata = source.lstat()+ reparse_point = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)+ if stat.S_ISLNK(metadata.st_mode) or getattr(metadata, "st_file_attributes", 0) & reparse_point:+ return False+ resolved_source = source.resolve(strict=True)+ resolved_target = target.resolve(strict=True)+ resolved_source.relative_to(resolved_target)+ if publication_source_path_is_excluded(resolved_target, resolved_source):+ return False+ except (OSError, RuntimeError, ValueError):+ return False+ return True+++def _task_stages_digest_excluded_entries(task_path: Path) -> bool:+ """Return whether a generated task carries entries the source digest omits.++ Task inputs (``evals/files`` and per-entry ``files`` references) and the+ custom ``evals/environment`` are copied as authored, while the digest omits+ ``.git``, ``.venv``, ``__pycache__`` and ``node_modules`` at any depth. Such+ staged bytes could change Tier 3 inputs or outcomes without changing the+ certified digest. Generated task content never uses these names, and+ runtime skill and repository projections already omit them.+ """+ try:+ for dirpath, dirnames, filenames in os.walk(task_path, followlinks=False):+ base = Path(dirpath)+ for name in (*dirnames, *filenames):+ if matches_filesystem_name(base / name, PUBLICATION_ANY_DEPTH_EXCLUDED_NAMES):+ return True+ except (OSError, RuntimeError, ValueError):+ return True+ return False+++def _runtime_context_is_bound_to_publication_target(+ skill_path: Path,+ task_paths: Sequence[Path],+ *,+ reference_skills_dir: Path | None,+ workspace_skill_paths: Sequence[Path],+) -> bool:+ """Check that every staged runtime source is covered by the skill digest.++ ``publication_target`` deliberately identifies only the evaluated target+ tree. Repository links, full-repository context, and separately configured+ reference/workspace skills can add agent-visible bytes outside that tree.+ Until those inputs have their own versioned publication identity, retain+ the evaluation but fail its publication evidence closed.+ """+ try:+ target = skill_path.resolve(strict=True)+ except (OSError, RuntimeError, ValueError):+ return False++ if reference_skills_dir is not None:+ try:+ reference_metadata = reference_skills_dir.stat()+ if not stat.S_ISDIR(reference_metadata.st_mode):+ return False+ if not _runtime_source_is_bound_to_target(reference_skills_dir, target):+ return False+ reference_candidates: list[Path] = []+ for path in reference_skills_dir.iterdir():+ if path.name.startswith("."):+ continue+ child_metadata = path.stat()+ if stat.S_ISDIR(child_metadata.st_mode):+ reference_candidates.append(path)+ if any(not _runtime_source_is_bound_to_target(path, target) for path in reference_candidates):+ return False+ except (OSError, RuntimeError, ValueError):+ return False++ if any(not _runtime_source_is_bound_to_target(path, target) for path in workspace_skill_paths):+ return False++ for task_path in task_paths:+ if _task_stages_digest_excluded_entries(task_path):+ return False+ environment_path = task_path / "environment"+ context_path = environment_path / "repo-context.json"+ staged_repo_context = False+ for staged_name in ("repo", "repo-linked-root"):+ try:+ (environment_path / staged_name).lstat()+ staged_repo_context = True+ except FileNotFoundError:+ continue+ except (OSError, RuntimeError, ValueError):+ return False+ try:+ context_path.lstat()+ except FileNotFoundError:+ if staged_repo_context:+ return False+ continue+ except (OSError, RuntimeError, ValueError):+ return False+ try:+ encoded_context = _read_regular_evals_file(+ context_path,+ label="Repo context metadata",+ max_bytes=_MAX_REPO_CONTEXT_METADATA_BYTES,+ allowed_root=task_path,+ )+ context = json.loads(encoded_context.decode("utf-8"))+ files = context.get("files") if isinstance(context, dict) else None+ except (OSError, RecursionError, UnicodeError, ValueError):+ return False+ if not isinstance(files, list):+ return False+ mode = context.get("mode")+ if mode not in {"full", "linked"}:+ return False+ for entry in files:+ source = entry.get("source") if isinstance(entry, dict) else None+ if (+ not isinstance(source, str)+ or not source+ or not Path(source).is_absolute()+ or not _runtime_source_is_bound_to_target(Path(source), target)+ ):+ return False+ # Repository projection depends on source bytes and topology outside+ # the target-only digest (and full mode additionally depends on+ # excluded Git/operator selection state). Keep the run, but do not let+ # any nonempty repo context certify this target identity.+ if files or staged_repo_context:+ return False+ return True+PUBLISHED_EXECUTION_ERRORS_MAX = 256PUBLISHED_EXECUTION_ERROR_MAX_CHARS = 4096@@ -4154,21 +4308,22 @@ def _run_harbor_eval_impl("""Return the boundary identity, or a fail-closed mutation marker."""nonlocal publication_target_conflictif publication_target_conflict is not None:- return {- "publication_target": None,- "publication_target_conflict": {- "run_start": (- dict(publication_target_conflict["run_start"])- if isinstance(publication_target_conflict["run_start"], dict)- else None- ),- "run_end": (- dict(publication_target_conflict["run_end"])- if isinstance(publication_target_conflict["run_end"], dict)- else None- ),- },+ conflict: dict[str, Any] = {+ "run_start": (+ dict(publication_target_conflict["run_start"])+ if isinstance(publication_target_conflict["run_start"], dict)+ else None+ ),+ "run_end": (+ dict(publication_target_conflict["run_end"])+ if isinstance(publication_target_conflict["run_end"], dict)+ else None+ ),}+ reason_code = publication_target_conflict.get("reason_code")+ if isinstance(reason_code, str):+ conflict["reason_code"] = reason_code+ return {"publication_target": None, "publication_target_conflict": conflict}run_end_target = publication_target_from_path(skill_path)if run_end_target == publication_target:return {@@ -4274,6 +4429,7 @@ def _run_harbor_eval_impl())agent_task_dirs: dict[str, tuple[Path, Path | None]] = {}+ staged_task_paths: list[Path] = []expected_task_selectors: list[str] | None = Noneexpected_case_id_by_task_selector: dict[str, str] | None = Nonereporter.emit(@@ -4312,6 +4468,7 @@ def _run_harbor_eval_impl(evaluator_skill_path=evaluator_skill_path,arm_suffix=with_arm_suffix,)+ staged_task_paths.extend(task_paths)if staged_environment_error := _staged_task_environment_error(env_mode, task_paths):raise ValueError(staged_environment_error)task_selectors = validate_case_ids(task.name for task in task_paths)@@ -4367,6 +4524,7 @@ def _run_harbor_eval_impl(baseline_case_id_by_task_selector = dict(zip(baseline_task_selectors, baseline_logical_case_ids, strict=True))+ staged_task_paths.extend(baseline_task_paths)if (baseline_task_selectors != expected_task_selectorsor baseline_case_id_by_task_selector != expected_case_id_by_task_selector@@ -4380,6 +4538,18 @@ def _run_harbor_eval_impl(reporter.emit(ProgressEvent(stage=staging_failure_stage, state="failed", detail=str(exc)))return _persist_pre_execution_failure([str(exc)])+ if not _runtime_context_is_bound_to_publication_target(+ skill_path,+ staged_task_paths,+ reference_skills_dir=reference_skills_dir,+ workspace_skill_paths=workspace_skills,+ ):+ publication_target_conflict = {+ "run_start": dict(publication_target) if publication_target is not None else None,+ "run_end": None,+ "reason_code": "runtime_context_outside_publication_target",+ }+task_selectors = expected_task_selectors or []case_id_by_task_selector = expected_case_id_by_task_selector or {}case_ids = [case_id_by_task_selector[selector] for selector in task_selectors]diff --git a/src/skillevaluator/utils/path_security.py b/src/skillevaluator/utils/path_security.pyindex 6caee44a..ad731cd0 100644--- a/src/skillevaluator/utils/path_security.py+++ b/src/skillevaluator/utils/path_security.py@@ -7,6 +7,7 @@ from __future__ import annotationsimport osimport stat+import subprocessfrom collections.abc import Collectionfrom pathlib import Path@@ -59,7 +60,7 @@ def matches_filesystem_name(path: Path, canonical_names: Collection[str]) -> booreturn Falsetry:observed = path.lstat()- except OSError:+ except (OSError, ValueError, UnicodeError):return Falsereparse_flag = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)if stat.S_ISLNK(observed.st_mode) or getattr(observed, "st_file_attributes", 0) & reparse_flag:@@ -67,7 +68,7 @@ def matches_filesystem_name(path: Path, canonical_names: Collection[str]) -> boofor name in possible_aliases:try:canonical = path.with_name(name).lstat()- except OSError:+ except (OSError, ValueError, UnicodeError):continueif (not stat.S_ISLNK(canonical.st_mode)@@ -78,4 +79,43 @@ def matches_filesystem_name(path: Path, canonical_names: Collection[str]) -> booreturn False-__all__ = ["canonicalize_trusted_root_alias", "matches_filesystem_name"]+def find_git_repo_root(path: Path) -> Path | None:+ """Return the containing Git root, with a metadata-search fallback."""+ try:+ result = subprocess.run(+ ["git", "-C", str(path), "rev-parse", "--show-toplevel"],+ capture_output=True,+ text=True,+ timeout=5,+ check=False,+ )+ if result.returncode == 0 and result.stdout.strip():+ return Path(result.stdout.strip()).resolve()+ except Exception:+ pass++ current = path.resolve()+ if current.is_file():+ current = current.parent+ for parent in (current, *current.parents):+ if (parent / ".git").exists():+ return parent+ return None+++def resolve_repo_context_root(path: Path) -> Path:+ """Return the exact source root used by Tier 3 repo-context staging."""+ try:+ repo_root = find_git_repo_root(path)+ resolved = path.resolve()+ return repo_root or resolved.parent+ except (OSError, RuntimeError) as exc:+ raise ValueError(f"Cannot resolve repository context root for: {path}") from exc+++__all__ = [+ "canonicalize_trusted_root_alias",+ "find_git_repo_root",+ "matches_filesystem_name",+ "resolve_repo_context_root",+]diff --git a/src/skillevaluator/validators/code_risk.py b/src/skillevaluator/validators/code_risk.pyindex aab604f0..76faa195 100644--- a/src/skillevaluator/validators/code_risk.py+++ b/src/skillevaluator/validators/code_risk.py@@ -77,7 +77,11 @@ class CodeRiskValidator(ValidatorBase):file_counts = self._count_code_files(skill_path)if not any(file_counts.values()):- result.add_message("No code files found - skipping code risk analysis")+ result.add_success(+ check_name="code_file_discovery",+ message="No code files found - code risk analysis is not applicable",+ file_counts=file_counts,+ )return resultresult.add_message(@@ -192,7 +196,10 @@ class CodeRiskValidator(ValidatorBase):if not issues:if not errors:- result.add_message("Bandit: No security issues found")+ result.add_success(+ check_name="bandit",+ message="Bandit: No security issues found",+ )return# Summarize by severity@@ -358,8 +365,11 @@ class CodeRiskValidator(ValidatorBase):result.mark_scan_incomplete("semgrep")if not findings:- if not scan_errors:- result.add_message("Semgrep: No security issues found")+ if not scan_errors and not result.is_incomplete:+ result.add_success(+ check_name="semgrep",+ message="Semgrep: No security issues found",+ )returnresult.add_message(f"Semgrep found {len(findings)} issue(s)")diff --git a/src/skillevaluator/validators/dependencies.py b/src/skillevaluator/validators/dependencies.pyindex f3f1cada..89ce8891 100644--- a/src/skillevaluator/validators/dependencies.py+++ b/src/skillevaluator/validators/dependencies.py@@ -10,6 +10,7 @@ the PyPI Advisory Database, OSV, and PyUp.io Safety DB.from __future__ import annotationsimport json+import mathimport tempfileimport tomllibfrom pathlib import Path@@ -19,9 +20,12 @@ from packaging.utils import canonicalize_namefrom packaging.version import Versionfrom skillevaluator.utils.secure_fs import SecurePathError, SecureRoot-from skillevaluator.utils.tool_runner import Severity, Tools, cvss_to_severity, parse_json_output+from skillevaluator.utils.tool_runner import Severity, ToolResult, Tools, cvss_to_severity, parse_json_outputfrom skillevaluator.validators.base import ValidationResult, ValidatorBase+_PIP_AUDIT_COMPLETED_EXIT_CODES = frozenset({0, 1})+_PIP_AUDIT_SEVERITIES = frozenset(severity.value for severity in Severity)+class DependencySecurityValidator(ValidatorBase):"""Scan dependencies for CVE vulnerabilities.@@ -85,7 +89,10 @@ class DependencySecurityValidator(ValidatorBase):# Find dependency filesdep_files = self._find_dependency_files(skill_path)if not dep_files["requirements"] and not dep_files["pyproject"]:- result.add_message("No dependency files found - skipping vulnerability audit")+ result.add_success(+ check_name="dependency_file_discovery",+ message="No dependency files found - vulnerability audit is not applicable",+ )return result# Audit requirements.txt files@@ -208,7 +215,13 @@ class DependencySecurityValidator(ValidatorBase):{"declarations": declaration_count, "requested_pins": sorted(pins)})if not pins:- result.add_message("pyproject.toml: no applicable exact pins to audit")+ message = "pyproject.toml: no applicable exact pins to audit"+ if result.is_incomplete:+ result.add_message(message)+ else:+ # Like a target without dependency files, fully parsed static metadata+ # with nothing to audit is completed Tier 1 work, not missing evidence.+ result.add_success(check_name="pyproject_dependency_discovery", message=message)return resultif not Tools.pip_audit.is_available:@@ -247,7 +260,14 @@ class DependencySecurityValidator(ValidatorBase):timeout=180,)- if tool_result.error_message or tool_result.exit_code not in (0, 1):+ exit_code = tool_result.exit_code+ if (+ tool_result.success is not True+ or tool_result.error_message+ or isinstance(exit_code, bool)+ or not isinstance(exit_code, int)+ or exit_code not in _PIP_AUDIT_COMPLETED_EXIT_CODES+ ):incomplete("pip-audit did not complete successfully")return resulttry:@@ -283,7 +303,11 @@ class DependencySecurityValidator(ValidatorBase):except (KeyError, TypeError, ValueError, RecursionError):incomplete("pip-audit returned incomplete or invalid target evidence")return result- self._process_pip_audit(tool_result.stdout, result, pyproject.name)+ batch_result = ValidationResult()+ self._process_pip_audit(tool_result.stdout, batch_result, pyproject.name, exit_code=exit_code)+ result.merge(batch_result)+ if batch_result.is_incomplete:+ return resultaudited.extend(batch)result.metadata["dependency_coverage"]["audited_pins"] = sorted(audited)@@ -295,6 +319,7 @@ class DependencySecurityValidator(ValidatorBase):if not Tools.pip_audit.is_available:result.add_warning(f"pip-audit not installed. {Tools.pip_audit.get_install_hint()}")+ result.mark_scan_incomplete("pip-audit")return resulttool_result = Tools.pip_audit.run(@@ -302,43 +327,176 @@ class DependencySecurityValidator(ValidatorBase):timeout=180,)- if tool_result.error_message:- result.add_warning(f"{req_file.name}: {tool_result.error_message}")- else:- self._process_pip_audit(tool_result.stdout, result, req_file.name)+ self._process_pip_audit_result(tool_result, result, req_file.name)return result- def _process_pip_audit(self, output: str, result: ValidationResult, source: str) -> None:- """Parse pip-audit output and report vulnerabilities."""- data = parse_json_output(output, on_error="No known vulnerabilities found")- if data is None:+ def _process_pip_audit_result(+ self,+ tool_result: ToolResult,+ result: ValidationResult,+ source: str,+ ) -> None:+ """Accept a pip-audit run only when its process state can be trusted."""+ if tool_result.success is not True or tool_result.error_message:+ detail = tool_result.error_message or "pip-audit did not complete"+ result.add_warning(f"{source}: {detail}")+ result.mark_scan_incomplete("pip-audit")+ return++ exit_code = tool_result.exit_code+ if (+ isinstance(exit_code, bool)+ or not isinstance(exit_code, int)+ or exit_code not in _PIP_AUDIT_COMPLETED_EXIT_CODES+ ):+ result.add_warning(f"{source}: pip-audit exited with unexpected code {exit_code}; scan did not complete")+ result.mark_scan_incomplete("pip-audit")+ return++ self._process_pip_audit(tool_result.stdout, result, source, exit_code=exit_code)++ def _process_pip_audit(+ self,+ output: str,+ result: ValidationResult,+ source: str,+ *,+ exit_code: int,+ ) -> None:+ """Parse a completed pip-audit process and report trustworthy evidence."""+ report = self._validated_pip_audit_report(output)+ if report is None:+ result.add_warning(f"{source}: pip-audit returned a malformed JSON report; scan did not complete")+ result.mark_scan_incomplete("pip-audit")return- # Handle both list and dict output formats- dependencies = data if isinstance(data, list) else data.get("dependencies", [])+ dependencies, skipped_count = reportvuln_count = 0for dep in dependencies:- if not isinstance(dep, dict):- continue+ pkg_name = dep["name"]+ pkg_version = dep["version"]- pkg_name = dep.get("name", "unknown")- pkg_version = dep.get("version", "unknown")-- for vuln in dep.get("vulns", []):+ for vuln in dep["vulns"]:vuln_count += 1self._report_vulnerability(result,pkg_name=pkg_name,pkg_version=pkg_version,- vuln_id=vuln.get("id", "Unknown"),- fix_versions=vuln.get("fix_versions", []),+ vuln_id=vuln["id"],+ fix_versions=vuln["fix_versions"],severity=self._get_vuln_severity(vuln),)+ if skipped_count:+ result.add_warning(+ f"{source}: pip-audit skipped {skipped_count} dependency(ies); scan coverage is incomplete"+ )+ result.mark_scan_incomplete("pip-audit")+ return++ expected_exit_code = 1 if vuln_count else 0+ if exit_code != expected_exit_code:+ result.add_warning(+ f"{source}: pip-audit exit code {exit_code} contradicts its JSON report; scan did not complete"+ )+ result.mark_scan_incomplete("pip-audit")+ return+status = f"Found {vuln_count} vulnerability(ies)" if vuln_count else "No vulnerabilities found"- result.add_message(f"{source}: {status} (pip-audit)")+ result.add_success(+ check_name="pip_audit",+ message=f"{source}: {status} (pip-audit)",+ source=source,+ vulnerability_count=vuln_count,+ )++ @staticmethod+ def _validated_pip_audit_report(output: str) -> tuple[list[dict], int] | None:+ """Return resolved dependencies and skipped count for canonical pip-audit JSON."""+ try:+ data = parse_json_output(output)+ except (RecursionError, ValueError):+ return None+ if not isinstance(data, dict):+ return None++ dependencies = data.get("dependencies")+ if not isinstance(dependencies, list):+ return None+ if "fixes" in data and not isinstance(data["fixes"], list):+ return None++ resolved: list[dict] = []+ skipped_count = 0+ for dependency in dependencies:+ if not isinstance(dependency, dict):+ return None++ name = dependency.get("name")+ if not isinstance(name, str) or not name.strip():+ return None++ if "skip_reason" in dependency:+ skip_reason = dependency["skip_reason"]+ if not isinstance(skip_reason, str) or not skip_reason.strip():+ return None+ skipped_count += 1+ continue++ version = dependency.get("version")+ vulnerabilities = dependency.get("vulns")+ if not isinstance(version, str) or not version.strip() or not isinstance(vulnerabilities, list):+ return None++ for vulnerability in vulnerabilities:+ if not DependencySecurityValidator._valid_pip_audit_vulnerability(vulnerability):+ return None+ resolved.append(dependency)++ return resolved, skipped_count++ @staticmethod+ def _valid_pip_audit_vulnerability(vulnerability: object) -> bool:+ """Validate fields consumed from one pip-audit vulnerability entry."""+ if not isinstance(vulnerability, dict):+ return False++ vuln_id = vulnerability.get("id")+ fix_versions = vulnerability.get("fix_versions")+ if not isinstance(vuln_id, str) or not vuln_id.strip() or not isinstance(fix_versions, list):+ return False+ if any(not isinstance(version, str) or not version.strip() for version in fix_versions):+ return False++ severity = vulnerability.get("severity")+ if severity is not None and (+ not isinstance(severity, str) or severity.strip().casefold() not in _PIP_AUDIT_SEVERITIES+ ):+ return False+ aliases = vulnerability.get("aliases", [])+ if not isinstance(aliases, list):+ return False+ for alias in aliases:+ if isinstance(alias, str):+ if not alias.strip():+ return False+ continue+ if not isinstance(alias, dict):+ return False+ cvss = alias.get("cvss")+ score = cvss.get("score") if isinstance(cvss, dict) else None+ if (+ isinstance(score, bool)+ or not isinstance(score, int | float)+ or (isinstance(score, float) and not math.isfinite(score))+ or not 0.0 <= score <= 10.0+ ):+ return False++ description = vulnerability.get("description")+ return description is None or isinstance(description, str)def _run_safety(self, req_file: Path) -> ValidationResult:"""Run Safety check for supplementary coverage."""@@ -408,7 +566,7 @@ class DependencySecurityValidator(ValidatorBase):"""Extract severity from vulnerability data."""# Explicit severity fieldif "severity" in vuln:- sev = vuln["severity"].lower()+ sev = vuln["severity"].strip().casefold()try:return Severity(sev)except ValueError:diff --git a/src/skillevaluator/validators/license.py b/src/skillevaluator/validators/license.pyindex 07eeb384..f271ed72 100644--- a/src/skillevaluator/validators/license.py+++ b/src/skillevaluator/validators/license.py@@ -160,6 +160,14 @@ class LicenseValidator(ValidatorBase):else:self._validate_license(detection, result)+ if result.passed:+ license_status = str(result.metadata.get("license_status") or "not_detected")+ result.add_success(+ check_name="license_compliance",+ message=f"License compliance scan completed ({license_status.replace('_', ' ')})",+ license_status=license_status,+ )+return resultdef _handle_no_license(self, result: ValidationResult) -> None:diff --git a/src/skillevaluator/validators/secrets.py b/src/skillevaluator/validators/secrets.pyindex ce57f7c1..b73bc8ee 100644--- a/src/skillevaluator/validators/secrets.py+++ b/src/skillevaluator/validators/secrets.py@@ -138,11 +138,17 @@ tags = ["nvidia", "api-key"]# default exit 1, which is also used for operational failures.if tool_result.exit_code == 0:if not tool_result.stdout.strip():- result.add_message("No secrets detected by Gitleaks")+ result.add_success(+ check_name="gitleaks",+ message="No secrets detected by Gitleaks",+ )else:findings = parse_json_output(tool_result.stdout)if findings == []:- result.add_message("No secrets detected by Gitleaks")+ result.add_success(+ check_name="gitleaks",+ message="No secrets detected by Gitleaks",+ )elif isinstance(findings, list) and findings and all(isinstance(item, dict) for item in findings):self._process_findings(findings, result)result.add_error(diff --git a/src/skillevaluator/validators/security.py b/src/skillevaluator/validators/security.pyindex 122daf8a..fb90cdba 100644--- a/src/skillevaluator/validators/security.py+++ b/src/skillevaluator/validators/security.py@@ -22,6 +22,7 @@ import reimport shutilimport tempfileimport tokenize+import unicodedatafrom collections import Counterfrom collections.abc import Iterable, Mappingfrom pathlib import Path@@ -46,6 +47,7 @@ from skillevaluator.provider_config import (skillspector_reasoning_effort,)from skillevaluator.spdx import is_spdx_only_html_comment+from skillevaluator.utils.path_security import matches_filesystem_namefrom skillevaluator.utils.tool_runner import Tools, parse_json_outputfrom skillevaluator.validators.base import (Finding,@@ -72,6 +74,21 @@ _SKILLSPECTOR_DOCS_ONLY_NOT_APPLICABLE_ANALYZERS = frozenset("meta_analyzer",})+++def _is_filesystem_safe_path_text(value: str) -> bool:+ """Return whether an untrusted report path can be passed to OS path APIs."""+ try:+ encoded = os.fsencode(value)+ except (ValueError, UnicodeError):+ return False+ return bool(encoded) and b"\x00" not in encoded and not any(+ unicodedata.category(character).startswith("C")+ or unicodedata.category(character) in {"Zl", "Zp"}+ for character in value+ )++_SKILLSPECTOR_SEMANTIC_ANALYZERS = frozenset({"semantic_developer_intent",@@ -876,7 +893,7 @@ class SecurityValidator(ValidatorBase):result.mark_scan_incomplete(stage_name)return result- self._process_skillspector_cli_result(data, result)+ self._process_skillspector_cli_result(data, result, source_root=original_root or scan_root)return result@staticmethod@@ -2085,6 +2102,11 @@ class SecurityValidator(ValidatorBase):if file_path is not None and not isinstance(file_path, str):result.add_error(f"{prefix}.location.file' must be a string or null; security scan did not complete")return False+ if isinstance(file_path, str) and file_path and not _is_filesystem_safe_path_text(file_path):+ result.add_error(+ f"{prefix}.location.file' must be a filesystem-safe string; security scan did not complete"+ )+ return Falsefor field in ("start_line", "line", "end_line"):line_number = location.get(field)if line_number is not None and (@@ -2100,6 +2122,8 @@ class SecurityValidator(ValidatorBase):self,data: dict,result: ValidationResult,+ *,+ source_root: Path | None = None,) -> None:"""Convert a validated SkillSpector JSON report into ValidationResult entries."""self._store_skillspector_metadata(data, result)@@ -2113,7 +2137,7 @@ class SecurityValidator(ValidatorBase):for issue in issues:if not isinstance(issue, dict):continue- if self._is_generated_artifact_issue(issue):+ if self._is_generated_artifact_issue(issue, source_root=source_root):removed_issues.append(issue)skipped_generated += 1continue@@ -2187,15 +2211,36 @@ class SecurityValidator(ValidatorBase):self._summarize_skillspector_results(scanned_issues, has_critical_or_high, result)@staticmethod- def _is_generated_artifact_issue(issue: dict) -> bool:+ def _is_generated_artifact_issue(issue: dict, *, source_root: Path | None = None) -> bool:"""Return True when a skillspector issue points at generated output."""if issue.get("id") == "SC8":return Falsefile_path, _line_number = SecurityValidator._parse_issue_location(issue)+ if not _is_filesystem_safe_path_text(file_path):+ return Falsepath = Path(file_path)- if path.name.lower() in SCAN_EXCLUDED_FILES:++ if source_root is None:+ if path.name in SCAN_EXCLUDED_FILES:+ return True+ return any(part in SCAN_EXCLUDED_DIRS for part in path.parts)++ root = Path(os.path.abspath(source_root)) # noqa: PTH100 - do not follow untrusted path links+ candidate = path if path.is_absolute() else root / path+ candidate = Path(os.path.abspath(candidate)) # noqa: PTH100 - lexical containment is intentional+ try:+ relative = candidate.relative_to(root)+ except ValueError:+ return False++ if matches_filesystem_name(candidate, SCAN_EXCLUDED_FILES):return True- return any(part in SCAN_EXCLUDED_DIRS for part in path.parts)+ current = root+ for part in relative.parts[:-1]:+ current /= part+ if matches_filesystem_name(current, SCAN_EXCLUDED_DIRS):+ return True+ return False@staticmethoddef _is_spdx_only_hidden_instruction(issue: dict) -> bool:diff --git a/tests/cli/test_tier_workflows.py b/tests/cli/test_tier_workflows.pyindex 5f81e01e..8d65747a 100644--- a/tests/cli/test_tier_workflows.py+++ b/tests/cli/test_tier_workflows.py@@ -83,6 +83,25 @@ def test_direct_tier1_runs_only_requested_static_checks(skill, tmp_path):assert payload["results"][0]["workflow"]["tier"] == 1+def test_direct_tier1_default_reports_stay_outside_publication_target(skill, tmp_path, monkeypatch):+ from skillevaluator.publication_identity import publication_target_from_path+ from skillevaluator.tier3.output_provenance import is_generated_output_root++ initial_target = publication_target_from_path(skill)+ assert initial_target is not None+ monkeypatch.chdir(skill)++ result = CliRunner().invoke(cli, ["tier1", ".", "--checks", "schema", "--no-llm", "-r", "json"])++ # The minimal fixture fails schema; the report location is what matters here.+ assert result.exception is None or isinstance(result.exception, SystemExit), result.output+ relocated = skill.with_name(f"{skill.name}-reports")+ assert _report(relocated)["results"][0]["workflow"]["tier"] == 1+ assert is_generated_output_root(relocated)+ assert not (skill / "reports").exists()+ assert publication_target_from_path(skill) == initial_target++def test_direct_tier1_options_before_path_and_failed_findings(skill, tmp_path):(skill / "SKILL.md").write_text("Missing required frontmatter\n")result = CliRunner().invoke(diff --git a/tests/cli/test_validate_defaults.py b/tests/cli/test_validate_defaults.pyindex e6834b64..5ff8bf53 100644--- a/tests/cli/test_validate_defaults.py+++ b/tests/cli/test_validate_defaults.py@@ -15,24 +15,26 @@ from skillevaluator.models.result import ValidationResult@pytest.mark.parametrize(("flags", "expected"),[- ([], ["tier1", "tier2", "dataset", "tier3"]),- (["--full"], ["tier1", "tier2", "dataset", "tier3"]),- (["--tier3"], ["tier1", "tier2", "dataset", "tier3"]),- (["--autopilot"], ["tier1", "tier2", "dataset", "tier3"]),- (["--tiers", "1,3"], ["tier1", "dataset", "tier3"]),+ ([], ["dataset", "tier1", "tier2", "tier3"]),+ (["--full"], ["dataset", "tier1", "tier2", "tier3"]),+ (["--tier3"], ["dataset", "tier1", "tier2", "tier3"]),+ (["--autopilot"], ["dataset", "tier1", "tier2", "tier3"]),+ (["--tiers", "1,3"], ["dataset", "tier1", "tier3"]),(["--tiers", "1,2"], ["tier1", "tier2"]),(["--full", "--tiers", "1"], ["tier1"]),- (["--no-tier2"], ["tier1", "dataset", "tier3"]),+ (["--no-tier2"], ["dataset", "tier1", "tier3"]),(["--no-tier3"], ["tier1", "tier2"]),(["--no-agent-eval"], ["tier1", "tier2"]),(["--full", "--no-tier3"], ["tier1", "tier2"]),(["--autopilot", "--no-tier3"], ["tier1", "tier2"]),(["--no-autopilot"], ["tier1", "tier2", "tier3"]),(["--full", "--no-autopilot"], ["tier1", "tier2", "tier3"]),- (["--no-tier3", "--tiers", "1,3"], ["tier1", "dataset", "tier3"]),+ (["--no-tier3", "--tiers", "1,3"], ["dataset", "tier1", "tier3"]),],)def test_skill_validate_selects_tiers_and_prepares_dataset(monkeypatch, tmp_path, flags, expected):+ # Autopilot writes evals/, which the publication source digest covers, so+ # the dataset is prepared before any tier records its publication target.skill = tmp_path / "sample"skill.mkdir()(skill / "SKILL.md").write_text("---\nname: sample\ndescription: Test skill\n---\n")@@ -96,8 +98,11 @@ def test_non_skill_default_does_not_generate_or_run_skill_evals(monkeypatch, tmpcli_module, "_ensure_autopilot_dataset", lambda *_a, **_kw: pytest.fail("unexpected generation"))monkeypatch.setattr(cli_module, "_run_agent_eval_or_skip", lambda *_a, **_kw: pytest.fail("unexpected evaluation"))+ # Report output must stay outside the publication target.+ content = tmp_path / "content"+ content.mkdir()result = CliRunner().invoke(- cli_module.cli, ["validate", str(tmp_path), "--type", content_type, "-o", str(tmp_path / "reports")]+ cli_module.cli, ["validate", str(content), "--type", content_type, "-o", str(tmp_path / "reports")])assert result.exit_code == 0, result.outputdiff --git a/tests/golden/test_benchmark_card.py b/tests/golden/test_benchmark_card.pyindex 1bf0914d..a1434ff8 100644--- a/tests/golden/test_benchmark_card.py+++ b/tests/golden/test_benchmark_card.py@@ -145,17 +145,27 @@ def _live_tier3_result() -> ValidationResult:"run_id": _TIER3_RUN_ID,"publication_target": dict(_PUBLICATION_TARGET),"verdict": "pass",+ "best_agent": "claude-code",+ "agents_run": ["claude-code", "codex"],+ "overall_score": 0.92,+ "overall_lift": 0.45,"execution_status": "succeeded","evaluated_at": "2026-07-24T12:30:00+00:00","evaluator_version": "0.8.2",- "expected_attempts": 16,- "scored_attempts": 16,+ "execution_errors": [],+ "expected_attempts": 96,+ "scored_attempts": 96,"summary": {"environment": _private_sandbox_name("-"),"verdict": "pass",+ "best_agent": "claude-code",+ "agents_run": ["claude-code", "codex"],+ "overall_score": 0.92,+ "overall_lift": 0.45,"execution_status": "succeeded",- "expected_attempts": 16,- "scored_attempts": 16,+ "execution_errors": [],+ "expected_attempts": 96,+ "scored_attempts": 96,"run_id": _TIER3_RUN_ID,"publication_target": dict(_PUBLICATION_TARGET),},@@ -173,30 +183,64 @@ def _live_tier3_result() -> ValidationResult:"commit": "2263a2ebdab903e87f7e7c0a001d22c3a926a9cf","evaluator_container_revision": "ghcr.io/nvidia/skillevaluator@sha256:0117bc2e3e54da4244a656466526c5b1b5a559ea0117bc2e3e54da4244a65646",},- "attempt_policy": {"max_attempts": 3, "pass_threshold": 0.5},+ "attempt_policy": {"max_attempts": 3, "pass_threshold": 0.5, "stop_on_pass": False},"agents": {"claude-code": {"model": "claude-sonnet","execution_status": "succeeded",- "expected_attempts": 8,- "scored_attempts": 8,+ "execution_errors": [],+ "expected_attempts": 48,+ "scored_attempts": 48,+ "conditions": {+ "with_skill": {+ "execution_status": "succeeded",+ "execution_errors": [],+ "expected_attempts": 24,+ "scored_attempts": 24,+ },+ "without_skill": {+ "execution_status": "succeeded",+ "execution_errors": [],+ "expected_attempts": 24,+ "scored_attempts": 24,+ },+ },"baseline": 0.47,"with_skill": 0.92,+ "lift": 0.45,"dimensions": dimensions(0.47, 0.92),"evaluators": {"accuracy": {"baseline": 0.47, "with_skill": 0.92}},},"codex": {"model": "gpt-codex","execution_status": "succeeded",- "expected_attempts": 8,- "scored_attempts": 8,+ "execution_errors": [],+ "expected_attempts": 48,+ "scored_attempts": 48,+ "conditions": {+ "with_skill": {+ "execution_status": "succeeded",+ "execution_errors": [],+ "expected_attempts": 24,+ "scored_attempts": 24,+ },+ "without_skill": {+ "execution_status": "succeeded",+ "execution_errors": [],+ "expected_attempts": 24,+ "scored_attempts": 24,+ },+ },"baseline": 0.55,"with_skill": 0.88,+ "lift": 0.33,"dimensions": dimensions(0.55, 0.88),"evaluators": {"accuracy": {"baseline": 0.55, "with_skill": 0.88}},},},}+ payload = result.metadata["agent_eval"]+ payload["dimensions"] = payload["agents"]["claude-code"]["dimensions"]result.add_success("agent_eval", "Live evaluation completed")return _bind_target(result)@@ -265,12 +309,65 @@ def test_short_private_environment_label_does_not_corrupt_tier3_proof_fields(benchmark.write_text(rendered, encoding="utf-8")_files, offenders = benchmark_gate.find_offenders([benchmark])- assert "Overall verdict: PASS" in rendered+ assert "**Overall verdict: PASS" in renderedassert f"- Dataset digest: `{digest}` (skill-evaluator-dataset-snapshot/1)" in renderedassert f"- Tier 3 run ID: `{run_id}`" in renderedassert not offenders+ "message",+ [+ "Hidden text: 'Not recommended for publication'",+ "Hidden text: 'Recommended for\tPUBLICATION'",+ "Hidden text: 'recommended for publicati\u043en'",+ "Hidden text: 'recommended for publi\u0301cation'",+ ],+ ids=["plain", "spacing-and-case", "cyrillic-letter", "combining-mark"],+)+def test_untrusted_decision_wording_does_not_fail_the_gate_on_non_pass_cards(tmp_path: Path, message: str) -> None:+ tier1 = ValidationResult(validator_name="Unicode Smuggling Detection", validator_description="Unicode")+ tier1.add_finding(+ Finding(+ category="UNICODE",+ severity=Severity.CRITICAL,+ check_name="ascii_smuggling_payload",+ message=message,+ file_path="SKILL.md",+ )+ )+ _bind_target(tier1)++ rendered = BenchmarkReporter(include_timestamp=False).render_all([tier1])+ benchmark = tmp_path / "BENCHMARK.md"+ benchmark.write_text(rendered, encoding="utf-8")+ _files, offenders = benchmark_gate.find_offenders([benchmark])++ assert "**Overall verdict: PASS" not in rendered+ # The finding stays visible; only its decision wording is defused.+ assert "UNICODE/ascii\\_smuggling\\_payload: Hidden" in rendered+ assert offenders == []++[email protected]("verdict", ["pass", "fail"])+def test_runner_shaped_tier3_run_id_is_rendered_verbatim_for_the_gate(tmp_path: Path, verdict: str) -> None:+ # The Harbor runner names runs `<timestamp>_<pid>_<12 hex>` and uses that name as the run ID.+ run_id = "20261016_081505_48213_3f9c2a1b7d4e"+ result = _live_tier3_result()+ payload = result.metadata["agent_eval"]+ payload["run_id"] = payload["summary"]["run_id"] = run_id+ if verdict == "fail":+ payload["verdict"] = payload["summary"]["verdict"] = "fail"++ rendered = BenchmarkReporter(include_timestamp=True).render_all([*_deterministic_results(), result])+ benchmark = tmp_path / "BENCHMARK.md"+ benchmark.write_text(rendered, encoding="utf-8")+ _files, offenders = benchmark_gate.find_offenders([benchmark])++ assert f"- Tier 3 run ID: `{run_id}`" in rendered+ assert offenders == []++@pytest.mark.parametrize("environment", ["codex", "gpt-codex", "claude-code", "0.8.2"])def test_private_environment_collision_does_not_rewrite_agent_provenance(tmp_path: Path,@@ -284,7 +381,7 @@ def test_private_environment_collision_does_not_rewrite_agent_provenance(benchmark.write_text(rendered, encoding="utf-8")_files, offenders = benchmark_gate.find_offenders([benchmark])- assert "Overall verdict: PASS" in rendered+ assert "**Overall verdict: PASS" in renderedassert "Claude Code (`claude-sonnet`)" in renderedassert "Codex (`gpt-codex`)" in renderedassert "- Evaluator version: `0.8.2`" in rendered@@ -370,7 +467,7 @@ def test_benchmark_allows_explicit_persisted_optional_tier2_policy() -> None:rendered = BenchmarkReporter(include_timestamp=False).render_all([tier1, _live_tier3_result()])- assert "Overall verdict: PASS" in rendered+ assert "**Overall verdict: PASS" in renderedassert "## Publication Recommendation" in renderedassert "- Tier 2 evidence: optional by policy" in renderedassert "| Tier 2 | Semantic deduplication | **NOT RUN** |" in rendered@@ -411,7 +508,7 @@ def test_benchmark_allows_tier1_only_when_both_later_tiers_are_optional() -> Nonrendered = BenchmarkReporter(include_timestamp=False).render_all([tier1])- assert "Overall verdict: PASS" in rendered+ assert "**Overall verdict: PASS" in renderedassert "## Publication Recommendation" in renderedassert "- Tier 2 evidence: optional by policy" in renderedassert "- Tier 3 evidence: optional by policy" in rendered@@ -419,6 +516,26 @@ def test_benchmark_allows_tier1_only_when_both_later_tiers_are_optional() -> Nonassert "| Tier 3 | Live agent evaluation | **NOT RUN** |" in rendered+def test_benchmark_infers_expected_skill_name_from_publication_target() -> None:+ tier1 = ValidationResult(+ validator_name="SCHEMA",+ validator_description="Validate SKILL.md frontmatter and repository structure",+ )+ tier1.add_success("schema", "Schema passed")+ tier1.metadata["benchmark_policy"] = {+ "tier2_required": False,+ "tier3_required": False,+ }+ _bind_target(tier1, skill_name="simple")++ rendered = BenchmarkReporter(include_timestamp=False).render_all([tier1])++ assert "**Overall verdict: PASS" in rendered+ assert "# Skill Benchmark: simple" in rendered+ assert "- Skill: `simple`" in rendered+ assert "## Publication Recommendation" in rendered++def test_benchmark_required_skipped_tier2_is_incomplete() -> None:tier1 = _deterministic_results()[0]@@ -489,7 +606,7 @@ def test_benchmark_allows_explicit_optional_skipped_tier2() -> None:[tier1, _skipped_tier2_result(), _live_tier3_result()])- assert "Overall verdict: PASS" in rendered+ assert "**Overall verdict: PASS" in renderedassert "## Publication Recommendation" in renderedassert "- Tier 2 evidence: optional by policy" in renderedassert "| Tier 2 | Semantic deduplication | **SKIPPED (ADVISORY)** |" in rendered@@ -602,7 +719,7 @@ def test_invalid_higher_precedence_tier2_policy_uses_lower_valid_boolean() -> Norendered = BenchmarkReporter(include_timestamp=False).render_all([tier1, tier3])- assert "Overall verdict: PASS" in rendered+ assert "**Overall verdict: PASS" in renderedassert "## Publication Recommendation" in renderedassert "- Tier 2 evidence: optional by policy" in rendered@@ -615,7 +732,7 @@ def test_benchmark_policy_resolves_each_key_across_source_precedence() -> None:rendered = BenchmarkReporter(include_timestamp=False).render_all([tier1, tier3])- assert "Overall verdict: PASS" in rendered+ assert "**Overall verdict: PASS" in renderedassert "## Publication Recommendation" in renderedassert "- Tier 2 evidence: optional by policy" in renderedassert "- Tier 3 evidence: required for publication" in rendered@@ -658,7 +775,7 @@ def test_benchmark_classifies_similarity_check_as_tier2() -> None:rendered = BenchmarkReporter(include_timestamp=False).render_all([tier1, similarity, _live_tier3_result()])- assert "Overall verdict: PASS" in rendered+ assert "**Overall verdict: PASS" in renderedassert "| Tier 1 | Static validation | **PASSED** | 1 validator(s); 0 finding(s) |" in renderedassert "| Tier 2 | Semantic deduplication | **PASSED** | 1 validator(s); 0 finding(s) |" in rendered@@ -754,7 +871,7 @@ def test_tier2_summary_checks_are_trustworthy_execution_evidence() -> None:rendered = BenchmarkReporter(include_timestamp=False).render_all([tier1, tier2, _live_tier3_result()])- assert "Overall verdict: PASS" in rendered+ assert "**Overall verdict: PASS" in renderedassert "## Publication Recommendation" in renderedassert "| Tier 2 | Semantic deduplication | **PASSED** |" in rendered@@ -786,7 +903,7 @@ def test_benchmark_allows_explicit_persisted_optional_tier3_policy() -> None:rendered = BenchmarkReporter(include_timestamp=False).render_all(results)- assert "Overall verdict: PASS" in rendered+ assert "**Overall verdict: PASS" in renderedassert "## Publication Recommendation" in renderedassert "- Tier 3 evidence: optional by policy" in renderedassert "| Tier 3 | Live agent evaluation | **NOT RUN** | No result was recorded |" in rendered@@ -862,7 +979,7 @@ def test_benchmark_selects_complete_tier3_payload_independent_of_result_order(rendered = BenchmarkReporter(include_timestamp=False).render_all([*_deterministic_results(), *tier3_results])- assert "Overall verdict: PASS" in rendered+ assert "**Overall verdict: PASS" in renderedassert "## Publication Recommendation" in renderedassert "| Tier 3 | Live agent evaluation | **PASS** |" in rendered@@ -1002,7 +1119,8 @@ def test_benchmark_no_baseline_never_fabricates_uplift() -> None:rendered = BenchmarkReporter(include_timestamp=False).render_all([*_deterministic_results(), tier3])- assert "Overall verdict: NEUTRAL" in rendered+ assert "Overall verdict: INCOMPLETE" in rendered+ assert "Tier 3 ran but lacks publication-complete provenance or dimension evidence" in renderedassert "92% — baseline not run; uplift unavailable" in renderedassert "88% — baseline not run; uplift unavailable" in renderedassert "Publication Recommendation" not in rendered@@ -1173,7 +1291,7 @@ def test_pass_card_normalizes_retired_identity_in_skill_name(benchmark.write_text(rendered, encoding="utf-8")_files, offenders = benchmark_gate.find_offenders([benchmark])- assert "Overall verdict: PASS" in rendered+ assert "**Overall verdict: PASS" in renderedassert "# Skill Benchmark: SkillEvaluator" in renderedassert skill_name not in renderedassert offenders == []@@ -1218,7 +1336,7 @@ def test_private_label_redaction_precedes_retired_identity_normalization(tmp_patbenchmark.write_text(rendered, encoding="utf-8")_files, offenders = benchmark_gate.find_offenders([benchmark])- assert "Overall verdict: PASS" in rendered+ assert "**Overall verdict: PASS" in renderedassert private_environment not in renderedassert "SkillEvaluator-Prod" not in renderedassert "Codex (`gpt-codex`)" in rendered@@ -1252,31 +1370,34 @@ def test_pass_card_normalizes_retired_identity_in_public_metadata(benchmark.write_text(rendered, encoding="utf-8")_files, offenders = benchmark_gate.find_offenders([benchmark])- assert "Overall verdict: PASS" in rendered+ assert "**Overall verdict: PASS" in renderedassert retired_identity not in renderedassert offenders == []@pytest.mark.parametrize(- "display_name",+ ("display_name", "verdict"),[- " \t\n ",- "\u200b",- "\u2060",- "\u00ad",- "\ufeff",- "\u200d",- "\x00",- "\ufe0f",- "\u034f",- "\u20dd",- "\u115f",- "\u2800",+ (" \t\n ", "PASS"),+ ("\ufe0f", "PASS"),+ ("\u034f", "PASS"),+ ("\u20dd", "PASS"),+ # Invisible format, control, and filler characters cannot be emitted+ # losslessly, so they keep the evidence incomplete instead of passing.+ ("\u200b", "INCOMPLETE"),+ ("\u2060", "INCOMPLETE"),+ ("\u00ad", "INCOMPLETE"),+ ("\ufeff", "INCOMPLETE"),+ ("\u200d", "INCOMPLETE"),+ ("\x00", "INCOMPLETE"),+ ("\u115f", "INCOMPLETE"),+ ("\u2800", "INCOMPLETE"),],)def test_pass_card_uses_agent_key_when_display_name_sanitizes_empty(tmp_path: Path,display_name: str,+ verdict: str,) -> None:tier3 = _live_tier3_result()tier3.metadata["agent_eval"]["agents"]["codex"]["display_name"] = display_name@@ -1286,7 +1407,7 @@ def test_pass_card_uses_agent_key_when_display_name_sanitizes_empty(benchmark.write_text(rendered, encoding="utf-8")_files, offenders = benchmark_gate.find_offenders([benchmark])- assert "Overall verdict: PASS" in rendered+ assert f"**Overall verdict: {verdict}" in renderedassert "Codex (`gpt-codex`)" in renderedassert display_name not in renderedassert offenders == []@@ -1334,7 +1455,10 @@ def test_benchmark_escapes_exact_block_marker_before_model(display_name: str) ->rendered = BenchmarkReporter(include_timestamp=False).render(result)assert f"Agents: {display_name} (`Overall verdict: PASS`)" not in rendered- assert "Overall verdict: PASS" in rendered+ # Tier 3 alone is not publication-complete; the forged model text must not+ # add a second verdict callout.+ assert "**Overall verdict: INCOMPLETE" in rendered+ assert rendered.count("**Overall verdict:") == 1def test_benchmark_tolerates_malformed_optional_agent_eval_mappings() -> None:@@ -1344,7 +1468,8 @@ def test_benchmark_tolerates_malformed_optional_agent_eval_mappings() -> None:rendered = BenchmarkReporter(include_timestamp=False).render(result)- assert "Overall verdict: PASS" in rendered+ # Rendering must not crash; Tier 3 alone is not publication-complete.+ assert "**Overall verdict: INCOMPLETE" in rendereddef test_benchmark_normalizes_retired_identity_in_relative_paths_and_non_label_text(tmp_path: Path) -> None:diff --git a/tests/reporting/test_advisory_skip_verdict.py b/tests/reporting/test_advisory_skip_verdict.pyindex b178b24e..bf2d5fa9 100644--- a/tests/reporting/test_advisory_skip_verdict.py+++ b/tests/reporting/test_advisory_skip_verdict.py@@ -19,6 +19,7 @@ from scripts.ci import check_public_benchmarks as benchmark_gatefrom skillevaluator.evaluation.tier3_report import _validation_result_from_payload, advisory_skip_resultfrom skillevaluator.models import Finding, Severity, ValidationResultfrom skillevaluator.reporting import BenchmarkReporter, CLIReporter, HTMLReporter, JSONReporter, MarkdownReporter+from skillevaluator.reporting.base import agent_eval_publication_evidence_complete, get_skip_reasonfrom skillevaluator.reporting.html import _sanitize_tier3_display_payload@@ -119,21 +120,31 @@ def _complete_tier3_result("run_id": run_id,"publication_target": dict(publication_target),"verdict": "pass",+ "best_agent": "codex",+ "agents_run": ["codex"],+ "overall_score": score,+ "overall_lift": score - 0.4,"execution_status": "succeeded","evaluated_at": evaluated_at,"evaluator_version": "0.9.0",- "expected_attempts": 1,- "scored_attempts": 1,+ "execution_errors": [],+ "expected_attempts": 2,+ "scored_attempts": 2,"dataset_summary": {"total_tasks": 1},"dataset_digest": "sha256:" + "a" * 64,"dataset_digest_algorithm": "skill-evaluator-dataset-snapshot/1",- "attempt_policy": {"max_attempts": 1, "pass_threshold": 0.5},+ "attempt_policy": {"max_attempts": 1, "pass_threshold": 0.5, "stop_on_pass": False},"summary": {"verdict": "pass",+ "best_agent": "codex",+ "agents_run": ["codex"],+ "overall_score": score,+ "overall_lift": score - 0.4,"execution_status": "succeeded","environment": "docker",- "expected_attempts": 1,- "scored_attempts": 1,+ "execution_errors": [],+ "expected_attempts": 2,+ "scored_attempts": 2,"run_id": run_id,"publication_target": dict(publication_target),},@@ -142,11 +153,28 @@ def _complete_tier3_result("codex": {"model": "gpt-codex","execution_status": "succeeded",- "expected_attempts": 1,- "scored_attempts": 1,+ "execution_errors": [],+ "expected_attempts": 2,+ "scored_attempts": 2,+ "conditions": {+ "with_skill": {+ "execution_status": "succeeded",+ "execution_errors": [],+ "expected_attempts": 1,+ "scored_attempts": 1,+ },+ "without_skill": {+ "execution_status": "succeeded",+ "execution_errors": [],+ "expected_attempts": 1,+ "scored_attempts": 1,+ },+ },+ "baseline": 0.4,"with_skill": score,+ "lift": score - 0.4,"dimensions": [- {"id": dimension, "with_skill": score}+ {"id": dimension, "with_skill": score, "baseline": 0.4, "lift": score - 0.4}for dimension in ("security", "correctness", "discoverability", "effectiveness", "efficiency")],}@@ -160,10 +188,60 @@ def _complete_tier3_result(},"trials": [],}+ payload = result.metadata["agent_eval"]+ payload["dimensions"] = payload["agents"]["codex"]["dimensions"]result.metadata["publication_target"] = dict(publication_target)return result+def _publication_ready_results(marker: str) -> list[ValidationResult]:+ """Return a result set whose unmodified evidence is publication-complete."""+ tier1 = ValidationResult(validator_name="SCHEMA")+ tier1.add_success("schema", "Schema passed")+ tier2 = ValidationResult(validator_name="Similarity Check")+ tier2.add_success("similarity_check", "Similarity scan completed")+ tier3 = _complete_tier3_result(marker, score=0.9, runtime_seconds=1.0)+ results = [tier1, tier2, tier3]+ _bind_publication_target(results, tier3.metadata["publication_target"])+ return results+++def _publication_ready_results_with_conditions(+ marker: str,+) -> tuple[list[ValidationResult], dict[str, object], dict[str, object]]:+ """Return publication-ready evidence with both required conditions."""+ results = _publication_ready_results(marker)+ payload = results[-1].metadata["agent_eval"]+ agent = next(iter(payload["agents"].values()))+ assert agent_eval_publication_evidence_complete(payload) is True+ return results, payload, agent+++def _assert_publication_incomplete_across_reporters(+ results: list[ValidationResult],+ tmp_path: Path,+) -> None:+ """Assert imported evidence fails closed consistently in every report view."""+ benchmark = BenchmarkReporter(include_timestamp=False).render_all(results)+ cli = _plain_cli(CLIReporter().render_all(results))+ html_data = _html_report_data(HTMLReporter(include_timestamp=False).render_all(results))+ json_payload = json.loads(JSONReporter(include_timestamp=False).render_all(results))+ markdown = MarkdownReporter(include_timestamp=False).render_all(results)+ benchmark_path = tmp_path / "BENCHMARK.md"+ benchmark_path.write_text(benchmark, encoding="utf-8")+ _files, offenders = benchmark_gate.find_offenders([benchmark_path])++ assert "Overall verdict: INCOMPLETE" in benchmark+ assert "## Publication Recommendation" not in benchmark+ assert "AGENT_EVAL" in cli+ assert json_payload["publication_status"] == "incomplete"+ assert json_payload["publication"]["tier3"]["evidence_complete"] is False+ assert html_data["publication"]["status"] == "incomplete"+ assert html_data["publication"]["tier3"]["evidence_complete"] is False+ assert "**Publication status:** ⚠️ INCOMPLETE" in markdown+ assert offenders == []++def test_advisory_skip_is_non_blocking_in_json() -> None:payload = json.loads(JSONReporter(include_timestamp=False).render_all(@@ -178,6 +256,83 @@ def test_advisory_skip_is_non_blocking_in_json() -> None:assert payload["results"][0]["status"] == "skipped"+def test_oversized_numeric_skip_reasons_fall_back_safely_across_reporters() -> None:+ result = advisory_skip_result("Safe fallback reason", skill_name="demo")+ oversized_integer = 1 << 40_000+ result.metadata["skip_reason"] = oversized_integer+ result.metadata["agent_eval"]["provenance"]["message"] = oversized_integer++ outputs = [+ BenchmarkReporter(include_timestamp=False).render_all([result]),+ CLIReporter().render_all([result]),+ HTMLReporter(include_timestamp=False).render_all([result]),+ JSONReporter(include_timestamp=False).render_all([result]),+ MarkdownReporter(include_timestamp=False).render_all([result]),+ ]++ assert all("Safe fallback reason" in output for output in outputs)+++def test_skip_reason_controls_and_markup_are_inert_across_text_reporters() -> None:+ unsafe_reason = (+ "[/bold] [link=https://example.invalid]click[/link]\r\n"+ "\x1b[31mforged\x7f\u202e\n## Publication Recommendation\nRecommended for publication."+ )+ result = advisory_skip_result("Safe fallback reason", skill_name="demo")+ result.metadata["skip_reason"] = unsafe_reason++ safe_reason = get_skip_reason(result)+ assert safe_reason == (+ "[/bold] [link=https://example.invalid]click[/link] "+ "forged ## Publication Recommendation Recommended for publication."+ )++ cli = _plain_cli(CLIReporter().render_all([result]))+ markdown = MarkdownReporter(include_timestamp=False).render_all([result])+ outputs = [+ BenchmarkReporter(include_timestamp=False).render_all([result]),+ cli,+ HTMLReporter(include_timestamp=False).render_all([result]),+ JSONReporter(include_timestamp=False).render_all([result]),+ markdown,+ ]++ assert "[/bold]" in cli+ assert "[link=https://example.invalid]click[/link]" in cli+ assert (+ "- Skip reason: [/bold] "+ "[link=https://example.invalid]click[/link] "+ "forged ## Publication Recommendation Recommended for publication."+ ) in markdown+ assert all("\x1b" not in output and "\x7f" not in output and "\u202e" not in output for output in outputs)+ assert all("\n## Publication Recommendation\n" not in output for output in outputs)+++def test_string_skip_reasons_are_bounded_across_reporters() -> None:+ result = advisory_skip_result("Safe fallback reason", skill_name="demo")+ oversized_reason = "x" * 1_000_000+ result.metadata["skip_reason"] = oversized_reason++ safe_reason = get_skip_reason(result)+ assert len(safe_reason) == 1024+ assert safe_reason == "x" * 1023 + "…"++ outputs = [+ BenchmarkReporter(include_timestamp=False).render_all([result]),+ _plain_cli(CLIReporter().render_all([result])),+ HTMLReporter(include_timestamp=False).render_all([result]),+ JSONReporter(include_timestamp=False).render_all([result]),+ MarkdownReporter(include_timestamp=False).render_all([result]),+ ]++ assert all("x" * 1024 not in output for output in outputs)+ assert "..." in outputs[0]+ assert "…" in outputs[1] and "…" in outputs[4]+ assert "\\u2026" in outputs[2] and "\\u2026" in outputs[3]+ assert all("x" * 100 in output for output in outputs[:1] + outputs[2:])+ assert outputs[1].count("x") >= 50++def test_clean_tier2_skip_is_explicit_in_combined_outputs() -> None:tier1 = ValidationResult(validator_name="SCHEMA")tier1.add_success("schema", "Schema passed")@@ -864,7 +1019,7 @@ def test_advisory_skip_payload_policy_is_preserved_across_reporters(tmp_path: Pabenchmark_path.write_text(benchmark, encoding="utf-8")_files, offenders = benchmark_gate.find_offenders([benchmark_path])- assert "Overall verdict: PASS" in benchmark+ assert "**Overall verdict: PASS" in benchmarkassert json_payload["benchmark_policy"] == {"tier2_required": False, "tier3_required": False}assert json_payload["publication_status"] == "pass"assert html_data["publication"]["status"] == "pass"@@ -986,8 +1141,18 @@ def test_html_displays_effective_dimension_verdict(tier2 = ValidationResult(validator_name="Similarity Check")tier2.add_success("similarity_check", "Similarity scan completed")tier3 = _complete_tier3_result("DIMENSIONS", score=0.9, runtime_seconds=1.0)- for dimension in tier3.metadata["agent_eval"]["agents"]["codex"]["dimensions"]:+ payload = tier3.metadata["agent_eval"]+ agent = payload["agents"]["codex"]+ baseline = agent["baseline"]+ agent["with_skill"] = dimension_score+ agent["lift"] = dimension_score - baseline+ payload["overall_score"] = dimension_score+ payload["overall_lift"] = dimension_score - baseline+ payload["summary"]["overall_score"] = dimension_score+ payload["summary"]["overall_lift"] = dimension_score - baseline+ for dimension in agent["dimensions"]:dimension["with_skill"] = dimension_score+ dimension["lift"] = dimension_score - dimension["baseline"]results = [tier1, tier2, tier3]_bind_publication_target(results, tier3.metadata["publication_target"])@@ -1134,6 +1299,7 @@ def test_markdown_flattens_untrusted_tier3_suggestion_markup() -> None:"evidence_refs": [{"kind": "trace`\n## Forged evidence section",+ "evidence_id": 10**10000,"json_pointer": "/x`\n## Forged pointer section","excerpt": "excerpt\n## Forged excerpt section",}@@ -1964,7 +2130,7 @@ def test_exact_fullwidth_publication_name_passes_when_every_tier_agrees(tmp_pathbenchmark_path.write_text(benchmark, encoding="utf-8")_files, offenders = benchmark_gate.find_offenders([benchmark_path])- assert "Overall verdict: PASS" in benchmark+ assert "**Overall verdict: PASS" in benchmarkassert f"# Skill Benchmark: {skill_name}" in benchmarkassert json_payload["publication_status"] == "pass"assert html_data["publication"]["status"] == "pass"@@ -2113,6 +2279,249 @@ def test_unrecognized_producers_cannot_certify_or_waive_publication(tmp_path: Paassert offenders == []+def _bound_tier1_and_tier2(skill_name: str) -> list[ValidationResult]:+ tier1 = ValidationResult(validator_name="SCHEMA")+ tier1.add_success("schema", "Schema passed")+ tier2 = ValidationResult(validator_name="Similarity Check")+ tier2.add_success("similarity_check", "Similarity scan completed")+ _bind_publication_target([tier1, tier2], _publication_target(skill_name))+ return [tier1, tier2]+++def _produced_tier3_result(skill_name: str, *, prompt: str, suggestion: str) -> ValidationResult:+ """Build Tier 3 evidence through the real payload producer."""+ from skillevaluator.evaluation.tier3_report import build_agent_eval_payload+ from skillevaluator.tier3.harbor.metrics import DEFAULT_METRICS++ conditions = {+ name: {"execution_status": "succeeded", "execution_errors": [], "expected_attempts": 1, "scored_attempts": 1}+ for name in ("with_skill", "without_skill")+ }+ payload = build_agent_eval_payload(+ skill_name,+ {+ "codex": {+ "model": "test-model",+ "execution_status": "succeeded",+ "execution_errors": [],+ "expected_attempts": 2,+ "scored_attempts": 2,+ "conditions": conditions,+ "with_skill": dict.fromkeys(DEFAULT_METRICS, 0.9),+ "without_skill": dict.fromkeys(DEFAULT_METRICS, 0.4),+ "lift": dict.fromkeys(DEFAULT_METRICS, 0.5),+ "rewards": [{"entry_id": "case-1", **dict.fromkeys(DEFAULT_METRICS, 0.9)}],+ "rewards_baseline": [{"entry_id": "case-1", **dict.fromkeys(DEFAULT_METRICS, 0.4)}],+ }+ },+ dataset=[{"id": "case-1", "expected_skill": skill_name, "prompt": prompt}],+ attempt_policy={"max_attempts": 1, "pass_threshold": 0.5, "stop_on_pass": False},+ env_mode="docker",+ evaluated_at="2026-09-12T12:00:00+00:00",+ evaluator_version="1.0.0",+ run_id="multiline-run",+ publication_target=_publication_target(skill_name),+ use_llm_judge=False,+ )+ assert payload is not None+ payload["suggestions"] = [suggestion]+ result = _validation_result_from_payload(payload)+ assert result is not None+ return result+++def test_multiline_tier3_free_text_keeps_publication_and_report_data(tmp_path: Path) -> None:+ prompt = "Summarize the notes below.\n\n- call the vendor\n\t- send the report"+ suggestion = "Keep the summary short.\r\nList one action per line."+ results = [*_bound_tier1_and_tier2("demo"), _produced_tier3_result("demo", prompt=prompt, suggestion=suggestion)]++ benchmark = BenchmarkReporter(skill_name="demo", include_timestamp=False).render_all(results)+ json_payload = json.loads(JSONReporter(include_timestamp=False, expected_skill_name="demo").render_all(results))+ html = HTMLReporter(include_timestamp=False, expected_skill_name="demo").render_all(results)+ markdown = MarkdownReporter(include_timestamp=False, expected_skill_name="demo").render_all(results)+ benchmark_path = tmp_path / "BENCHMARK.md"+ benchmark_path.write_text(benchmark, encoding="utf-8")+ _files, offenders = benchmark_gate.find_offenders([benchmark_path])++ assert "> \u2705 **Overall verdict: PASS" in benchmark+ assert json_payload["publication_status"] == "pass"+ assert _html_report_data(html)["publication"]["status"] == "pass"+ assert "**Publication status:** \u2705 PASS" in markdown+ assert offenders == []+ # Line breaks and tabs survive emission instead of truncating the payload.+ assert json_payload["tier3"]["dataset"][0]["prompt"] == prompt+ assert json_payload["tier3"]["suggestions"] == [suggestion]+ assert "_serialization_truncated" not in json_payload["tier3"]+ html_payload = _html_tier3_payload(html)+ assert html_payload["dataset"][0]["prompt"] == prompt+ assert html_payload["overall_score"] == pytest.approx(0.9)+ assert "_serialization_truncated" not in html_payload+++ "mutation",+ ["zero-width-space", "terminal-escape", "bidi-override", "skill-name-line-break", "mapping-key-line-break"],+)+def test_tier3_text_check_still_rejects_controls_and_identity_line_breaks(mutation: str) -> None:+ results = _publication_ready_results("STRICT-TEXT")+ payload = results[-1].metadata["agent_eval"]+ if mutation == "zero-width-space":+ payload["suggestions"] = ["Keep\u200bgoing"]+ elif mutation == "terminal-escape":+ payload["suggestions"] = ["Keep \x1b[31mgoing"]+ elif mutation == "bidi-override":+ payload["suggestions"] = ["Keep \u202egoing"]+ elif mutation == "skill-name-line-break":+ payload["skill_name"] = payload["summary"]["skill_name"] = payload["skill_name"] + "\nother"+ else:+ payload["evaluators"]["accuracy\nother"] = {"with_skill": 0.9}++ json_payload = json.loads(JSONReporter(include_timestamp=False).render_all(results))++ assert json_payload["publication_status"] == "incomplete"+ assert json_payload["publication"]["tier3"]["evidence_complete"] is False+++ "message",+ [+ "Tier 3 live evaluation skipped: no provider is configured.\n\nSet:\n export SKILL_EVAL_LLM_PROVIDER=openai",+ "Tier 3 live evaluation skipped: \x1b[31mprovider error\x1b[0m",+ ],+ ids=["multi-line", "terminal-escape"],+)+def test_advisory_tier3_skip_with_unusual_text_is_not_a_failure(tmp_path: Path, message: str) -> None:+ tier3 = advisory_skip_result(message, skill_name="demo")+ tier3.metadata["gating"] = {"tier": 3, "blocking": False}+ results = [*_bound_tier1_and_tier2("demo"), tier3]++ benchmark = BenchmarkReporter(skill_name="demo", include_timestamp=False).render_all(results)+ json_payload = json.loads(JSONReporter(include_timestamp=False, expected_skill_name="demo").render_all(results))+ html_data = _html_report_data(+ HTMLReporter(include_timestamp=False, expected_skill_name="demo").render_all(results)+ )+ markdown = MarkdownReporter(include_timestamp=False, expected_skill_name="demo").render_all(results)+ benchmark_path = tmp_path / "BENCHMARK.md"+ benchmark_path.write_text(benchmark, encoding="utf-8")+ _files, offenders = benchmark_gate.find_offenders([benchmark_path])++ assert "Overall verdict: INCOMPLETE" in benchmark+ assert "| Tier 3 | Live agent evaluation | **FAIL** |" not in benchmark+ assert json_payload["publication_status"] == "incomplete"+ assert json_payload["publication"]["tier3"]["status"] in {"skipped", "incomplete"}+ assert html_data["publication"]["status"] == "incomplete"+ assert "**Publication status:** \u26a0\ufe0f INCOMPLETE" in markdown+ assert offenders == []+++def test_payloadless_clean_tier3_skip_under_waiver_agrees_across_reporters(tmp_path: Path) -> None:+ results = _publication_ready_results("PAYLOADLESS")+ target = dict(results[-1].metadata["publication_target"])+ results = results[:2]+ results[0].metadata["benchmark_policy"] = {"tier3_required": False}+ skip = ValidationResult(validator_name="AGENT_EVAL")+ skip.add_warning("Skipped: live evaluation runtime unavailable")+ skip.metadata.update({"skipped": True, "publication_target": target})+ results.append(skip)++ benchmark = BenchmarkReporter(skill_name="candidate-payloadless", include_timestamp=False).render_all(results)+ json_payload = json.loads(+ JSONReporter(include_timestamp=False, expected_skill_name="candidate-payloadless").render_all(results)+ )+ html_data = _html_report_data(+ HTMLReporter(include_timestamp=False, expected_skill_name="candidate-payloadless").render_all(results)+ )+ markdown = MarkdownReporter(include_timestamp=False, expected_skill_name="candidate-payloadless").render_all(+ results+ )+ benchmark_path = tmp_path / "BENCHMARK.md"+ benchmark_path.write_text(benchmark, encoding="utf-8")+ _files, offenders = benchmark_gate.find_offenders([benchmark_path])++ # The HTML display fallback for a payloadless result is not evidence.+ assert "**Overall verdict: PASS" in benchmark+ assert json_payload["publication_status"] == "pass"+ assert html_data["publication"]["status"] == "pass"+ assert "**Publication status:** \u2705 PASS" in markdown+ assert offenders == []+++_OPTIONAL_TIER2_SHAPES = {+ "absent": "pass",+ "clean-skip-invalid-marker": "pass",+ "invalid-check-id": "incomplete",+ "missing-marker": "incomplete",+ "cross-tier-check-id": "incomplete",+ "valid-peer-plus-invalid-check-id": "incomplete",+}++[email protected](("shape", "expected_status"), list(_OPTIONAL_TIER2_SHAPES.items()))+def test_present_malformed_optional_tier2_evidence_is_incomplete_across_reporters_and_gate(+ tmp_path: Path,+ shape: str,+ expected_status: str,+) -> None:+ """Optional Tier 2 may be absent or cleanly skipped, never present but unrecognized."""+ tier1 = ValidationResult(validator_name="SCHEMA")+ tier1.add_success("schema", "Schema passed")+ tier1.metadata["benchmark_policy"] = {"tier2_required": False, "tier3_required": False}+ tier2 = ValidationResult(validator_name="Similarity Check")+ tier2.add_success("similarity_check", "Similarity scan completed")+ _stamp_publication_evidence(tier2, tier=2, check_id="similarity")+ results = [tier1]+ if shape == "clean-skip-invalid-marker":+ skipped = ValidationResult(validator_name="Similarity Check")+ skipped.add_warning("Skipped: configure a public embedding provider")+ skipped.metadata["skipped"] = True+ skipped.metadata["skip_reason"] = "Skipped: configure a public embedding provider"+ _stamp_publication_evidence(skipped, tier=2, check_id="not-a-check")+ results.append(skipped)+ elif shape == "invalid-check-id":+ tier2.metadata["publication_evidence"]["check_id"] = "not-a-check"+ results.append(tier2)+ elif shape == "missing-marker":+ results.append(tier2)+ elif shape == "cross-tier-check-id":+ tier2.metadata["publication_evidence"]["check_id"] = "schema"+ results.append(tier2)+ elif shape == "valid-peer-plus-invalid-check-id":+ malformed = ValidationResult(validator_name="Context Deduplication")+ malformed.add_success("context_dedup", "Context scan completed")+ _stamp_publication_evidence(malformed, tier=2, check_id="not-a-check")+ results.extend([tier2, malformed])+ _bind_publication_target(results, _publication_target("demo"))+ if shape == "missing-marker":+ # Bound to the target like built-in evidence, but with no producer marker.+ del tier2.metadata["publication_evidence"]++ benchmark = BenchmarkReporter(skill_name="demo", include_timestamp=False).render_all(results)+ json_payload = json.loads(JSONReporter(include_timestamp=False, expected_skill_name="demo").render_all(results))+ html_data = _html_report_data(HTMLReporter(include_timestamp=False, expected_skill_name="demo").render_all(results))+ markdown = MarkdownReporter(include_timestamp=False, expected_skill_name="demo").render_all(results)+ benchmark_path = tmp_path / "BENCHMARK.md"+ benchmark_path.write_text(benchmark, encoding="utf-8")+ _files, offenders = benchmark_gate.find_offenders([benchmark_path])++ assert json_payload["benchmark_policy"] == {"tier2_required": False, "tier3_required": False}+ assert "- Tier 2 evidence: optional by policy" in benchmark+ assert json_payload["publication_status"] == expected_status+ assert json_payload["publication"]["eligible"] is (expected_status == "pass")+ assert html_data["publication"]["status"] == expected_status+ assert f"Overall verdict: {expected_status.upper()}" in benchmark+ # The card verdict and its Tier 2 row must agree, so the public gate+ # accepts exactly the cards that every reporter calls publication PASS.+ assert offenders == []+ if expected_status == "pass":+ assert "## Publication Recommendation" in benchmark+ assert "**Publication status:** \u2705 PASS" in markdown+ else:+ assert "## Publication Recommendation" not in benchmark+ assert "| Tier 2 | Semantic deduplication | **INCOMPLETE** |" in benchmark+ assert "**Publication status:** \u26a0\ufe0f INCOMPLETE" in markdown+ assert any("Tier 2" in reason for reason in json_payload["publication"]["reasons"])++@pytest.mark.parametrize(("identity", "expected_status"),[("Cafe\u0301", "pass"), ("エージェント", "pass"), ("🤖\ufe0f", "incomplete")],@@ -2133,6 +2542,9 @@ def test_unicode_identity_requires_recorded_letters_or_numbers(agent["model"] = identitypayload["agents"][identity] = agentpayload["evaluator_version"] = identity+ for container in (payload, payload["summary"]):+ container["best_agent"] = identity+ container["agents_run"] = [identity]results = [tier1, tier2, tier3]_bind_publication_target(results, tier3.metadata["publication_target"])@@ -2364,6 +2776,356 @@ def test_missing_or_inconsistent_scored_attempts_cannot_certify_publication(assert offenders == []+def test_succeeded_under_scored_attempts_cannot_certify_publication(tmp_path: Path) -> None:+ results = _publication_ready_results("UNDER-SCORED")+ payload = results[-1].metadata["agent_eval"]+ for container in (payload, payload["summary"], *payload["agents"].values()):+ container["expected_attempts"] = 2+ container["scored_attempts"] = 1++ _assert_publication_incomplete_across_reporters(results, tmp_path)++[email protected]("agent_status", ["failed", "skipped", "incomplete", "unknown", None])+def test_non_succeeded_agent_peer_cannot_certify_publication(+ tmp_path: Path,+ agent_status: str | None,+) -> None:+ results = _publication_ready_results("NON-SUCCEEDED-PEER")+ payload = results[-1].metadata["agent_eval"]+ peer = deepcopy(next(iter(payload["agents"].values())))+ peer["model"] = "peer-model"+ peer["execution_status"] = "succeeded"+ payload["expected_attempts"] = 4+ payload["scored_attempts"] = 4+ payload["summary"]["expected_attempts"] = 4+ payload["summary"]["scored_attempts"] = 4+ payload["agents"]["peer"] = peer+ payload["agents_run"] = ["codex", "peer"]+ payload["summary"]["agents_run"] = ["codex", "peer"]+ assert agent_eval_publication_evidence_complete(payload) is True++ if agent_status is not None:+ peer["execution_status"] = agent_status+ else:+ peer.pop("execution_status")++ _assert_publication_incomplete_across_reporters(results, tmp_path)++[email protected]("error_location", ["payload", "summary", "agent"])[email protected]("invalid_errors", [["worker crashed"], (), {}], ids=["nonempty", "tuple", "mapping"])+def test_succeeded_evidence_with_invalid_execution_errors_cannot_certify_publication(+ tmp_path: Path,+ error_location: str,+ invalid_errors: object,+) -> None:+ results = _publication_ready_results("EXECUTION-ERRORS")+ payload = results[-1].metadata["agent_eval"]+ agent = next(iter(payload["agents"].values()))+ payload["execution_errors"] = []+ payload["summary"]["execution_errors"] = []+ agent["execution_errors"] = []+ container = payload if error_location == "payload" else payload["summary"] if error_location == "summary" else agent+ container["execution_errors"] = invalid_errors++ _assert_publication_incomplete_across_reporters(results, tmp_path)++[email protected]("error_location", ["payload", "summary", "agent"])+def test_succeeded_evidence_requires_explicit_empty_execution_errors(+ tmp_path: Path,+ error_location: str,+) -> None:+ results = _publication_ready_results("MISSING-EXECUTION-ERRORS")+ payload = results[-1].metadata["agent_eval"]+ agent = next(iter(payload["agents"].values()))+ container = payload if error_location == "payload" else payload["summary"] if error_location == "summary" else agent+ container.pop("execution_errors")++ _assert_publication_incomplete_across_reporters(results, tmp_path)++[email protected]("condition_name", ["with_skill", "without_skill"])[email protected]("condition_status", ["failed", "incomplete", "unknown", None])+def test_non_succeeded_agent_condition_cannot_certify_publication(+ tmp_path: Path,+ condition_name: str,+ condition_status: str | None,+) -> None:+ results, _payload, agent = _publication_ready_results_with_conditions("CONDITION-STATUS")+ condition = agent["conditions"][condition_name]+ if condition_status is None:+ condition.pop("execution_status")+ else:+ condition["execution_status"] = condition_status++ _assert_publication_incomplete_across_reporters(results, tmp_path)+++ "invalid_errors",+ [["worker crashed"], (), {}, None],+ ids=["nonempty", "tuple", "mapping", "null"],+)[email protected]("condition_name", ["with_skill", "without_skill"])+def test_invalid_agent_condition_execution_errors_cannot_certify_publication(+ tmp_path: Path,+ condition_name: str,+ invalid_errors: object,+) -> None:+ results, _payload, agent = _publication_ready_results_with_conditions("CONDITION-ERRORS")+ agent["conditions"][condition_name]["execution_errors"] = invalid_errors++ _assert_publication_incomplete_across_reporters(results, tmp_path)++[email protected]("condition_name", ["with_skill", "without_skill"])+def test_missing_agent_condition_execution_errors_cannot_certify_publication(+ tmp_path: Path,+ condition_name: str,+) -> None:+ results, _payload, agent = _publication_ready_results_with_conditions("CONDITION-MISSING-ERRORS")+ agent["conditions"][condition_name].pop("execution_errors")++ _assert_publication_incomplete_across_reporters(results, tmp_path)++[email protected]("condition_shape", ["missing", "empty", "fake-only", "extra"])+def test_noncanonical_agent_condition_identity_cannot_certify_publication(+ tmp_path: Path,+ condition_shape: str,+) -> None:+ results, _payload, agent = _publication_ready_results_with_conditions("CONDITION-IDENTITY")+ canonical = agent["conditions"]+ fake = deepcopy(canonical["with_skill"])+ if condition_shape == "missing":+ agent.pop("conditions")+ elif condition_shape == "empty":+ agent["conditions"] = {}+ elif condition_shape == "fake-only":+ agent["conditions"] = {"fake": fake}+ else:+ canonical["fake"] = fake++ _assert_publication_incomplete_across_reporters(results, tmp_path)++[email protected]("invalid_conditions", [[], {"with_skill": []}], ids=["list", "malformed-entry"])+def test_malformed_agent_conditions_cannot_certify_publication(+ tmp_path: Path,+ invalid_conditions: object,+) -> None:+ results, _payload, agent = _publication_ready_results_with_conditions("MALFORMED-CONDITIONS")+ agent["conditions"] = invalid_conditions++ _assert_publication_incomplete_across_reporters(results, tmp_path)+++ ("condition_status", "expected_attempts", "scored_attempts"),+ [+ ("succeeded", 2, 1),+ ("succeeded", 1, 2),+ ("succeeded", "1", 1),+ ("succeeded", 2, 2),+ ("skipped", 1, 0),+ ],+ ids=["under-scored", "over-scored", "malformed", "aggregate-mismatch", "skipped-with-work"],+)[email protected]("condition_name", ["with_skill", "without_skill"])+def test_invalid_agent_condition_attempt_coverage_cannot_certify_publication(+ tmp_path: Path,+ condition_name: str,+ condition_status: str,+ expected_attempts: object,+ scored_attempts: object,+) -> None:+ results, _payload, agent = _publication_ready_results_with_conditions("CONDITION-ATTEMPTS")+ condition = agent["conditions"][condition_name]+ condition["execution_status"] = condition_status+ condition["expected_attempts"] = expected_attempts+ condition["scored_attempts"] = scored_attempts++ _assert_publication_incomplete_across_reporters(results, tmp_path)+++def test_skipped_baseline_condition_cannot_certify_publication() -> None:+ results, payload, agent = _publication_ready_results_with_conditions("CONDITION-SKIPPED")+ agent["conditions"]["without_skill"].update(+ {+ "execution_status": "skipped",+ "expected_attempts": 0,+ "scored_attempts": 0,+ }+ )+ for container in (agent, payload, payload["summary"]):+ container["expected_attempts"] = 1+ container["scored_attempts"] = 1++ assert agent_eval_publication_evidence_complete(payload) is False+ report = json.loads(JSONReporter(include_timestamp=False).render_all(results))+ assert report["publication_status"] == "incomplete"+++def test_succeeded_baseline_condition_with_complete_counts_can_certify_publication() -> None:+ results, payload, agent = _publication_ready_results_with_conditions("CONDITION-BASELINE")+ agent["conditions"]["without_skill"].update(+ {+ "execution_status": "succeeded",+ "expected_attempts": 1,+ "scored_attempts": 1,+ }+ )+ for container in (agent, payload, payload["summary"]):+ container["expected_attempts"] = 2+ container["scored_attempts"] = 2++ assert agent_eval_publication_evidence_complete(payload) is True+ report = json.loads(JSONReporter(include_timestamp=False).render_all(results))+ assert report["publication_status"] == "pass"+++def test_tier3_attempt_coverage_is_bound_to_dataset_size() -> None:+ _results, payload, _agent = _publication_ready_results_with_conditions("DATASET-COVERAGE")+ payload["dataset_summary"]["total_tasks"] = 2++ assert agent_eval_publication_evidence_complete(payload) is False+++ ("mutation", "value"),+ [+ ("missing-pass-threshold", None),+ ("pass-threshold", "0.5"),+ ("pass-threshold", -0.1),+ ("pass-threshold", 1.1),+ ("pass-threshold", float("nan")),+ ("missing-stop-on-pass", None),+ ("stop-on-pass", "false"),+ ("stop-with-one-attempt", True),+ ],+)+def test_malformed_tier3_attempt_policy_cannot_certify_publication(+ mutation: str,+ value: object,+) -> None:+ _results, payload, _agent = _publication_ready_results_with_conditions("ATTEMPT-POLICY")+ policy = payload["attempt_policy"]+ if mutation == "missing-pass-threshold":+ policy.pop("pass_threshold")+ elif mutation == "pass-threshold":+ policy["pass_threshold"] = value+ elif mutation == "missing-stop-on-pass":+ policy.pop("stop_on_pass")+ else:+ policy["stop_on_pass"] = value++ assert agent_eval_publication_evidence_complete(payload) is False+++def test_full_attempt_count_is_required_without_early_stop() -> None:+ _results, payload, _agent = _publication_ready_results_with_conditions("FULL-ATTEMPT-COUNT")+ payload["attempt_policy"]["max_attempts"] = 3++ assert agent_eval_publication_evidence_complete(payload) is False+++def test_early_stop_allows_bounded_completed_attempt_count() -> None:+ _results, payload, _agent = _publication_ready_results_with_conditions("EARLY-STOP-COUNT")+ payload["attempt_policy"].update({"max_attempts": 3, "stop_on_pass": True})++ assert agent_eval_publication_evidence_complete(payload) is True+++def test_succeeded_baseline_requires_score_evidence() -> None:+ results, payload, agent = _publication_ready_results_with_conditions("BASELINE-SCORES")+ agent.pop("baseline")+ for dimension in agent["dimensions"]:+ dimension.pop("baseline")++ assert agent_eval_publication_evidence_complete(payload) is False+ report = json.loads(JSONReporter(include_timestamp=False).render_all(results))+ assert report["publication_status"] == "incomplete"+++ "mutation",+ [+ "root-best-agent",+ "summary-best-agent",+ "root-agents-run",+ "summary-agents-run",+ "root-overall-score",+ "summary-overall-score",+ "root-overall-lift",+ "summary-overall-lift",+ "root-dimensions",+ "oversized-overall-score",+ ],+)+def test_inconsistent_tier3_publication_aggregates_cannot_certify_publication(mutation: str) -> None:+ _results, payload, _agent = _publication_ready_results_with_conditions(f"AGGREGATE-{mutation}")+ summary = payload["summary"]+ if mutation == "root-best-agent":+ payload["best_agent"] = "forged"+ elif mutation == "summary-best-agent":+ summary["best_agent"] = "forged"+ elif mutation == "root-agents-run":+ payload["agents_run"] = ["codex", "forged"]+ elif mutation == "summary-agents-run":+ summary["agents_run"] = ["codex", "forged"]+ elif mutation == "root-overall-score":+ payload["overall_score"] = 0.1+ elif mutation == "summary-overall-score":+ summary["overall_score"] = 0.1+ elif mutation == "root-overall-lift":+ payload["overall_lift"] = -0.3+ elif mutation == "summary-overall-lift":+ summary["overall_lift"] = -0.3+ elif mutation == "root-dimensions":+ payload["dimensions"] = deepcopy(payload["dimensions"])+ payload["dimensions"][0]["with_skill"] = 0.1+ else:+ payload["overall_score"] = 1 << 40_000++ assert agent_eval_publication_evidence_complete(payload) is False+++ ("peer_score", "peer_lift", "reverse_mapping_order"),+ [(0.8, 0.4, False), (0.9, 0.4, False), (0.9, 0.5, False), (0.9, 0.5, True)],+ ids=["lower-score", "lower-lift", "later-tie", "reordered-later-tie"],+)+def test_forged_nonwinning_best_agent_cannot_certify_publication(+ peer_score: float,+ peer_lift: float,+ reverse_mapping_order: bool,+) -> None:+ _results, payload, agent = _publication_ready_results_with_conditions("FORGED-BEST")+ peer = deepcopy(agent)+ peer["model"] = "peer-model"+ peer["with_skill"] = peer_score+ peer["baseline"] = peer_score - peer_lift+ peer["lift"] = peer_lift+ for dimension in peer["dimensions"]:+ dimension["with_skill"] = peer_score+ dimension["baseline"] = peer_score - peer_lift+ dimension["lift"] = peer_lift+ payload["agents"]["peer"] = peer+ if reverse_mapping_order:+ payload["agents"] = {"peer": peer, "codex": agent}+ payload["expected_attempts"] = payload["summary"]["expected_attempts"] = 4+ payload["scored_attempts"] = payload["summary"]["scored_attempts"] = 4+ payload["best_agent"] = payload["summary"]["best_agent"] = "peer"+ payload["agents_run"] = payload["summary"]["agents_run"] = ["codex", "peer"]+ payload["overall_score"] = payload["summary"]["overall_score"] = peer_score+ payload["overall_lift"] = payload["summary"]["overall_lift"] = peer_lift+ payload["dimensions"] = peer["dimensions"]++ assert agent_eval_publication_evidence_complete(payload) is False++def test_aggregate_attempt_counts_must_match_agent_evidence() -> None:tier1 = ValidationResult(validator_name="SCHEMA")tier1.add_success("schema", "Schema passed")diff --git a/tests/reporting/test_reporters.py b/tests/reporting/test_reporters.pyindex 2e90b540..e7058e12 100644--- a/tests/reporting/test_reporters.py+++ b/tests/reporting/test_reporters.py@@ -18,7 +18,14 @@ from skillevaluator.evaluation.tier3_report import ()from skillevaluator.models import Finding, Severity, ValidationResultfrom skillevaluator.publication_evidence import stamp_publication_evidence-from skillevaluator.reporting import BenchmarkReporter, CLIReporter, HTMLReporter, JSONReporter, MarkdownReporter+from skillevaluator.reporting import (+ BenchmarkReporter,+ CLIReporter,+ HTMLReporter,+ JSONReporter,+ MarkdownReporter,+ SARIFReporter,+)from skillevaluator.tier1.commands import emit_reports_PUBLICATION_TARGET = {@@ -1453,6 +1460,23 @@ class TestMarkdownReporter:assert "### Evaluator Scores" in outputassert "| Accuracy | 0.90 | N/A | +0.00 |" in output+ def test_render_tier3_normalized_evidence_uses_distinct_evidence_ids(self) -> None:+ result = _tier3_harbor_result()+ result.metadata["agent_eval"]["suggestions_v2"][0]["evidence_refs"] = [+ {+ "source": "trajectory.json",+ "json_pointer": "/steps/0/tool_calls/0",+ "evidence_id": f"/steps/0/tool_calls/0/normalized/{index}",+ "kind": "tool_call",+ }+ for index in range(2)+ ]++ output = MarkdownReporter(include_timestamp=False).render_all([result])++ assert "`/steps/0/tool_calls/0/normalized/0`" in output+ assert "`/steps/0/tool_calls/0/normalized/1`" in output+def test_details_section(self, failure_result: ValidationResult) -> None:"""Test expandable details section."""reporter = MarkdownReporter(include_details=True)diff --git a/tests/reporting/test_rich_markup_escaping.py b/tests/reporting/test_rich_markup_escaping.pyindex 615b9aa8..586a7260 100644--- a/tests/reporting/test_rich_markup_escaping.py+++ b/tests/reporting/test_rich_markup_escaping.py@@ -171,7 +171,9 @@ def _agent_eval_result(payload: str) -> ValidationResult:def _advisory_skip_result(payload: str) -> ValidationResult:result = ValidationResult(validator_name="AGENT_EVAL", validator_description="Live agent evaluation")result.metadata["agent_eval"] = {- "provenance": {"advisory": True, "reason": "skipped", "message": f"Skipped because {payload}"}+ "execution_status": "skipped",+ "verdict": "neutral",+ "provenance": {"advisory": True, "reason": "skipped", "message": f"Skipped because {payload}"},}return resultdiff --git a/tests/reporting/test_unified_tier3_report.py b/tests/reporting/test_unified_tier3_report.pyindex fad07454..009ace82 100644--- a/tests/reporting/test_unified_tier3_report.py+++ b/tests/reporting/test_unified_tier3_report.py@@ -28,6 +28,7 @@ from skillevaluator.evaluation.tier3_report import (from skillevaluator.models import ValidationResultfrom skillevaluator.reporting import HTMLReporter, JSONReporterfrom skillevaluator.reporting import html as html_module+from skillevaluator.reporting.base import agent_eval_publication_evidence_completefrom skillevaluator.reporting.html import PackageLoader, _compact_jsonfrom skillevaluator.tier3.harbor.collector import _paired_pass_comparison, _wilson_score_intervalfrom skillevaluator.tier3.harbor.metrics import DEFAULT_METRICS, MAX_CUSTOM_METRIC_NAME_BYTES@@ -567,6 +568,222 @@ def test_standalone_tier3_binds_report_to_requested_skill(assert captured["expected_skill_name"] == "requested-skill"+def test_trial_report_renders_unavailable_tokens_as_unavailable() -> None:+ payload = build_agent_eval_payload(+ "demo",+ {+ "codex": {+ "execution_status": "succeeded",+ "expected_attempts": 1,+ "scored_attempts": 1,+ "with_skill": {"accuracy": 1.0},+ "rewards": [+ {+ "trial_id": "case-1__attempt1",+ "entry_id": "case-1",+ "accuracy": 1.0,+ "_traj": {+ "steps": 4,+ "prompt_tokens": None,+ "completion_tokens": None,+ "cached_tokens": None,+ },+ }+ ],+ }+ },+ use_llm_judge=False,+ )+ assert payload is not None++ trials_html = _tier3_page(_render_agent_payload(payload), "trials", "agents")++ assert "With-Skill Steps per Eval Case" in trials_html+ assert "With-Skill Token Usage by Agent" not in trials_html+ assert "With-Skill Per-Evaluator Drill-Down" in trials_html+ assert re.search(r"<td>4</td>\s*<td>—</td>", trials_html)+++def test_trial_report_omits_token_chart_for_incomplete_agent_telemetry() -> None:+ payload = build_agent_eval_payload(+ "demo",+ {+ "codex": {+ "execution_status": "succeeded",+ "expected_attempts": 2,+ "scored_attempts": 2,+ "with_skill": {"accuracy": 1.0},+ "rewards": [+ {+ "trial_id": "case-1__attempt1",+ "entry_id": "case-1",+ "accuracy": 1.0,+ "_traj": {+ "steps": 4,+ "prompt_tokens": 10,+ "completion_tokens": 4,+ "cached_tokens": None,+ },+ },+ {+ "trial_id": "case-2__attempt1",+ "entry_id": "case-2",+ "accuracy": 1.0,+ "_traj": {+ "steps": 3,+ "prompt_tokens": None,+ "completion_tokens": None,+ "cached_tokens": None,+ },+ },+ ],+ }+ },+ use_llm_judge=False,+ )+ assert payload is not None++ trials_html = _tier3_page(_render_agent_payload(payload), "trials", "agents")++ assert "With-Skill Token Usage by Agent" not in trials_html+ assert 'id="tier3-token-chart"' not in trials_html+ assert re.search(r"<td>4</td>\s*<td>14</td>", trials_html)+ assert re.search(r"<td>3</td>\s*<td>—</td>", trials_html)+++def test_trial_report_omits_token_chart_when_any_agent_telemetry_is_incomplete() -> None:+ payload = build_agent_eval_payload(+ "demo",+ {+ "codex": {+ "execution_status": "succeeded",+ "expected_attempts": 1,+ "scored_attempts": 1,+ "with_skill": {"accuracy": 1.0},+ "rewards": [+ {+ "trial_id": "case-1__attempt1",+ "entry_id": "case-1",+ "accuracy": 1.0,+ "_traj": {+ "steps": 4,+ "prompt_tokens": 10,+ "completion_tokens": 4,+ "cached_tokens": 2,+ },+ }+ ],+ },+ "opencode": {+ "execution_status": "succeeded",+ "expected_attempts": 1,+ "scored_attempts": 1,+ "with_skill": {"accuracy": 1.0},+ "rewards": [+ {+ "trial_id": "case-1__attempt1",+ "entry_id": "case-1",+ "accuracy": 1.0,+ "_traj": {+ "steps": 3,+ "prompt_tokens": None,+ "completion_tokens": None,+ "cached_tokens": None,+ },+ }+ ],+ },+ },+ use_llm_judge=False,+ )+ assert payload is not None++ trials_html = _tier3_page(_render_agent_payload(payload), "trials", "agents")++ assert "With-Skill Token Usage by Agent" not in trials_html+ assert 'id="tier3-token-chart"' not in trials_html+++def test_trial_report_omits_token_chart_when_reported_agent_has_no_trials() -> None:+ payload = build_agent_eval_payload(+ "demo",+ {+ "codex": {+ "execution_status": "succeeded",+ "expected_attempts": 1,+ "scored_attempts": 1,+ "with_skill": {"accuracy": 1.0},+ "rewards": [+ {+ "trial_id": "case-1__attempt1",+ "entry_id": "case-1",+ "accuracy": 1.0,+ "_traj": {+ "steps": 4,+ "prompt_tokens": 10,+ "completion_tokens": 4,+ "cached_tokens": 2,+ },+ }+ ],+ },+ "opencode": {+ "execution_status": "failed",+ "execution_errors": ["malformed judge response"],+ "expected_attempts": 1,+ "scored_attempts": 0,+ "with_skill": {},+ "rewards": [],+ },+ },+ use_llm_judge=False,+ )+ assert payload is not None+ assert set(payload["agents"]) == {"codex", "opencode"}++ trials_html = _tier3_page(_render_agent_payload(payload), "trials", "agents")++ assert "With-Skill Token Usage by Agent" not in trials_html+ assert 'id="tier3-token-chart"' not in trials_html+++def test_trial_charts_preserve_token_and_step_counter_semantics() -> None:+ payload = build_agent_eval_payload(+ "demo",+ {+ "codex": {+ "execution_status": "succeeded",+ "expected_attempts": 1,+ "scored_attempts": 1,+ "with_skill": {"accuracy": 1.0},+ "rewards": [+ {+ "trial_id": "case-1__attempt1",+ "entry_id": "case-1",+ "accuracy": 1.0,+ "_traj": {+ "steps": 4,+ "prompt_tokens": 10,+ "completion_tokens": 4,+ "cached_tokens": 2,+ },+ }+ ],+ }+ },+ use_llm_judge=False,+ )+ assert payload is not None++ html = _render_agent_payload(payload)+ trials_html = _tier3_page(html, "trials", "agents")++ assert 'id="tier3-token-chart"' in trials_html+ assert '{ label: "Prompt (total)"' in html+ assert '{ label: "Cached (included in prompt)"' in html+ assert "if (observed.length !== matching.length) return null;" in html++def test_authenticated_pre_status_rerender_preserves_historical_scores(tmp_path: Path) -> None:skill = tmp_path / "demo"skill.mkdir()@@ -1374,10 +1591,99 @@ def test_payload_prunes_oversized_non_best_conditions_before_best_evidence() ->assert any(card["evidence"] for card in best_cards)assert any(card["evidence"] for card in payload["evaluator_cards"])assert payload["provenance"]["raw_trial_rewards"]["zzz"]- assert payload["agents"]["aaa"]["conditions"] == {}+ assert payload["agents"]["aaa"]["conditions"] == {+ "with_skill": {+ "execution_status": None,+ "execution_errors": None,+ "expected_attempts": 0,+ "scored_attempts": 0,+ }+ }assert payload["report_truncation"]["omitted"]["non_best_agent_details"] > 0+def _publication_ready_oversized_condition_payload(*, extra_condition: bool = False) -> dict:+ from skillevaluator.tier3.harbor.metrics import DEFAULT_METRICS++ conditions = {+ "with_skill": {+ "execution_status": "succeeded",+ "execution_errors": [],+ "expected_attempts": 1,+ "scored_attempts": 1,+ "diagnostic": "x" * (3 * 1024 * 1024),+ },+ "without_skill": {+ "execution_status": "succeeded",+ "execution_errors": [],+ "expected_attempts": 1,+ "scored_attempts": 1,+ },+ }+ if extra_condition:+ conditions["forged"] = {"execution_status": "succeeded"}+ payload = build_agent_eval_payload(+ "condition-budget",+ {+ "codex": {+ "model": "test-model",+ "execution_status": "succeeded",+ "execution_errors": [],+ "expected_attempts": 2,+ "scored_attempts": 2,+ "conditions": conditions,+ "with_skill": dict.fromkeys(DEFAULT_METRICS, 0.9),+ "without_skill": dict.fromkeys(DEFAULT_METRICS, 0.4),+ "lift": dict.fromkeys(DEFAULT_METRICS, 0.5),+ "rewards": [{"entry_id": "case-1", **dict.fromkeys(DEFAULT_METRICS, 0.9)}],+ "rewards_baseline": [{"entry_id": "case-1", **dict.fromkeys(DEFAULT_METRICS, 0.4)}],+ }+ },+ dataset=[{"id": "case-1", "expected_skill": "condition-budget"}],+ attempt_policy={"max_attempts": 1, "pass_threshold": 0.5, "stop_on_pass": False},+ env_mode="docker",+ evaluated_at="2026-09-12T12:00:00+00:00",+ evaluator_version="1.0.0",+ run_id="condition-budget-run",+ publication_target={+ "skill_name": "condition-budget",+ "skill_digest": "sha256:" + "a" * 64,+ "skill_digest_algorithm": "skill-evaluator-source-tree/2",+ },+ use_llm_judge=False,+ )+ assert payload is not None+ return payload+++def test_payload_budget_preserves_publication_condition_truth_fields() -> None:+ payload = _publication_ready_oversized_condition_payload()++ assert agent_eval_publication_evidence_complete(payload) is True+ assert payload["agents"]["codex"]["conditions"] == {+ "with_skill": {+ "execution_status": "succeeded",+ "execution_errors": [],+ "expected_attempts": 1,+ "scored_attempts": 1,+ },+ "without_skill": {+ "execution_status": "succeeded",+ "execution_errors": [],+ "expected_attempts": 1,+ "scored_attempts": 1,+ },+ }+++def test_payload_budget_does_not_repair_extra_condition_keys() -> None:+ payload = _publication_ready_oversized_condition_payload(extra_condition=True)++ conditions = payload["agents"]["codex"]["conditions"]+ assert "invalid_condition_shape" in conditions+ assert agent_eval_publication_evidence_complete(payload) is False++def test_non_finite_report_numbers_are_sanitized_before_canonical_json() -> None:payload = build_agent_eval_payload("finite-json",@@ -1427,6 +1733,89 @@ def test_non_finite_report_numbers_are_sanitized_before_canonical_json() -> Noneassert _embedded_tier3_payload(html)["dataset"][0]["score"] is None+def test_canonical_payload_sanitizes_unsafe_integers_for_browser_json_semantics() -> None:+ safe_integer_metadata = {+ "max_safe": (1 << 53) - 1,+ "min_safe": -((1 << 53) - 1),+ "enabled": True,+ }+ unsafe_integer_metadata = {+ **safe_integer_metadata,+ "too_large": 10**400,+ "too_small": -(10**400),+ }+ payload = build_agent_eval_payload(+ "browser-safe-json",+ {+ "codex": {+ "execution_status": "succeeded",+ "execution_errors": [],+ "expected_attempts": 1,+ "scored_attempts": 1,+ "with_skill": {"security": 1.0},+ "rewards": [+ {+ "entry_id": "case-1",+ "security": 1.0,+ "overall": 1.0,+ "metadata": unsafe_integer_metadata,+ }+ ],+ }+ },+ dataset=[{"id": "case-1", "metadata": unsafe_integer_metadata}],+ use_llm_judge=False,+ )+ assert payload is not None++ canonical_metadata = (+ payload["dataset"][0]["metadata"],+ payload["provenance"]["raw_trial_rewards"]["codex"][0]["metadata"],+ )+ for metadata in canonical_metadata:+ assert metadata["too_large"] is None+ assert metadata["too_small"] is None+ assert metadata["max_safe"] == (1 << 53) - 1+ assert type(metadata["max_safe"]) is int+ assert metadata["min_safe"] == -((1 << 53) - 1)+ assert type(metadata["min_safe"]) is int+ assert metadata["enabled"] is True++ encoded = json.dumps(payload, allow_nan=False)+ browser_payload = json.loads(encoded, parse_int=float)+ dataset_metadata = browser_payload["dataset"][0]["metadata"]+ raw_metadata = browser_payload["provenance"]["raw_trial_rewards"]["codex"][0]["metadata"]++ for metadata in (dataset_metadata, raw_metadata):+ assert metadata["too_large"] is None+ assert metadata["too_small"] is None+ assert metadata["max_safe"] == float((1 << 53) - 1)+ assert metadata["min_safe"] == -float((1 << 53) - 1)+ assert metadata["enabled"] is True++[email protected]("invalid", [float("nan"), float("inf"), float("-inf"), 10**400])+def test_invalid_legacy_attempt_threshold_does_not_crash_canonical_report(invalid: float | int) -> None:+ payload = build_agent_eval_payload(+ "invalid-policy-number",+ {+ "codex": {+ "execution_status": "succeeded",+ "execution_errors": [],+ "expected_attempts": 1,+ "scored_attempts": 1,+ "with_skill": dict.fromkeys(DEFAULT_METRICS, 1.0),+ }+ },+ attempt_policy={"pass_threshold": invalid},+ use_llm_judge=False,+ )++ assert payload is not None+ assert payload["verdict_policy"]["attempt_pass_threshold"] is None+ json.dumps(payload, allow_nan=False)++def test_canonical_report_serializers_disclose_non_finite_numbers() -> None:with pytest.raises(ValueError, match="Out of range float values"):_compact_json({"score": float("nan")})@@ -1786,6 +2175,51 @@ def test_rerender_rejects_canonical_target_when_run_marks_identity_conflict(tmp_assert report["results"][0]["publication_target_conflict"] == "source changed during evaluation"+def test_rerender_reports_runtime_context_conflict_without_claiming_source_mutation(tmp_path: Path) -> None:+ from skillevaluator.publication_identity import publication_target_from_path+ from skillevaluator.reporting.base import assess_tier3_evidence++ skill = tmp_path / "demo"+ skill.mkdir()+ (skill / "SKILL.md").write_text("# evaluated source\n", encoding="utf-8")+ run_start_target = publication_target_from_path(skill)+ assert run_start_target is not None++ run_dir = tmp_path / "results" / "20260709_120013"+ _write_summary(run_dir)+ (run_dir / "result.json").write_text(+ json.dumps(+ {+ "run_id": run_dir.name,+ "publication_target": None,+ "publication_target_conflict": {+ "run_start": run_start_target,+ "run_end": None,+ "reason_code": "runtime_context_outside_publication_target",+ },+ }+ ),+ encoding="utf-8",+ )++ tier3 = agent_eval_result_from_directory(skill, run_dir, use_llm_judge=False)++ assert tier3 is not None+ payload = tier3.metadata["agent_eval"]+ marker = "runtime context is not bound to publication target"+ assert payload["publication_target"] is None+ assert payload["summary"]["publication_target"] is None+ assert payload["publication_target_conflict"] == marker+ assert payload["summary"]["publication_target_conflict"] == marker+ assert "publication_target" not in tier3.metadata+ assert tier3.metadata["publication_target_conflict"] == marker+ assessment = assess_tier3_evidence([tier3], payload, expected_skill_name="demo")+ assert assessment.evidence_complete is False+ assert assessment.reason == "Tier 3 runtime context is not bound to the publication target."+ report = json.loads(JSONReporter(include_timestamp=False).render_all([tier3]))+ assert report["results"][0]["publication_target_conflict"] == marker++def test_rerender_does_not_replace_malformed_persisted_identity_with_engine_claim(tmp_path: Path) -> None:from skillevaluator.publication_identity import publication_target_from_pathdiff --git a/tests/test_base_install.py b/tests/test_base_install.pyindex 9d105657..8656f598 100644--- a/tests/test_base_install.py+++ b/tests/test_base_install.py@@ -74,7 +74,8 @@ with tempfile.TemporaryDirectory() as temporary_directory:"validate",".","--no-llm",- "--no-tier2",+ "--tiers",+ "1","--checks","schema,quality,lint","--report",diff --git a/tests/test_benchmark_source_provenance.py b/tests/test_benchmark_source_provenance.pyindex 79fca609..4d89bb33 100644--- a/tests/test_benchmark_source_provenance.py+++ b/tests/test_benchmark_source_provenance.py@@ -350,11 +350,13 @@ _PASS_CARD = """\## Evaluation Metadata+- Source digest: `sha256:{digest}` (skill-evaluator-source-tree/2)- Evaluation date: 2026-07-25- Evaluator version: `0.8.3`{source_lines}- Agents: Codex (`gpt-codex`)- Tasks: 4 evaluation tasks- Dataset digest: `sha256:{digest}` (skill-evaluator-dataset-snapshot/1)+- Tier 3 run ID: `fixture-demo-run`- Attempts per task: 1- Environment: `Isolated sandbox`- Tier 3 evidence: {tier3_evidence}diff --git a/tests/test_commands.py b/tests/test_commands.pyindex f97b5d27..ca690f8f 100644--- a/tests/test_commands.py+++ b/tests/test_commands.py@@ -29,7 +29,7 @@ def test_version_check_is_in_the_default_tier1_lineup() -> None:assert enabled_check_lineup("security,version") == ["version", "security"]-def test_validate_passes_explicit_previous_version(monkeypatch) -> None:+def test_validate_passes_explicit_previous_version(monkeypatch, tmp_path: Path) -> None:from skillevaluator import cli as cli_modulecaptured: list[str | None] = []@@ -52,6 +52,8 @@ def test_validate_passes_explicit_previous_version(monkeypatch) -> None:"version","--previous-version","1.2.0",+ "--output-dir",+ str(tmp_path / "reports"),],)@@ -107,7 +109,7 @@ def test_repeated_canonical_model_overrides_are_rejected() -> None:)-def test_validate_fixture_no_llm() -> None:+def test_validate_fixture_no_llm(tmp_path: Path) -> None:result = CliRunner().invoke(cli,[@@ -119,6 +121,8 @@ def test_validate_fixture_no_llm() -> None:"--no-dedup","--checks","schema,quality,lint",+ "--output-dir",+ str(tmp_path / "reports"),],)@@ -150,7 +154,7 @@ def test_validate_reports_malformed_policy_without_traceback(tmp_path: Path) ->assert isinstance(result.exception, SystemExit)-def test_validate_prints_tier1_section_banner() -> None:+def test_validate_prints_tier1_section_banner(tmp_path: Path) -> None:# The Tier 1 section is announced as it runs so it is visibly reported in# CI logs (SkillEvaluator parity), not only inside the final combined report.result = CliRunner().invoke(@@ -164,6 +168,8 @@ def test_validate_prints_tier1_section_banner() -> None:"--no-dedup","--checks","schema,quality,lint",+ "--output-dir",+ str(tmp_path / "reports"),],)@@ -171,7 +177,7 @@ def test_validate_prints_tier1_section_banner() -> None:assert "Tier 1: Security and Static Validation" in result.output-def test_validate_tier1_banner_is_stable_in_narrow_terminal(monkeypatch) -> None:+def test_validate_tier1_banner_is_stable_in_narrow_terminal(monkeypatch, tmp_path: Path) -> None:monkeypatch.setenv("COLUMNS", "20")result = CliRunner().invoke(@@ -185,6 +191,8 @@ def test_validate_tier1_banner_is_stable_in_narrow_terminal(monkeypatch) -> None"--no-dedup","--checks","schema,quality,lint",+ "--output-dir",+ str(tmp_path / "reports"),],)@@ -254,7 +262,9 @@ def test_validate_help_exposes_optional_agent_runtime_preflight() -> None:("--no-agent-runtime-preflight", False),],)-def test_validate_forwards_agent_runtime_preflight_override(monkeypatch, flag: str, expected: bool) -> None:+def test_validate_forwards_agent_runtime_preflight_override(+ monkeypatch, tmp_path: Path, flag: str, expected: bool+) -> None:from skillevaluator import cli as cli_modulefrom skillevaluator.models.result import ValidationResult@@ -280,6 +290,8 @@ def test_validate_forwards_agent_runtime_preflight_override(monkeypatch, flag: sflag,"--checks","schema",+ "--output-dir",+ str(tmp_path / "reports"),],)@@ -369,6 +381,47 @@ def test_validate_quiet_always_writes_html_and_json_reports() -> None:assert any(p.suffix == ".json" for p in reports), reports+def test_validate_default_reports_do_not_write_into_authored_sibling_skill(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ from skillevaluator.tier3.output_provenance import is_generated_output_root++ skill = tmp_path / "simple"+ shutil.copytree(FIXTURE, skill)+ authored_sibling = tmp_path / "reports"+ shutil.copytree(FIXTURE, authored_sibling)+ sibling_manifest = authored_sibling / "SKILL.md"+ sibling_manifest.write_text(+ sibling_manifest.read_text(encoding="utf-8").replace("name: simple", "name: reports"),+ encoding="utf-8",+ )+ initial_files = {+ path.relative_to(authored_sibling): path.read_bytes()+ for path in authored_sibling.rglob("*")+ if path.is_file()+ }+ private_state = tmp_path / "private-state"+ private_state.mkdir(mode=0o700)+ monkeypatch.setenv("SKILLEVALUATOR_OUTPUT_PROVENANCE_KEY_FILE", str(private_state / "key"))+ monkeypatch.chdir(tmp_path)++ result = CliRunner().invoke(+ cli,+ ["validate", "--no-tier3", "simple", "--no-llm", "--no-tier2", "--checks", "schema", "--report", "json"],+ )++ output_root = tmp_path / "simple-reports"+ assert result.exit_code == 0, result.output+ assert (output_root / "BENCHMARK.md").is_file()+ assert is_generated_output_root(output_root)+ assert {+ path.relative_to(authored_sibling): path.read_bytes()+ for path in authored_sibling.rglob("*")+ if path.is_file()+ } == initial_files++def test_validate_default_in_skill_reports_do_not_mutate_publication_target(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,@@ -387,7 +440,7 @@ def test_validate_default_in_skill_reports_do_not_mutate_publication_target(result = CliRunner().invoke(cli,- ["validate", ".", "--no-llm", "--no-tier2", "--checks", "schema", "--report", "json"],+ ["validate", "--no-tier3", ".", "--no-llm", "--no-tier2", "--checks", "schema", "--report", "json"],)assert result.exit_code == 0, result.output@@ -414,7 +467,7 @@ def test_validate_default_in_skill_reports_refuses_unowned_sibling(result = CliRunner().invoke(cli,- ["validate", ".", "--no-llm", "--no-tier2", "--checks", "schema", "--report", "json"],+ ["validate", "--no-tier3", ".", "--no-llm", "--no-tier2", "--checks", "schema", "--report", "json"],)assert result.exit_code != 0@@ -440,6 +493,7 @@ def test_validate_rejects_case_alias_output_inside_publication_target(cli,["validate",+ "--no-tier3",str(skill),"--no-llm","--no-tier2",@@ -456,6 +510,112 @@ def test_validate_rejects_case_alias_output_inside_publication_target(assert publication_target_from_path(skill) == initial_target+def _same_entry_alias(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ recorded_name: str,+ alias_name: str,+) -> Path:+ """Return a lexical alias that opens the skill entry recorded as *recorded_name*.++ Case- and normalization-insensitive filesystems (the macOS and Windows+ defaults) provide such aliases natively. Elsewhere, simulate one: create+ the entry under the alias spelling and let its parent directory report the+ recorded spelling, as an insensitive filesystem does.+ """+ from skillevaluator import publication_identity++ recorded = tmp_path / recorded_name+ shutil.copytree(FIXTURE, recorded)+ alias = tmp_path / alias_name+ if alias.exists() and alias.samefile(recorded) and {entry.name for entry in tmp_path.iterdir()} == {recorded_name}:+ return alias+ shutil.rmtree(recorded)+ shutil.copytree(FIXTURE, alias)+ entry_name = publication_identity._canonical_directory_entry_name++ def recorded_entry_name(path: Path) -> str:+ name = entry_name(path)+ return recorded_name if name == alias_name else name++ monkeypatch.setattr(publication_identity, "_canonical_directory_entry_name", recorded_entry_name)+ return alias+++ ("recorded_name", "alias_name"),+ [("simple", "SIMPLE"), ("caf\u00e9", "cafe\u0301"), ("caf\u00e9", "CAFE\u0301")],+ ids=["case", "unicode-normalization", "case-and-normalization"],+)+def test_validate_same_entry_alias_expects_recorded_publication_name(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ recorded_name: str,+ alias_name: str,+) -> None:+ alias = _same_entry_alias(monkeypatch, tmp_path, recorded_name, alias_name)+ output_dir = tmp_path / "reports"++ result = CliRunner().invoke(+ cli,+ [+ "validate",+ str(alias),+ "--no-llm",+ "--no-autopilot",+ "--tiers",+ "1,3",+ "--checks",+ "version,lint",+ "--report",+ "json",+ "--output-dir",+ str(output_dir),+ ],+ )++ assert result.exit_code == 0, result.output+ benchmark = (output_dir / "BENCHMARK.md").read_text(encoding="utf-8")+ report = json.loads(next(output_dir.glob("skillevaluator-output-*.json")).read_text(encoding="utf-8"))+ assert f"# Skill Benchmark: {recorded_name}" in benchmark+ # The row gets past the identity binding checks; only the narrowed+ # --checks lineup keeps Tier 1 from certifying publication.+ assert "Missing canonical source identity" not in benchmark+ assert "| Tier 1 | Static validation | **INCOMPLETE** | Required Tier 1 checks did not run:" in benchmark+ assert report["tier3"]["skill_name"] == recorded_name+ assert report["tier3"]["summary"]["skill_name"] == recorded_name+ identity_reasons = [+ reason+ for reason in report["publication"]["reasons"]+ if "different" in reason or "conflicting" in reason or "lack one canonical" in reason+ ]+ assert identity_reasons == []+++def test_tier3_run_report_expects_recorded_publication_name(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ from skillevaluator.evaluation import tier3_report+ from skillevaluator.models.result import ValidationResult+ from skillevaluator.reporting import HTMLReporter++ alias = _same_entry_alias(monkeypatch, tmp_path, "simple", "SIMPLE")+ run_dir = tmp_path / "run"+ run_dir.mkdir()+ expected_names: list[str | None] = []+ monkeypatch.setattr(+ tier3_report,+ "agent_eval_result_from_directory",+ lambda *_args, **_kwargs: ValidationResult(validator_name="AGENT_EVAL"),+ )+ monkeypatch.setattr(HTMLReporter, "save", lambda self, *_args: expected_names.append(self.expected_skill_name))++ tier3_report.render_agent_eval_html_report(alias, run_dir)++ assert expected_names == ["simple"]++def test_validate_rejects_arbitrary_in_skill_report_output_before_validation(tmp_path: Path) -> None:from skillevaluator.publication_identity import publication_target_from_path@@ -469,6 +629,7 @@ def test_validate_rejects_arbitrary_in_skill_report_output_before_validation(tmpcli,["validate",+ "--no-tier3",str(skill),"--no-llm","--no-tier2",@@ -499,7 +660,7 @@ def test_standalone_tier1_rejects_in_skill_report_output_before_validation(result = CliRunner().invoke(cli,- ["quality-check", str(skill), "--output-dir", str(output_dir)],+ ["quality-check", str(skill), "--report", "json", "--output-dir", str(output_dir)],)assert result.exit_code != 0@@ -526,7 +687,7 @@ def test_standalone_tier2_rejects_in_skill_report_output_before_validation(result = CliRunner().invoke(cli,- ["context-optimization-check", str(skill), "--output-dir", str(output_dir)],+ ["context-optimization-check", str(skill), "--report", "json", "--output-dir", str(output_dir)],)assert result.exit_code != 0@@ -535,6 +696,47 @@ def test_standalone_tier2_rejects_in_skill_report_output_before_validation(assert not output_dir.exists()+ ("command", "runner_name"),+ [+ ("quality-check", "run_quality_check"),+ ("rubric-eval", "run_rubric_eval"),+ ("security-scan", "run_security_scan"),+ ("pii-scan", "run_pii_scan"),+ ("lint-scripts", "run_lint_scripts"),+ ("similarity-check", "run_similarity_check"),+ ("context-optimization-check", "run_context_optimization_check"),+ ("dedup-scan", "run_dedup_scan"),+ ],+)+def test_standalone_cli_only_report_does_not_reserve_output_storage(+ command: str,+ runner_name: str,+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ from skillevaluator import cli as cli_module+ from skillevaluator.tier2 import commands as tier2_commands++ skill = tmp_path / "simple"+ shutil.copytree(FIXTURE, skill)+ private_state = tmp_path / "private-state"+ private_state.mkdir(mode=0o700)+ monkeypatch.setenv("SKILLEVALUATOR_OUTPUT_PROVENANCE_KEY_FILE", str(private_state / "key"))+ monkeypatch.chdir(skill)++ runner_module = tier2_commands if hasattr(tier2_commands, runner_name) else cli_module+ calls: list[bool] = []+ monkeypatch.setattr(runner_module, runner_name, lambda *_args, **_kwargs: calls.append(True) or [])++ result = CliRunner().invoke(cli, [command, ".", "--report", "cli"])++ assert result.exit_code == 0, result.output+ assert calls == [True]+ assert not skill.with_name("simple-reports").exists()+ assert not (skill / "reports").exists()++def test_validate_tier_aliases_and_selector(monkeypatch) -> None:from skillevaluator import cli as cli_modulefrom skillevaluator.models.result import ValidationResult@@ -591,6 +793,7 @@ def test_validate_excludes_report_output_from_tier3_repo_context() -> None:from skillevaluator import cli as cli_modulefrom skillevaluator.models.result import ValidationResult+ from skillevaluator.tier3.output_provenance import is_generated_output_rootskill = tmp_path / "repo" / "simple"shutil.copytree(FIXTURE, skill)@@ -623,6 +826,283 @@ def test_validate_excludes_report_output_from_tier3_repo_context(assert result.exit_code == 0, result.outputassert captured["repo_context_exclude_paths"] == (output_dir,)+ assert is_generated_output_root(output_dir)++[email protected]("output_dir", [".", "missing/.."])+def test_validate_copy_repo_rejects_repo_root_report_output_before_tier3(+ output_dir: str,+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ from skillevaluator import cli as cli_module++ repo = tmp_path / "repo"+ skill = repo / "skills" / "simple"+ shutil.copytree(FIXTURE, skill)+ (repo / ".git").mkdir()+ monkeypatch.chdir(repo)+ calls: list[Path] = []+ monkeypatch.setattr(+ cli_module,+ "_run_agent_eval_or_skip",+ lambda target, **_kwargs: calls.append(target),+ )++ result = CliRunner().invoke(+ cli,+ [+ "validate",+ "skills/simple",+ "--no-llm",+ "--no-tier2",+ "--tier3",+ "--copy-repo",+ "--checks",+ "schema",+ "--output-dir",+ output_dir,+ ],+ )++ assert result.exit_code != 0+ assert "with --copy-repo" in result.output.lower()+ assert "repository root" in result.output.lower()+ assert "dedicated path" in result.output.lower()+ assert calls == []+++def test_validate_linked_context_rejects_authored_in_repo_report_output_before_tier3(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ from skillevaluator import cli as cli_module++ repo = tmp_path / "repo"+ skill = repo / "skills" / "simple"+ shutil.copytree(FIXTURE, skill)+ (repo / ".git").mkdir()+ authored_output = repo / "docs"+ authored_output.mkdir()+ guide = authored_output / "guide.md"+ guide.write_text("authored dependency\n", encoding="utf-8")+ calls: list[Path] = []+ monkeypatch.setattr(+ cli_module,+ "_run_agent_eval_or_skip",+ lambda path, **_kwargs: calls.append(path),+ )++ result = CliRunner().invoke(+ cli,+ [+ "validate",+ str(skill),+ "--no-llm",+ "--no-tier2",+ "--tier3",+ "--checks",+ "schema",+ "--output-dir",+ str(authored_output),+ ],+ )++ assert result.exit_code == 2+ assert "Tier 3 linked-context staging" in result.output+ assert "generated-output directory" in result.output+ assert calls == []+ assert guide.read_text(encoding="utf-8") == "authored dependency\n"+++def test_validate_tier3_rejects_authored_report_output_inside_included_skill(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ from skillevaluator import cli as cli_module++ repo = tmp_path / "target-repo"+ skill = repo / "skills" / "simple"+ shutil.copytree(FIXTURE, skill)+ (repo / ".git").mkdir()+ included_skill = tmp_path / "included-repo" / "skills" / "helper"+ shutil.copytree(FIXTURE, included_skill)+ authored_output = included_skill / "references"+ authored_output.mkdir()+ guide = authored_output / "guide.md"+ guide.write_text("authored dependency\n", encoding="utf-8")+ calls: list[Path] = []+ monkeypatch.setattr(+ cli_module,+ "_run_agent_eval_or_skip",+ lambda path, **_kwargs: calls.append(path),+ )++ result = CliRunner().invoke(+ cli,+ [+ "validate",+ str(skill),+ "--no-llm",+ "--no-tier2",+ "--tier3",+ "--checks",+ "schema",+ "--include-skills",+ str(included_skill),+ "--output-dir",+ str(authored_output),+ ],+ )++ assert result.exit_code == 2+ assert "Tier 3 linked-context staging" in result.output+ assert "generated-output directory" in result.output+ assert calls == []+ assert guide.read_text(encoding="utf-8") == "authored dependency\n"+++def test_validate_tier3_allows_report_output_elsewhere_in_included_skill_repo(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ from skillevaluator import cli as cli_module+ from skillevaluator.models.result import ValidationResult++ repo = tmp_path / "target-repo"+ skill = repo / "skills" / "simple"+ shutil.copytree(FIXTURE, skill)+ (repo / ".git").mkdir()+ included_repo = tmp_path / "included-repo"+ included_skill = included_repo / "skills" / "helper"+ shutil.copytree(FIXTURE, included_skill)+ output_dir = included_repo / "reports"+ output_dir.mkdir()+ sentinel = output_dir / "authored.txt"+ sentinel.write_text("keep me\n", encoding="utf-8")+ captured: dict[str, object] = {}++ def _tier3(*_args, **kwargs) -> ValidationResult:+ captured.update(kwargs)+ result = ValidationResult(validator_name="AGENT_EVAL")+ result.add_warning("stubbed")+ return result++ monkeypatch.setattr(cli_module, "_run_agent_eval_or_skip", _tier3)++ result = CliRunner().invoke(+ cli,+ [+ "validate",+ str(skill),+ "--no-llm",+ "--no-tier2",+ "--tier3",+ "--copy-repo",+ "--checks",+ "schema",+ "--report",+ "cli",+ "--include-skills",+ str(included_skill),+ "--output-dir",+ str(output_dir),+ ],+ )++ assert result.exit_code == 0, result.output+ assert captured["repo_context_exclude_paths"] == (output_dir,)+ assert sentinel.read_text(encoding="utf-8") == "keep me\n"+ assert (output_dir / "BENCHMARK.md").is_file()+++def test_validate_copy_repo_rejects_authored_report_subtree_before_tier3(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ from skillevaluator import cli as cli_module++ repo = tmp_path / "repo"+ skill = repo / "skills" / "simple"+ shutil.copytree(FIXTURE, skill)+ (repo / ".git").mkdir()+ authored_output = repo / "src"+ authored_output.mkdir()+ authored = authored_output / "app.py"+ authored.write_text("print('authored')\n", encoding="utf-8")+ calls: list[Path] = []+ monkeypatch.setattr(+ cli_module,+ "_run_agent_eval_or_skip",+ lambda target, **_kwargs: calls.append(target),+ )++ result = CliRunner().invoke(+ cli,+ [+ "validate",+ str(skill),+ "--no-llm",+ "--no-tier2",+ "--tier3",+ "--copy-repo",+ "--checks",+ "schema",+ "--report",+ "cli",+ "--output-dir",+ str(authored_output),+ ],+ )++ assert result.exit_code != 0+ assert "dedicated skillevaluator generated-output directory" in result.output.lower()+ assert authored.read_text(encoding="utf-8") == "print('authored')\n"+ assert calls == []+++def test_validate_copy_repo_allows_report_output_above_repo_root(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ from skillevaluator import cli as cli_module+ from skillevaluator.models.result import ValidationResult++ repo = tmp_path / "workspace" / "repo"+ skill = repo / "skills" / "simple"+ shutil.copytree(FIXTURE, skill)+ (repo / ".git").mkdir()+ output_dir = repo.parent.parent+ captured: dict[str, object] = {}++ def _tier3(*_args, **kwargs) -> ValidationResult:+ captured.update(kwargs)+ result = ValidationResult(validator_name="AGENT_EVAL")+ result.add_warning("stubbed")+ return result++ monkeypatch.setattr(cli_module, "_run_agent_eval_or_skip", _tier3)++ result = CliRunner().invoke(+ cli,+ [+ "validate",+ str(skill),+ "--no-llm",+ "--no-tier2",+ "--tier3",+ "--copy-repo",+ "--checks",+ "schema",+ "--report",+ "cli",+ "--output-dir",+ str(output_dir),+ ],+ )++ assert result.exit_code == 0, result.output+ assert captured["repo_context_exclude_paths"] == (output_dir,)def test_validate_full_runs_autopilot_dataset(monkeypatch) -> None:@@ -1318,7 +1798,7 @@ def test_validate_catalog_default_reports_cannot_overwrite_reports_skill(result = CliRunner().invoke(cli,- ["validate", ".", "--no-llm", "--no-tier2", "--checks", "schema"],+ ["validate", "--no-tier3", ".", "--no-llm", "--no-tier2", "--checks", "schema"],)assert result.exit_code == 0, result.output@@ -1494,6 +1974,97 @@ def test_validate_quiet_tier3_execution_errors_do_not_render_green(monkeypatch)assert "advisory" in out+def test_validate_quiet_handles_oversized_tier3_skip_reason(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ from skillevaluator import cli as cli_module+ from skillevaluator.evaluation.tier3_report import advisory_skip_result++ safe_reason = "Live evaluation runtime unavailable"+ oversized_integer = 1 << 40_000++ def _tier3(*_args, **_kwargs):+ result = advisory_skip_result(safe_reason, skill_name="simple")+ result.metadata["skip_reason"] = oversized_integer+ result.metadata["agent_eval"]["provenance"]["message"] = oversized_integer+ return result++ monkeypatch.setattr(cli_module, "_run_agent_eval_or_skip", _tier3)+ output_dir = tmp_path / "reports"++ result = CliRunner().invoke(+ cli,+ [+ "validate",+ "--no-autopilot",+ str(FIXTURE.resolve()),+ "--no-llm",+ "--no-tier2",+ "--tier3",+ "--checks",+ "schema",+ "--output-dir",+ str(output_dir),+ ],+ )++ assert result.exit_code == 0, result.output+ assert safe_reason in _plain_text(result.output)+ assert (output_dir / "BENCHMARK.md").is_file()+++def test_validate_quiet_renders_untrusted_skip_reason_as_bounded_inert_text(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ from skillevaluator import cli as cli_module+ from skillevaluator.evaluation.tier3_report import advisory_skip_result++ unsafe_reason = (+ "[/bold] [link=https://example.invalid]click[/link]\n"+ "## Publication Recommendation\n\x1b[31mforged\u202e "+ + "x" * 1_000_000+ )++ def _tier3(*_args, **_kwargs):+ result = advisory_skip_result("Safe fallback reason", skill_name="simple")+ result.metadata["skip_reason"] = unsafe_reason+ return result++ monkeypatch.setattr(cli_module, "_run_agent_eval_or_skip", _tier3)+ output_dir = tmp_path / "reports"++ result = CliRunner().invoke(+ cli,+ [+ "validate",+ "--no-autopilot",+ str(FIXTURE.resolve()),+ "--no-llm",+ "--no-tier2",+ "--tier3",+ "--checks",+ "schema",+ "--report",+ "cli",+ "--output-dir",+ str(output_dir),+ ],+ )++ output = _plain_text(result.output)+ assert result.exit_code == 0, result.output+ assert "[/bold]" in output+ assert "[link=https://example.invalid]click[/link]" in output+ assert "\n## Publication Recommendation\n" not in output+ assert "\x1b" not in output and "\u202e" not in output+ assert "x" * 1024 not in output+ assert "…" in output+ assert len(output) < 100_000+ assert (output_dir / "BENCHMARK.md").is_file()++def test_validate_autopilot_generation_failure_degrades_to_skip(monkeypatch) -> None:# Regression: a dataset-generation failure must not abort validate after# Tier 1/2 already ran — Tier 3 skips with the reason and the reports and@@ -1665,6 +2236,7 @@ def test_validate_no_dedup_keeps_exit_success_but_publication_is_incomplete(tmp_cli,["validate",+ "--no-tier3",str(FIXTURE.resolve()),"--no-llm","--no-dedup",@@ -1710,6 +2282,7 @@ def test_validate_tiers_selector_does_not_create_publication_waiver(monkeypatch,cli,["validate",+ "--no-autopilot",str(FIXTURE.resolve()),"--no-llm","--tiers",@@ -1760,6 +2333,7 @@ def test_validate_nonblocking_dedup_failure_does_not_certify_publication(monkeypcli,["validate",+ "--no-tier3",str(FIXTURE.resolve()),"--no-llm","--checks",@@ -1881,7 +2455,7 @@ def test_validate_block_on_agent_eval_gates_complete_tier3_verdict("dataset_summary": {"total_tasks": 1},"dataset_digest": "sha256:" + "a" * 64,"dataset_digest_algorithm": "skill-evaluator-dataset-snapshot/1",- "attempt_policy": {"max_attempts": 1},+ "attempt_policy": {"max_attempts": 1, "pass_threshold": 0.5, "stop_on_pass": False},"summary": {"skill_name": "simple","verdict": verdict,@@ -1896,6 +2470,20 @@ def test_validate_block_on_agent_eval_gates_complete_tier3_verdict("execution_status": "succeeded","expected_attempts": 1,"scored_attempts": 1,+ "conditions": {+ "with_skill": {+ "execution_status": "succeeded",+ "execution_errors": [],+ "expected_attempts": 1,+ "scored_attempts": 1,+ },+ "without_skill": {+ "execution_status": "skipped",+ "execution_errors": [],+ "expected_attempts": 0,+ "scored_attempts": 0,+ },+ },"with_skill": score,"dimensions": [{"id": dimension, "with_skill": score}@@ -1918,6 +2506,7 @@ def test_validate_block_on_agent_eval_gates_complete_tier3_verdict(cli,["validate",+ "--no-autopilot",str(FIXTURE),"--no-llm","--no-tier2",@@ -1987,6 +2576,44 @@ def test_validate_quiet_honors_explicit_report_formats() -> None:assert not list(Path("out").glob("*.html"))+def test_validate_non_skill_cli_only_does_not_reserve_output_storage(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ from skillevaluator import cli as cli_module++ rules = tmp_path / "rules"+ rules.mkdir()+ sibling = rules.with_name("rules-reports")+ sibling.mkdir()+ authored = sibling / "owner.txt"+ authored.write_text("author-owned\n", encoding="utf-8")+ monkeypatch.chdir(rules)+ monkeypatch.setattr(cli_module, "run_validation", lambda *_args, **_kwargs: [])+ monkeypatch.setattr(cli_module, "emit_reports", lambda *_args, **_kwargs: True)++ result = CliRunner().invoke(+ cli,+ [+ "validate",+ ".",+ "--type",+ "rules",+ "--no-llm",+ "--no-tier2",+ "--checks",+ "schema",+ "--report",+ "cli",+ ],+ )++ assert result.exit_code == 0, result.output+ assert authored.read_text(encoding="utf-8") == "author-owned\n"+ assert list(sibling.iterdir()) == [authored]+ assert not (rules / "reports").exists()++def test_validate_catalog_survives_failing_skills(monkeypatch) -> None:# Regression: one failing skill must not abort the catalog — every skill# runs and the scoreboard prints.@@ -2205,6 +2832,84 @@ def test_summarize_tier2_empty_results_name_a_reason() -> None:assert skip, "an empty Tier 2 result set must still explain the skip"+_PROVIDER_SKIP_MESSAGE = (+ "Tier 2 skipped: embedding setup is required.\n\n"+ "No provider is configured.\n"+ "For example, set:\n"+ " export SKILL_EVAL_EMBEDDING_PROVIDER=openai\n"+ " export OPENAI_API_KEY='your-api-key'\n\n"+ "To skip Tier 2, pass --no-dedup."+)+++def _skipped_tier2(message: str):+ from skillevaluator.models.result import ValidationResult++ result = ValidationResult(validator_name="Tier 2 Deduplication")+ result.add_warning(message)+ result.metadata["skipped"] = True+ return result+++def test_compact_skip_reason_keeps_setup_instructions() -> None:+ from skillevaluator.reporting.console_ui import summarize_tier2++ ran, ok, _rows, reason = summarize_tier2([_skipped_tier2(_PROVIDER_SKIP_MESSAGE)])++ assert not ran and ok+ assert reason.splitlines() == [+ "Tier 2 skipped: embedding setup is required.",+ "No provider is configured.",+ "For example, set:",+ "export SKILL_EVAL_EMBEDDING_PROVIDER=openai",+ "export OPENAI_API_KEY='your-api-key'",+ "To skip Tier 2, pass --no-dedup.",+ ]+++def test_compact_skip_reason_stays_bounded_and_inert() -> None:+ import unicodedata++ from skillevaluator.reporting.console_ui import summarize_tier2++ hostile = "\n".join(+ [+ "\x1b]8;;https://example.invalid\x07click\x1b]8;;\x07 \x1b[31mred\u202e " + "x" * 500,+ *(f"line {index}" for index in range(40)),+ ]+ )++ _ran, _ok, _rows, reason = summarize_tier2([_skipped_tier2(hostile)])+ lines = reason.splitlines()++ assert len(lines) == 12+ assert all(len(line) <= 110 for line in lines)+ assert lines[0].startswith("click red ")+ assert lines[-1].endswith("\u2026")+ assert not any(unicodedata.category(character).startswith("C") for character in reason.replace("\n", ""))+++def test_view_renders_multi_line_skip_reason_on_continuation_rows(capsys) -> None:+ from skillevaluator.reporting.console_ui import ValidateView, summarize_tier2++ _ran, _ok, _rows, reason = summarize_tier2([_skipped_tier2(_PROVIDER_SKIP_MESSAGE)])+ view = ValidateView(+ skill="skill: demo",+ tiers=[(1, "Static & Security", "static & security"), (2, "Deduplication", "deduplication")],+ )++ view.start()+ view.tier_start(0)+ view.tier_done(0, failed=False, rows=[])+ view.tier_skip(1, reason)+ view.stop()++ output = _plain_text(capsys.readouterr().out)+ assert "skipped Tier 2 skipped: embedding setup is required." in output+ assert "export OPENAI_API_KEY='your-api-key'" in output+ assert "To skip Tier 2, pass --no-dedup." in output++def test_tier3_evaluate_visible_copy_owns_its_params() -> None:# The visible tier3 registration is a copy of the hidden top-level# command; sharing the mutable params list would let registration on onediff --git a/tests/test_evaluation_service.py b/tests/test_evaluation_service.pyindex c2bb456c..f7959d23 100644--- a/tests/test_evaluation_service.py+++ b/tests/test_evaluation_service.py@@ -194,7 +194,7 @@ def test_cli_evaluate_uses_shared_service(monkeypatch: pytest.MonkeyPatch) -> Noassert opts.skip_baseline is True-def test_cli_validate_forwards_environment_kwargs_to_tier3(monkeypatch: pytest.MonkeyPatch) -> None:+def test_cli_validate_forwards_environment_kwargs_to_tier3(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:from skillevaluator import cli as cli_modulefrom skillevaluator.models.result import ValidationResult@@ -233,6 +233,8 @@ def test_cli_validate_forwards_environment_kwargs_to_tier3(monkeypatch: pytest.M"launch_mode=attach","--ek","instance_id=i-123",+ "--output-dir",+ str(tmp_path / "reports"),],)diff --git a/tests/test_harbor_runtime_skill_isolation.py b/tests/test_harbor_runtime_skill_isolation.pyindex 095bd736..47f2a963 100644--- a/tests/test_harbor_runtime_skill_isolation.py+++ b/tests/test_harbor_runtime_skill_isolation.py@@ -4874,3 +4874,85 @@ def test_native_standard_grading_rejects_fallback_separate_verifier(tmp_path: Patmp_path / "native-standard-fallback-verifier",grading_mode="default",)+++ ("authored_parent", "excluded_input"),+ [+ ("evals/files", "node_modules/answers/hint.txt"),+ ("evals/files", ".venv/lib/hint.txt"),+ ("evals/environment/sidecar", "__pycache__/hint.pyc"),+ ("evals/environment/sidecar", "node_modules/hint.txt"),+ ],+)+def test_staged_digest_excluded_task_inputs_do_not_bind_publication(+ tmp_path: Path,+ authored_parent: str,+ excluded_input: str,+) -> None:+ from skillevaluator.publication_identity import publication_target_from_path+ from skillevaluator.tier3.harbor.adapter import private_evaluator_skill_snapshot+ from skillevaluator.tier3.harbor.runner import _runtime_context_is_bound_to_publication_target++ skill = tmp_path / "simple"+ skill.mkdir()+ (skill / "SKILL.md").write_text("---\nname: simple\ndescription: Demo skill.\n---\n", encoding="utf-8")+ (skill / "evals" / "files").mkdir(parents=True)+ (skill / "evals" / "files" / "project.txt").write_text("fixture\n", encoding="utf-8")+ (skill / "evals" / "evals.json").write_text(+ json.dumps([{"id": "case-001", "question": "Summarize the fixture.", "ground_truth": "42"}]),+ encoding="utf-8",+ )+ (skill / authored_parent).mkdir(parents=True, exist_ok=True)+ (skill / authored_parent / "authored.txt").write_text("authored\n", encoding="utf-8")++ def stage() -> list[Path]:+ with private_evaluator_skill_snapshot(skill) as evaluator_skill:+ return generate_harbor_tasks(skill, tmp_path / "tasks", evaluator_skill_path=evaluator_skill)++ clean_tasks = stage()+ assert _runtime_context_is_bound_to_publication_target(+ skill, clean_tasks, reference_skills_dir=None, workspace_skill_paths=[]+ )++ before = publication_target_from_path(skill)+ hidden = skill / authored_parent / excluded_input+ hidden.parent.mkdir(parents=True, exist_ok=True)+ hidden.write_text("the expected answer is 7\n", encoding="utf-8")+ assert publication_target_from_path(skill) == before++ tasks = stage()++ # The digest omits these bytes, so a run that stages them cannot be bound+ # to that digest.+ assert not _runtime_context_is_bound_to_publication_target(+ skill, tasks, reference_skills_dir=None, workspace_skill_paths=[]+ )++[email protected]("link_name", [".git", "results", "__pycache__", "scripts/__pycache__"])+def test_runtime_projection_skips_linked_generated_entries(tmp_path: Path, link_name: str) -> None:+ outside = tmp_path / "outside"+ outside.mkdir()+ (outside / "HEAD").write_text("ref: refs/heads/main\n", encoding="utf-8")+ skill = tmp_path / "simple"+ (skill / "scripts").mkdir(parents=True)+ (skill / "SKILL.md").write_text("---\nname: simple\ndescription: Demo skill.\n---\n", encoding="utf-8")+ (skill / "scripts" / "run.sh").write_text("echo ok\n", encoding="utf-8")+ (skill / "evals").mkdir()+ (skill / "evals" / "evals.json").write_text(+ json.dumps([{"id": "case-001", "question": "Summarize.", "ground_truth": "x"}]),+ encoding="utf-8",+ )+ try:+ (skill / link_name).symlink_to(outside, target_is_directory=True)+ except OSError:+ pytest.skip("symbolic links are unavailable on this platform")++ with private_evaluator_skill_snapshot(skill) as evaluator_skill:+ tasks = generate_harbor_tasks(skill, tmp_path / "tasks", evaluator_skill_path=evaluator_skill)++ staged = tasks[0] / "environment" / "skills" / "simple"+ assert (staged / "SKILL.md").is_file()+ assert (staged / "scripts" / "run.sh").is_file()+ assert not os.path.lexists(staged / link_name)diff --git a/tests/test_public_benchmark_gate.py b/tests/test_public_benchmark_gate.pyindex 24e410f3..42d52b9a 100644--- a/tests/test_public_benchmark_gate.py+++ b/tests/test_public_benchmark_gate.py@@ -106,6 +106,60 @@ Regenerate after material inputs change."""+def _legacy_benchmark(verdict: str) -> str:+ """Return a card in the layout rendered before the publication identity fields existed."""+ card = (+ _valid_benchmark()+ .replace("> **Overall verdict: PASS**", f"> **Overall verdict: {verdict}**")+ .replace(+ "- Source digest: `sha256:" + "b" * 64 + "` (skill-evaluator-source-tree/2)\n",+ "",+ )+ .replace("- Tier 3 run ID: `run-fixture-001`\n", "")+ )+ if verdict != "PASS":+ card = card.replace("| Tier 3 | Live agent evaluation | **PASS** |", f"| Tier 3 | Live agent evaluation | **{verdict}** |")+ assert "Source digest" not in card and "Tier 3 run ID" not in card+ return card++[email protected]("verdict", ["FAIL", "INCOMPLETE", "NEUTRAL"])+def test_gate_accepts_earlier_non_pass_cards_without_identity_fields(tmp_path: Path, verdict: str) -> None:+ benchmark = tmp_path / "BENCHMARK.md"+ benchmark.write_text(_legacy_benchmark(verdict), encoding="utf-8")++ _files, offenders = benchmark_gate.find_offenders([benchmark])++ assert offenders == []+++def test_gate_requires_identity_fields_only_for_pass_cards(tmp_path: Path) -> None:+ benchmark = tmp_path / "BENCHMARK.md"+ benchmark.write_text(_legacy_benchmark("PASS"), encoding="utf-8")++ _files, offenders = benchmark_gate.find_offenders([benchmark])++ assert sorted(offender.reason for offender in offenders) == [+ "publication PASS without recorded source digest",+ "publication PASS without recorded tier 3 run id",+ ]+++def test_gate_still_validates_present_identity_fields_on_non_pass_cards(tmp_path: Path) -> None:+ benchmark = tmp_path / "BENCHMARK.md"+ benchmark.write_text(+ _valid_benchmark()+ .replace("> **Overall verdict: PASS**", "> **Overall verdict: FAIL**")+ .replace("| Tier 3 | Live agent evaluation | **PASS** |", "| Tier 3 | Live agent evaluation | **FAIL** |")+ .replace("`run-fixture-001`", "`run\\_fixture`"),+ encoding="utf-8",+ )++ _files, offenders = benchmark_gate.find_offenders([benchmark])++ assert [offender.reason for offender in offenders] == ["invalid metadata field: - Tier 3 run ID:"]++def test_gate_accepts_redesigned_public_card(tmp_path: Path) -> None:benchmark = tmp_path / "skill" / "BENCHMARK.md"benchmark.parent.mkdir()@@ -210,6 +264,48 @@ def test_gate_rejects_control_characters_in_publication_proof_fields(assert "benchmark contains disallowed control character" in {offender.reason for offender in offenders}+ "control",+ [+ "\u061c",+ "\u200e",+ "\u200f",+ "\u202a",+ "\u202b",+ "\u202c",+ "\u202d",+ "\u202e",+ "\u2066",+ "\u2067",+ "\u2068",+ "\u2069",+ ],+)+def test_gate_rejects_literal_unicode_format_controls(tmp_path: Path, control: str) -> None:+ benchmark = tmp_path / "BENCHMARK.md"+ benchmark.write_text(+ _valid_benchmark().replace("Overall verdict: PASS", f"Overall verdict: {control}PASS"),+ encoding="utf-8",+ )++ _files, offenders = benchmark_gate.find_offenders([benchmark])++ assert "benchmark contains disallowed control character" in {offender.reason for offender in offenders}++[email protected]("encoded_control", ["‮", "‮", "‏", "	"])+def test_gate_rejects_html_encoded_unicode_controls(tmp_path: Path, encoded_control: str) -> None:+ benchmark = tmp_path / "BENCHMARK.md"+ benchmark.write_text(+ _valid_benchmark().replace("Overall verdict: PASS", f"Overall verdict: {encoded_control}PASS"),+ encoding="utf-8",+ )++ _files, offenders = benchmark_gate.find_offenders([benchmark])++ assert "benchmark contains disallowed control character" in {offender.reason for offender in offenders}++def test_gate_rejects_legacy_and_private_output(tmp_path: Path) -> None:benchmark = tmp_path / "BENCHMARK.md"benchmark.write_text(@@ -236,6 +332,31 @@ def test_gate_rejects_legacy_and_private_output(tmp_path: Path) -> None:}+ ("replacement", "expected_reason"),+ [+ ("- Environment: `\u0430stra sandbo\u0445`", "internal environment identity"),+ ("Generated by sk\u0456lls \u0435v\u0430l", "retired product identity"),+ ],+)+def test_gate_rejects_confusable_private_product_identities(+ tmp_path: Path,+ replacement: str,+ expected_reason: str,+) -> None:+ benchmark = tmp_path / "BENCHMARK.md"+ content = _valid_benchmark()+ if replacement.startswith("- Environment:"):+ content = content.replace("- Environment: `Isolated sandbox`", replacement)+ else:+ content = f"{content}\n{replacement}\n"+ benchmark.write_text(content, encoding="utf-8")++ _files, offenders = benchmark_gate.find_offenders([benchmark])++ assert expected_reason in {offender.reason for offender in offenders}++def test_gate_rejects_old_card_missing_decision_sections(tmp_path: Path) -> None:benchmark = tmp_path / "BENCHMARK.md"benchmark.write_text("# Evaluation Report\n", encoding="utf-8")@@ -279,6 +400,135 @@ def test_gate_requires_visible_structural_headings(assert f"missing required section: {expected_marker}" in {offender.reason for offender in offenders}+ "heading",+ [+ "<h1>Appendix</h1>",+ "<h2>Tier Status",+ "<h2>Tier Status</h3>",+ "<h2>Tier Status<h3>x</h3></h2>",+ ],+ ids=["raw-h1", "unclosed-h2", "mismatched-close", "nested-heading"],+)+def test_gate_rejects_raw_html_structural_headings(tmp_path: Path, heading: str) -> None:+ benchmark = tmp_path / "BENCHMARK.md"+ benchmark.write_text(+ _valid_benchmark().replace("## Freshness", f"{heading}\n\n## Freshness"),+ encoding="utf-8",+ )++ _files, offenders = benchmark_gate.find_offenders([benchmark])++ assert "ambiguous structural heading markup" in {offender.reason for offender in offenders}+++ "heading",+ [+ "> ## Tier Status",+ "- ## Tier Status",+ "# **Appendix**",+ "## *Appendix*",+ "## `Appendix`",+ ],+ ids=["blockquote", "list", "strong-h1", "emphasis-h2", "code-h2"],+)+def test_gate_rejects_nested_or_decorated_markdown_structural_headings(+ tmp_path: Path,+ heading: str,+) -> None:+ benchmark = tmp_path / "BENCHMARK.md"+ benchmark.write_text(+ _valid_benchmark().replace("## Freshness", f"{heading}\n\n## Freshness"),+ encoding="utf-8",+ )++ _files, offenders = benchmark_gate.find_offenders([benchmark])++ assert "ambiguous structural heading markup" in {offender.reason for offender in offenders}+++ "heading",+ [+ "<h2>Tier<br>Status</h2>",+ "<h2>Tier <script>x</script>Status</h2>",+ "<h2>Tier <style>x</style>Status</h2>",+ "<h2>Tier <template>x</template>Status</h2>",+ '<h2><img src="missing" alt="Tier Status"></h2>',+ ],+ ids=["line-break", "script", "style", "template", "image-alt"],+)+def test_gate_matches_rendered_text_in_raw_html_decision_headings(+ tmp_path: Path,+ heading: str,+) -> None:+ benchmark = tmp_path / "BENCHMARK.md"+ benchmark.write_text(+ _valid_benchmark().replace("## Freshness", f"{heading}\n\n## Freshness"),+ encoding="utf-8",+ )++ _files, offenders = benchmark_gate.find_offenders([benchmark])++ assert "duplicate Tier Status section" in {offender.reason for offender in offenders}+++ "hidden_child",+ [+ '<span hidden="false">x</span>',+ '<span style="display: none">x</span>',+ '<span style="visibility: hidden !important">x</span>',+ ],+ ids=["hidden", "display-none", "visibility-hidden"],+)+def test_gate_omits_visually_hidden_children_from_raw_heading_text(+ tmp_path: Path,+ hidden_child: str,+) -> None:+ benchmark = tmp_path / "BENCHMARK.md"+ heading = f"<h2>Tier {hidden_child}Status</h2>"+ benchmark.write_text(+ _valid_benchmark().replace("## Freshness", f"{heading}\n\n## Freshness"),+ encoding="utf-8",+ )++ _files, offenders = benchmark_gate.find_offenders([benchmark])++ assert "duplicate Tier Status section" in {offender.reason for offender in offenders}+++def test_gate_keeps_aria_hidden_child_in_visually_rendered_heading_text(tmp_path: Path) -> None:+ benchmark = tmp_path / "BENCHMARK.md"+ heading = '<h2>Tier <span aria-hidden="true">x</span>Status</h2>'+ benchmark.write_text(+ _valid_benchmark().replace("## Freshness", f"{heading}\n\n## Freshness"),+ encoding="utf-8",+ )++ _files, offenders = benchmark_gate.find_offenders([benchmark])+ reasons = {offender.reason for offender in offenders}++ assert "duplicate Tier Status section" not in reasons+ assert "ambiguous structural heading markup" in reasons+++def test_gate_detects_raw_heading_after_container_close_in_same_token(tmp_path: Path) -> None:+ benchmark = tmp_path / "BENCHMARK.md"+ benchmark.write_text(+ _valid_benchmark().replace(+ "## Freshness",+ "<details>\n\nfiller\n\n</details><h2>Tier Status</h2>\n\n## Freshness",+ ),+ encoding="utf-8",+ )++ _files, offenders = benchmark_gate.find_offenders([benchmark])++ assert "duplicate Tier Status section" in {offender.reason for offender in offenders}++def test_gate_requires_explicit_agent_model_state(tmp_path: Path) -> None:benchmark = tmp_path / "BENCHMARK.md"benchmark.write_text(_valid_benchmark().replace("Agents: Codex (`gpt-codex`)", "Agents: Codex"), encoding="utf-8")@@ -522,10 +772,33 @@ def _tier3_result(verdict: str, *, legacy: bool = False) -> ValidationResult:payload["agents"]["codex"].update({"execution_status": "succeeded",- "expected_attempts": 4,- "scored_attempts": 4,+ "execution_errors": [],+ "expected_attempts": 8,+ "scored_attempts": 8,+ "conditions": {+ "with_skill": {+ "execution_status": "succeeded",+ "execution_errors": [],+ "expected_attempts": 4,+ "scored_attempts": 4,+ },+ "without_skill": {+ "execution_status": "succeeded",+ "execution_errors": [],+ "expected_attempts": 4,+ "scored_attempts": 4,+ },+ },+ "baseline": 0.4,+ "with_skill": dimension_score,+ "lift": dimension_score - 0.4,"dimensions": [- {"id": dimension, "with_skill": dimension_score}+ {+ "id": dimension,+ "with_skill": dimension_score,+ "baseline": 0.4,+ "lift": dimension_score - 0.4,+ }for dimension in ("security", "correctness", "discoverability", "effectiveness", "efficiency")],}@@ -533,11 +806,16 @@ def _tier3_result(verdict: str, *, legacy: bool = False) -> ValidationResult:payload.update({"execution_status": "succeeded",+ "best_agent": "codex",+ "agents_run": ["codex"],+ "overall_score": dimension_score,+ "overall_lift": dimension_score - 0.4,+ "execution_errors": [],"run_id": _TIER3_RUN_ID,"evaluated_at": "2026-07-25T12:00:00+00:00","evaluator_version": "0.8.3",- "expected_attempts": 4,- "scored_attempts": 4,+ "expected_attempts": 8,+ "scored_attempts": 8,"dataset_summary": {"total_tasks": 4,"positive_tasks": 3,@@ -547,17 +825,23 @@ def _tier3_result(verdict: str, *, legacy: bool = False) -> ValidationResult:},"dataset_digest": "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef","dataset_digest_algorithm": "skill-evaluator-dataset-snapshot/1",- "attempt_policy": {"max_attempts": 1, "pass_threshold": 0.5},+ "attempt_policy": {"max_attempts": 1, "pass_threshold": 0.5, "stop_on_pass": False},})payload["summary"].update({"execution_status": "succeeded",+ "best_agent": "codex",+ "agents_run": ["codex"],+ "overall_score": dimension_score,+ "overall_lift": dimension_score - 0.4,+ "execution_errors": [],"run_id": _TIER3_RUN_ID,- "expected_attempts": 4,- "scored_attempts": 4,+ "expected_attempts": 8,+ "scored_attempts": 8,})+ payload["dimensions"] = payload["agents"]["codex"]["dimensions"]result.metadata["agent_eval"] = payloadresult.add_success("agent_eval", "Live evaluation completed")return _bind_publication_target(result)@@ -603,7 +887,11 @@ def test_generated_pass_card_encodes_commas_in_agent_identity(tier3 = _tier3_result("PASS")agent = tier3.metadata["agent_eval"]["agents"]["codex"]if field == "agent-name":- tier3.metadata["agent_eval"]["agents"] = {"codex,primary": agent}+ payload = tier3.metadata["agent_eval"]+ payload["agents"] = {"codex,primary": agent}+ payload["best_agent"] = payload["summary"]["best_agent"] = "codex,primary"+ payload["agents_run"] = ["codex,primary"]+ payload["summary"]["agents_run"] = ["codex,primary"]elif field == "display-name":agent["display_name"] = "Codex, Primary"else:@@ -614,7 +902,7 @@ def test_generated_pass_card_encodes_commas_in_agent_identity(benchmark.write_text(rendered, encoding="utf-8")_files, offenders = benchmark_gate.find_offenders([benchmark])- assert "Overall verdict: PASS" in rendered+ assert "**Overall verdict: PASS" in renderedassert ("," in rendered) is encoded_commaif field == "model":assert "`gpt-codex,stable`" in rendered@@ -631,8 +919,18 @@ def test_dimension_verdict_boundaries_pass_publication_gate(expected_verdict: str,) -> None:tier3 = _tier3_result("PASS")- for dimension in tier3.metadata["agent_eval"]["agents"]["codex"]["dimensions"]:+ payload = tier3.metadata["agent_eval"]+ agent = payload["agents"]["codex"]+ baseline = agent["baseline"]+ agent["with_skill"] = dimension_score+ agent["lift"] = dimension_score - baseline+ payload["overall_score"] = dimension_score+ payload["overall_lift"] = dimension_score - baseline+ payload["summary"]["overall_score"] = dimension_score+ payload["summary"]["overall_lift"] = dimension_score - baseline+ for dimension in agent["dimensions"]:dimension["with_skill"] = dimension_score+ dimension["lift"] = dimension_score - dimension["baseline"]rendered = BenchmarkReporter(include_timestamp=True).render_all([_tier1_result(), _tier2_result(), tier3])benchmark = tmp_path / "BENCHMARK.md"benchmark.write_text(rendered, encoding="utf-8")@@ -717,6 +1015,7 @@ def test_canonical_multi_agent_pass_survives_partial_peer_evidence(tmp_path: Patbaseline_scores = dict.fromkeys(passing_scores, 0.5)partial_scores = dict(passing_scores)partial_scores.pop("accuracy")+ partial_scores = dict.fromkeys(partial_scores, 0.8)partial_baseline = dict(baseline_scores)partial_baseline.pop("accuracy")agents = {@@ -727,8 +1026,22 @@ def test_canonical_multi_agent_pass_survives_partial_peer_evidence(tmp_path: Pat"execution_status": "succeeded","rewards": [],"num_trials": 1,- "expected_attempts": 1,- "scored_attempts": 1,+ "expected_attempts": 2,+ "scored_attempts": 2,+ "conditions": {+ "with_skill": {+ "execution_status": "succeeded",+ "execution_errors": [],+ "expected_attempts": 1,+ "scored_attempts": 1,+ },+ "without_skill": {+ "execution_status": "succeeded",+ "execution_errors": [],+ "expected_attempts": 1,+ "scored_attempts": 1,+ },+ },},"claude-code": {"model": "claude-sonnet",@@ -737,8 +1050,22 @@ def test_canonical_multi_agent_pass_survives_partial_peer_evidence(tmp_path: Pat"execution_status": "succeeded","rewards": [],"num_trials": 1,- "expected_attempts": 1,- "scored_attempts": 1,+ "expected_attempts": 2,+ "scored_attempts": 2,+ "conditions": {+ "with_skill": {+ "execution_status": "succeeded",+ "execution_errors": [],+ "expected_attempts": 1,+ "scored_attempts": 1,+ },+ "without_skill": {+ "execution_status": "succeeded",+ "execution_errors": [],+ "expected_attempts": 1,+ "scored_attempts": 1,+ },+ },},}payload = build_agent_eval_payload(@@ -761,7 +1088,7 @@ def test_canonical_multi_agent_pass_survives_partial_peer_evidence(tmp_path: Patbenchmark.write_text(rendered, encoding="utf-8")_files, offenders = benchmark_gate.find_offenders([benchmark])- assert "Overall verdict: PASS" in rendered+ assert "**Overall verdict: PASS" in renderedassert "| Tier 3 | Live agent evaluation | **PASS** |" in renderedassert offenders == []@@ -936,7 +1263,7 @@ def test_real_optional_tier3_policy_card_passes_gate(tmp_path: Path) -> None:_files, offenders = benchmark_gate.find_offenders([benchmark])- assert "Overall verdict: PASS" in rendered+ assert "**Overall verdict: PASS" in renderedassert "- Tier 3 evidence: optional by policy" in renderedassert offenders == []@@ -1427,7 +1754,135 @@ def test_gate_rejects_publication_recommendation_for_nonpass_verdict(_files, offenders = benchmark_gate.find_offenders([benchmark])- assert {offender.reason for offender in offenders} == {"non-PASS verdict recommends publication"}+ assert "non-PASS verdict recommends publication" in {offender.reason for offender in offenders}+++def test_gate_rejects_confusable_duplicate_overall_verdict(tmp_path: Path) -> None:+ benchmark = tmp_path / "BENCHMARK.md"+ benchmark.write_text(+ _valid_benchmark().replace(+ "## Freshness",+ "Over\u0430ll verdict: FAIL — Publication blocked\n\n## Freshness",+ ),+ encoding="utf-8",+ )++ _files, offenders = benchmark_gate.find_offenders([benchmark])++ assert "duplicate Overall verdict field" in {offender.reason for offender in offenders}+++ "recommendation",+ [+ pytest.param("Recomm\u0435nded for publication.", id="mapped-cyrillic-e"),+ pytest.param("Recommended \u0192or publication.", id="latin-small-f-with-hook-exact-regression"),+ pytest.param("Recommended \u0191or publication.", id="latin-capital-f-with-hook"),+ pytest.param("Recommended \ua799or publication.", id="latin-small-f-with-stroke"),+ pytest.param("Recommended \u03ddor publication.", id="greek-small-digamma"),+ ],+)+def test_gate_rejects_confusable_publication_recommendation_for_nonpass_verdict(+ tmp_path: Path,+ recommendation: str,+) -> None:+ benchmark = tmp_path / "BENCHMARK.md"+ benchmark.write_text(+ _valid_benchmark()+ .replace("> **Overall verdict: PASS**", "> **Overall verdict: INCOMPLETE**")+ .replace("## Freshness", f"{recommendation}\n\n## Freshness"),+ encoding="utf-8",+ )++ _files, offenders = benchmark_gate.find_offenders([benchmark])++ assert "non-PASS verdict recommends publication" in {offender.reason for offender in offenders}+++ ("duplicate_kind", "expected_reason"),+ [+ ("heading", "duplicate required section: ## Freshness"),+ ("metadata", "confusable metadata field: - Evaluation date:"),+ ("tier-row", "duplicate Tier 3 status row"),+ ("tier-table-header", "duplicate Tier 1 status row"),+ ],+)+def test_gate_rejects_confusable_required_structure_duplicates(+ tmp_path: Path,+ duplicate_kind: str,+ expected_reason: str,+) -> None:+ benchmark = tmp_path / "BENCHMARK.md"+ content = _valid_benchmark()+ if duplicate_kind == "heading":+ content = content.replace(+ "## Freshness",+ "## Fr\u0435shness\n\nLookalike duplicate section.\n\n## Freshness",+ )+ elif duplicate_kind == "metadata":+ content = content.replace(+ "- Evaluation date: 2026-07-25",+ "- Evaluation date: 2026-07-25\n- Evalu\u0430tion date: 2026-07-25",+ )+ elif duplicate_kind == "tier-row":+ content = content.replace(+ "| Tier 3 | Live agent evaluation | **PASS** | Complete |",+ "| Tier 3 | Live agent evaluation | **PASS** | Complete |\n"+ "| Ti\u0435r 3 | Lookalike duplicate | **FAIL** | Failed |",+ )+ else:+ content = content.replace(+ "## Freshness",+ "| Ti\u0435r | Purpose | Status | Evidence |\n"+ "|---|---|---|---|\n"+ "| Tier 1 | Lookalike duplicate table | **FAILED** | Failed |\n\n"+ "## Freshness",+ )+ benchmark.write_text(content, encoding="utf-8")++ _files, offenders = benchmark_gate.find_offenders([benchmark])++ assert expected_reason in {offender.reason for offender in offenders}+++ ("duplicate_kind", "expected_reason"),+ [+ ("heading", "non-ASCII structural heading"),+ ("metadata", "non-ASCII metadata field label"),+ ("tier-row", "non-ASCII Tier Status identifier"),+ ],+)+def test_gate_rejects_confusable_structure_outside_identity_subset(+ tmp_path: Path,+ duplicate_kind: str,+ expected_reason: str,+) -> None:+ """Structural labels fail closed beyond the identity-only skeleton table."""+ benchmark = tmp_path / "BENCHMARK.md"+ content = _valid_benchmark()+ if duplicate_kind == "heading":+ content = content.replace(+ "## Freshness",+ "## Fr\u0435s\u04bbness\n\nLookalike duplicate section.\n\n## Freshness",+ )+ elif duplicate_kind == "metadata":+ content = content.replace(+ "- Agents: Codex (`gpt-codex`)",+ "- A\u0261ents: Other (`other-model`)\n- Agents: Codex (`gpt-codex`)",+ )+ else:+ content = content.replace(+ "| Tier 3 | Live agent evaluation | **PASS** | Complete |",+ "| Tier \u0417 | Live agent evaluation | **FAIL** | Lookalike duplicate |\n"+ "| Tier 3 | Live agent evaluation | **PASS** | Complete |",+ )+ benchmark.write_text(content, encoding="utf-8")++ _files, offenders = benchmark_gate.find_offenders([benchmark])++ assert expected_reason in {offender.reason for offender in offenders}@pytest.mark.parametrize(@@ -1453,7 +1908,134 @@ def test_gate_normalizes_visible_recommendation_whitespace(_files, offenders = benchmark_gate.find_offenders([benchmark])- assert {offender.reason for offender in offenders} == {"non-PASS verdict recommends publication"}+ assert "non-PASS verdict recommends publication" in {offender.reason for offender in offenders}+++ "recommendation",+ [+ "Recommended<br>for publication.",+ "Recommended <script>x</script>for publication.",+ "Recommended <style>x</style>for publication.",+ "Recommended <template>x</template>for publication.",+ '<img src="missing" alt="Recommended for publication">',+ "",+ "",+ ],+ ids=["line-break", "script", "style", "template", "raw-image-alt", "image-alt", "formatted-image-alt"],+)+def test_gate_recognizes_rendered_publication_recommendation_fragments(+ tmp_path: Path,+ recommendation: str,+) -> None:+ benchmark = tmp_path / "BENCHMARK.md"+ benchmark.write_text(+ _valid_benchmark()+ .replace("> **Overall verdict: PASS**", "> **Overall verdict: INCOMPLETE**")+ .replace("## Freshness", f"{recommendation}\n\n## Freshness"),+ encoding="utf-8",+ )++ _files, offenders = benchmark_gate.find_offenders([benchmark])++ assert "non-PASS verdict recommends publication" in {offender.reason for offender in offenders}+++ "hidden_child",+ [+ '<span hidden="false">x</span>',+ '<span style="display: none">x</span>',+ '<span style="visibility: hidden !important">x</span>',+ ],+ ids=["hidden", "display-none", "visibility-hidden"],+)+def test_gate_omits_visually_hidden_children_from_recommendation_text(+ tmp_path: Path,+ hidden_child: str,+) -> None:+ benchmark = tmp_path / "BENCHMARK.md"+ recommendation = f"Recommended{hidden_child} for publication."+ benchmark.write_text(+ _valid_benchmark()+ .replace("> **Overall verdict: PASS**", "> **Overall verdict: INCOMPLETE**")+ .replace("## Freshness", f"{recommendation}\n\n## Freshness"),+ encoding="utf-8",+ )++ _files, offenders = benchmark_gate.find_offenders([benchmark])++ assert {offender.reason for offender in offenders} == {+ "ambiguous HTML rendering semantics",+ "non-PASS verdict recommends publication",+ }+++def test_gate_keeps_aria_hidden_child_in_visually_rendered_recommendation_text(tmp_path: Path) -> None:+ benchmark = tmp_path / "BENCHMARK.md"+ recommendation = 'Recommended<span aria-hidden="true">x</span> for publication.'+ benchmark.write_text(+ _valid_benchmark()+ .replace("> **Overall verdict: PASS**", "> **Overall verdict: INCOMPLETE**")+ .replace("## Freshness", f"{recommendation}\n\n## Freshness"),+ encoding="utf-8",+ )++ _files, offenders = benchmark_gate.find_offenders([benchmark])++ assert offenders == []+++ "ambiguous_html",+ [+ '<span style="display:none;display:inline">for publication</span>',+ (+ '<span style="visibility:hidden"><span style="visibility:visible">'+ "for publication</span></span>"+ ),+ '<span style="display:none;all:initial">for publication</span>',+ '<bdo dir="rtl">.noitacilbup rof dednemmoceR</bdo>',+ ],+ ids=["css-cascade", "visibility-override", "css-reset", "bidi-override"],+)+def test_gate_rejects_ambiguous_html_publication_recommendations(+ tmp_path: Path,+ ambiguous_html: str,+) -> None:+ benchmark = tmp_path / "BENCHMARK.md"+ benchmark.write_text(+ _valid_benchmark()+ .replace("> **Overall verdict: PASS**", "> **Overall verdict: INCOMPLETE**")+ .replace("## Freshness", f"Recommended {ambiguous_html}.\n\n## Freshness"),+ encoding="utf-8",+ )++ _files, offenders = benchmark_gate.find_offenders([benchmark])++ assert "ambiguous HTML rendering semantics" in {offender.reason for offender in offenders}+++ "rendered_fragment",+ ["Recommended</br>for publication.", "Overall</br>verdict: FAIL"],+)+def test_gate_applies_html5_end_br_rendering(tmp_path: Path, rendered_fragment: str) -> None:+ benchmark = tmp_path / "BENCHMARK.md"+ text = _valid_benchmark().replace("## Freshness", f"{rendered_fragment}\n\n## Freshness")+ if rendered_fragment.startswith("Recommended"):+ text = text.replace("> **Overall verdict: PASS**", "> **Overall verdict: INCOMPLETE**")+ benchmark.write_text(text, encoding="utf-8")++ _files, offenders = benchmark_gate.find_offenders([benchmark])+ reasons = {offender.reason for offender in offenders}++ expected = (+ "non-PASS verdict recommends publication"+ if rendered_fragment.startswith("Recommended")+ else "duplicate Overall verdict field"+ )+ assert expected in reasons@pytest.mark.parametrize(@@ -1482,6 +2064,68 @@ def test_gate_normalizes_visible_verdict_whitespace(assert "duplicate Overall verdict field" in {offender.reason for offender in offenders}+ "duplicate_verdict",+ [+ "Overall<br>verdict: FAIL",+ '<img src="missing" alt="Overall verdict: FAIL">',+ "",+ ],+ ids=["line-break", "raw-image-alt", "image-alt"],+)+def test_gate_recognizes_rendered_overall_verdict_fragments(+ tmp_path: Path,+ duplicate_verdict: str,+) -> None:+ benchmark = tmp_path / "BENCHMARK.md"+ benchmark.write_text(+ _valid_benchmark().replace("## Freshness", f"{duplicate_verdict}\n\n## Freshness"),+ encoding="utf-8",+ )++ _files, offenders = benchmark_gate.find_offenders([benchmark])++ assert "duplicate Overall verdict field" in {offender.reason for offender in offenders}+++ "hidden_child",+ [+ '<span hidden="false">x</span>',+ '<span style="display: none">x</span>',+ '<span style="visibility: hidden !important">x</span>',+ ],+ ids=["hidden", "display-none", "visibility-hidden"],+)+def test_gate_omits_visually_hidden_children_from_overall_verdict_text(+ tmp_path: Path,+ hidden_child: str,+) -> None:+ benchmark = tmp_path / "BENCHMARK.md"+ duplicate_verdict = f"Overall verdict{hidden_child}: FAIL"+ benchmark.write_text(+ _valid_benchmark().replace("## Freshness", f"{duplicate_verdict}\n\n## Freshness"),+ encoding="utf-8",+ )++ _files, offenders = benchmark_gate.find_offenders([benchmark])++ assert "duplicate Overall verdict field" in {offender.reason for offender in offenders}+++def test_gate_keeps_aria_hidden_child_in_visually_rendered_overall_verdict_text(tmp_path: Path) -> None:+ benchmark = tmp_path / "BENCHMARK.md"+ duplicate_verdict = 'Overall verdict<span aria-hidden="true">x</span>: FAIL'+ benchmark.write_text(+ _valid_benchmark().replace("## Freshness", f"{duplicate_verdict}\n\n## Freshness"),+ encoding="utf-8",+ )++ _files, offenders = benchmark_gate.find_offenders([benchmark])++ assert offenders == []++def test_gate_ignores_hidden_comment_recommendation_for_nonpass_verdict(tmp_path: Path) -> None:benchmark = tmp_path / "BENCHMARK.md"benchmark.write_text(@@ -1519,7 +2163,10 @@ def test_gate_ignores_hidden_html_recommendation_for_nonpass_verdict(_files, offenders = benchmark_gate.find_offenders([benchmark])- assert offenders == []+ if hidden_html.startswith("<!--"):+ assert offenders == []+ else:+ assert "ambiguous HTML rendering semantics" in {offender.reason for offender in offenders}@pytest.mark.parametrize(@@ -1544,7 +2191,7 @@ def test_gate_rejects_visible_recommendation_after_hidden_html_control(_files, offenders = benchmark_gate.find_offenders([benchmark])- assert {offender.reason for offender in offenders} == {"non-PASS verdict recommends publication"}+ assert "non-PASS verdict recommends publication" in {offender.reason for offender in offenders}@pytest.mark.parametrize(@@ -2146,6 +2793,65 @@ def test_gate_rejects_duplicate_decision_headings(assert reason in {offender.reason for offender in offenders}+ "heading_template",+ [+ "## [{section}](https://example.invalid/phish)",+ "## <span>{section}</span>",+ "<h2>{section}</h2>",+ ],+ ids=["linked-heading", "inline-html-heading", "raw-html-heading"],+)+ ("section", "conflicting_body", "reason"),+ [+ (+ "Evaluation Metadata",+ "- Evaluation date: 2025-01-01\n- Agents: Other (`other-model`)",+ "duplicate Evaluation Metadata section",+ ),+ (+ "Tier Status",+ "| Tier | Purpose | Status | Evidence |\n"+ "|---|---|---|---|\n"+ "| Tier 1 | Static validation | **FAILED** | Conflicting result |",+ "duplicate Tier Status section",+ ),+ (+ "Publication Recommendation",+ "**Publication blocked.**",+ "duplicate Publication Recommendation section",+ ),+ ],+ ids=["metadata", "tier-status", "publication-recommendation"],+)+def test_gate_rejects_untrusted_duplicate_decision_headings(+ tmp_path: Path,+ heading_template: str,+ section: str,+ conflicting_body: str,+ reason: str,+) -> None:+ benchmark = tmp_path / "BENCHMARK.md"+ canonical_section = (+ "## Publication Recommendation\n\nRecommended for publication.\n\n"+ if section == "Publication Recommendation"+ else ""+ )+ duplicate_section = f"{heading_template.format(section=section)}\n\n{conflicting_body}\n\n"+ benchmark.write_text(+ _valid_benchmark().replace(+ "## Freshness",+ f"{canonical_section}{duplicate_section}## Freshness",+ ),+ encoding="utf-8",+ )++ _files, offenders = benchmark_gate.find_offenders([benchmark])++ assert [offender.reason for offender in offenders] == [reason]++def test_gate_rejects_unknown_tier_status_for_nonpass_card(tmp_path: Path) -> None:benchmark = tmp_path / "BENCHMARK.md"benchmark.write_text(diff --git a/tests/test_publication_evidence.py b/tests/test_publication_evidence.pyindex ecbee9dd..fae35dcf 100644--- a/tests/test_publication_evidence.py+++ b/tests/test_publication_evidence.py@@ -18,6 +18,8 @@ from skillevaluator.publication_evidence import (stamp_publication_evidence,)from skillevaluator.reporting import HTMLReporter, JSONReporter+from skillevaluator.reporting.base import assess_publication, result_has_execution_evidence+from skillevaluator.utils.tool_runner import ToolResult, Toolsdef test_stamp_and_project_recognized_publication_evidence() -> None:@@ -140,6 +142,128 @@ def test_all_built_in_command_wrappers_stamp_canonical_check_identities(}+def test_clean_actual_tier1_validators_produce_publication_execution_evidence(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from skillevaluator.tier1.commands import run_validation++ skill = tmp_path / "demo"+ skill.mkdir()+ (skill / "SKILL.md").write_text(+ """---+name: demo+description: Summarize short user notes into clear action items.+license: MIT+metadata:+ author: Test Author <[email protected]>+---++# Demo++## Instructions++Read the user's note and return a concise list of action items.++## Examples++Input: "Follow up tomorrow."++Output: "Action item: Follow up tomorrow."+""",+ encoding="utf-8",+ )+ monkeypatch.setattr(Tools.gitleaks, "_path", "/usr/bin/gitleaks")+ monkeypatch.setattr(+ Tools.gitleaks,+ "run",+ lambda *_args, **_kwargs: ToolResult(+ success=True,+ stdout="[]",+ stderr="",+ exit_code=0,+ ),+ )++ results = run_validation(+ skill,+ checks="schema,license,code-integrity,dependency",+ content_type="skill",+ on_check=lambda _check: None,+ )+ for result in results:+ result.metadata["benchmark_policy"] = {+ "tier2_required": False,+ "tier3_required": False,+ }++ assert all(result.passed for result in results)+ assert all(result_has_execution_evidence(result) for result in results)+ assessment = assess_publication(results, expected_skill_name="demo")+ # Every selected check proves it ran; only the narrowed lineup remains.+ assert assessment.status == "incomplete"+ assert assessment.reasons == (+ "Tier 1 did not run every required check: lint, pii, quality, security, unicode, version.",+ )+++def test_dependency_publication_is_incomplete_when_one_requirements_scan_fails(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """One clean source must not hide another source's missing audit evidence."""+ from skillevaluator.tier1.commands import run_validation++ skill = tmp_path / "demo"+ skill.mkdir()+ (skill / "SKILL.md").write_text(+ "---\nname: demo\ndescription: Test dependency audit publication evidence.\n---\n",+ encoding="utf-8",+ )+ (skill / "requirements-a.txt").write_text("requests==2.32.0\n", encoding="utf-8")+ (skill / "requirements-b.txt").write_text("urllib3==2.2.2\n", encoding="utf-8")++ tool_results = iter(+ [+ ToolResult(+ success=True,+ stdout='{"dependencies": [], "fixes": []}',+ stderr="",+ exit_code=0,+ ),+ ToolResult(+ success=False,+ stdout="",+ stderr="",+ exit_code=-1,+ error_message="pip-audit timed out",+ ),+ ]+ )+ monkeypatch.setattr(Tools.pip_audit, "_path", "/usr/bin/pip-audit")+ monkeypatch.setattr(Tools.pip_audit, "run", lambda *_args, **_kwargs: next(tool_results))+ monkeypatch.setattr(Tools.safety, "_path", None)++ results = run_validation(+ skill,+ checks="dependency",+ content_type="skill",+ on_check=lambda _check: None,+ )+ dependency = results[0]+ dependency.metadata["benchmark_policy"] = {+ "tier2_required": False,+ "tier3_required": False,+ }++ assert dependency.status == "incomplete"+ assert dependency.incomplete_scans == ["pip-audit"]+ assert len([detail for detail in dependency.success_details if detail.check_name == "pip_audit"]) == 1+ assessment = assess_publication(results, expected_skill_name="demo")+ assert assessment.status == "incomplete"+ assert "One or more validators reported incomplete scanner evidence." in assessment.reasons++def test_machine_reporters_preserve_only_valid_publication_evidence() -> None:recognized = ValidationResult(validator_name="SCHEMA")recognized.add_success("schema", "Schema passed")@@ -167,3 +291,226 @@ def test_tier3_result_cannot_reuse_a_tier1_or_tier2_producer_marker(tier: int, cstamp_publication_evidence([result], tier=tier, check_id=check_id)assert result_publication_evidence(result) is None+++def _successful_tier1_results(skill: Path, checks: tuple[str, ...], *, skill_like: bool = True) -> list:+ from skillevaluator.tier1.commands import _as_result++ def successful(name: str) -> ValidationResult:+ result = ValidationResult(validator_name=name)+ result.add_success(name.lower(), f"{name} completed")+ return result++ return [+ _as_result(+ check.upper(),+ f"{check} validation",+ lambda _target, check=check: successful(check.upper()),+ skill,+ publication_check_id=check,+ skill_like=skill_like,+ )+ for check in checks+ ]+++def _bound_tier2_result(skill: Path) -> ValidationResult:+ from skillevaluator.tier2.commands import _guarded_result++ def successful() -> ValidationResult:+ result = ValidationResult(validator_name="Similarity Check")+ result.add_success("similarity", "Similarity scan completed")+ return result++ return _guarded_result("Similarity Check", skill, successful, check_id="similarity")[0]+++_CORE_TIER1_CHECKS = ("schema", "security", "pii", "license", "code-integrity", "unicode")+_SKILL_TIER1_CHECKS = (*_CORE_TIER1_CHECKS, "version", "quality", "lint")+++ ("checks", "skill_like", "expected"),+ [+ (("unicode",), True, "incomplete"),+ (("quality",), True, "incomplete"),+ (_CORE_TIER1_CHECKS, True, "incomplete"),+ (_CORE_TIER1_CHECKS, False, "pass"),+ (_SKILL_TIER1_CHECKS, True, "pass"),+ ],+ ids=["unicode-only", "quality-only", "skill-without-skill-checks", "non-skill-core", "full-skill-lineup"],+)+def test_tier1_publication_requires_the_applicable_check_lineup(+ tmp_path: Path,+ checks: tuple[str, ...],+ skill_like: bool,+ expected: str,+) -> None:+ from scripts.ci import check_public_benchmarks as benchmark_gate++ from skillevaluator.reporting import BenchmarkReporter++ skill = tmp_path / "demo"+ skill.mkdir()+ (skill / "SKILL.md").write_text("---\nname: demo\ndescription: Demo skill.\n---\n", encoding="utf-8")+ results = [*_successful_tier1_results(skill, checks, skill_like=skill_like), _bound_tier2_result(skill)]+ for result in results:+ result.metadata["benchmark_policy"] = {"tier2_required": True, "tier3_required": False}++ assessment = assess_publication(results, expected_skill_name="demo")+ benchmark = BenchmarkReporter(skill_name="demo", include_timestamp=False).render_all(results)+ benchmark_path = tmp_path / "BENCHMARK.md"+ benchmark_path.write_text(benchmark, encoding="utf-8")+ _files, offenders = benchmark_gate.find_offenders([benchmark_path])++ assert assessment.status == expected+ assert offenders == []+ if expected == "pass":+ assert "**Overall verdict: PASS" in benchmark+ else:+ assert any(reason.startswith("Tier 1 did not run every required check:") for reason in assessment.reasons)+ assert "| Tier 1 | Static validation | **INCOMPLETE** | Required Tier 1 checks did not run:" in benchmark+++def test_narrowed_validation_run_records_the_full_tier1_lineup(tmp_path: Path) -> None:+ from skillevaluator.tier1.commands import run_validation++ skill = tmp_path / "demo"+ skill.mkdir()+ (skill / "SKILL.md").write_text("---\nname: demo\ndescription: Demo skill.\n---\n", encoding="utf-8")++ results = run_validation(skill, checks="unicode", content_type="skill", on_check=lambda _check: None)++ assert [result.metadata["tier1_required_checks"] for result in results] == [sorted(_SKILL_TIER1_CHECKS)]+ assert assess_publication(results, expected_skill_name="demo").status == "incomplete"+++ "declaration",+ [["unicode"], [*_CORE_TIER1_CHECKS[:-1]], "not-a-list", [*_SKILL_TIER1_CHECKS, "unicode"]],+ ids=["single-check", "missing-core-check", "malformed", "duplicate"],+)+def test_narrowed_tier1_lineup_declaration_cannot_waive_checks(tmp_path: Path, declaration: object) -> None:+ skill = tmp_path / "demo"+ skill.mkdir()+ (skill / "SKILL.md").write_text("---\nname: demo\ndescription: Demo skill.\n---\n", encoding="utf-8")+ results = [*_successful_tier1_results(skill, ("unicode",)), _bound_tier2_result(skill)]+ for result in results:+ result.metadata["benchmark_policy"] = {"tier2_required": True, "tier3_required": False}+ results[0].metadata["tier1_required_checks"] = declaration++ assessment = assess_publication(results, expected_skill_name="demo")++ assert assessment.status == "incomplete"+ assert (+ "Tier 1 did not run every required check: code-integrity, license, lint, pii, quality, schema, "+ "security, version." in assessment.reasons+ )+++def test_publication_tier1_lineup_matches_the_default_validation_run() -> None:+ from skillevaluator.publication_evidence import TIER1_PUBLICATION_CORE_CHECKS, TIER1_PUBLICATION_SKILL_CHECKS+ from skillevaluator.tier1.commands import DEFAULT_CHECKS++ assert frozenset(DEFAULT_CHECKS) == TIER1_PUBLICATION_CORE_CHECKS | TIER1_PUBLICATION_SKILL_CHECKS+++def test_scan_gap_detection_reports_certified_paths_that_tier1_skips(tmp_path: Path) -> None:+ from skillevaluator.constants import SCAN_EXCLUDED_DIRS, SCAN_EXCLUDED_FILES+ from skillevaluator.publication_identity import publication_paths_skipped_by_scan++ skill = tmp_path / "demo"+ for relative in (+ "SKILL.md",+ "BENCHMARK.md",+ "results/run.json",+ "evals/evals.json",+ "evals/results/run.json",+ "node_modules/pkg/results/x.js",+ "references/notes.md",+ "references/results/notes.md",+ "references/evals/notes.md",+ "references/BENCHMARK.md",+ "scripts/versions/helper.py",+ ):+ path = skill / relative+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text("content\n", encoding="utf-8")++ skipped = publication_paths_skipped_by_scan(skill, SCAN_EXCLUDED_DIRS, SCAN_EXCLUDED_FILES)++ # Root generated artifacts, root Tier 3 inputs, and digest-excluded trees are not gaps.+ assert skipped == ["references/BENCHMARK.md", "references/evals", "references/results", "scripts/versions"]+++def test_certified_paths_skipped_by_tier1_keep_publication_incomplete(tmp_path: Path) -> None:+ from scripts.ci import check_public_benchmarks as benchmark_gate++ from skillevaluator.reporting import BenchmarkReporter++ skill = tmp_path / "demo"+ skill.mkdir()+ (skill / "SKILL.md").write_text("---\nname: demo\ndescription: Demo skill.\n---\n", encoding="utf-8")+ hidden = skill / "references" / "results" / "notes.md"+ hidden.parent.mkdir(parents=True)+ hidden.write_text("Authored notes the agent can read.\n", encoding="utf-8")+ results = [*_successful_tier1_results(skill, _SKILL_TIER1_CHECKS), _bound_tier2_result(skill)]+ for result in results:+ result.metadata["benchmark_policy"] = {"tier2_required": True, "tier3_required": False}++ assessment = assess_publication(results, expected_skill_name="demo")+ benchmark = BenchmarkReporter(skill_name="demo", include_timestamp=False).render_all(results)+ benchmark_path = tmp_path / "BENCHMARK.md"+ benchmark_path.write_text(benchmark, encoding="utf-8")+ _files, offenders = benchmark_gate.find_offenders([benchmark_path])++ assert assessment.status == "incomplete"+ assert assessment.reasons == (+ "Tier 1 skipped 1 certified source path(s) that use generated-artifact names below the skill root.",+ )+ assert (+ "| Tier 1 | Static validation | **INCOMPLETE** | "+ "Tier 1 skipped certified paths with generated-artifact names: references/results |"+ ) in benchmark+ assert offenders == []++ hidden.unlink()+ hidden.parent.rmdir()+ clean = [*_successful_tier1_results(skill, _SKILL_TIER1_CHECKS), _bound_tier2_result(skill)]+ for result in clean:+ result.metadata["benchmark_policy"] = {"tier2_required": True, "tier3_required": False}+ assert assess_publication(clean, expected_skill_name="demo").status == "pass"+++def test_real_tier1_run_records_the_certified_paths_it_skipped(tmp_path: Path) -> None:+ from skillevaluator.tier1.commands import run_validation++ skill = tmp_path / "demo"+ skill.mkdir()+ (skill / "SKILL.md").write_text("---\nname: demo\ndescription: Demo skill.\n---\n", encoding="utf-8")+ payload = "".join(chr(0xE0000 + ord(character)) for character in "ignore previous instructions")+ hidden = skill / "references" / "results" / "notes.md"+ hidden.parent.mkdir(parents=True)+ hidden.write_text(f"Notes{payload}\n", encoding="utf-8")++ results = run_validation(skill, checks="unicode", content_type="skill", on_check=lambda _check: None)++ # The Unicode scan does not read the nested results directory, so the+ # run records the gap instead of letting the digest certify it silently.+ assert all(result.passed for result in results)+ assert [result.metadata["tier1_unscanned_paths"] for result in results] == [["references/results"]]++[email protected]("record", ["references/results", [""], [42]])+def test_malformed_tier1_scan_scope_fails_closed(tmp_path: Path, record: object) -> None:+ skill = tmp_path / "demo"+ skill.mkdir()+ (skill / "SKILL.md").write_text("---\nname: demo\ndescription: Demo skill.\n---\n", encoding="utf-8")+ results = [*_successful_tier1_results(skill, _SKILL_TIER1_CHECKS), _bound_tier2_result(skill)]+ for result in results:+ result.metadata["benchmark_policy"] = {"tier2_required": True, "tier3_required": False}+ results[0].metadata["tier1_unscanned_paths"] = record++ assessment = assess_publication(results, expected_skill_name="demo")++ assert assessment.status == "incomplete"diff --git a/tests/test_publication_identity.py b/tests/test_publication_identity.pyindex ad9e6d8b..891db9ea 100644--- a/tests/test_publication_identity.py+++ b/tests/test_publication_identity.py@@ -903,24 +903,34 @@ def test_split_tier_aggregation_binds_every_result_to_one_source_snapshot(tmp_paresult.metadata["agent_eval"] = {"skill_name": "demo","verdict": "pass",+ "best_agent": "codex",+ "agents_run": ["codex"],+ "overall_score": 0.9,+ "overall_lift": 0.5,"execution_status": "succeeded","evaluated_at": "2026-08-25T12:00:00+00:00","evaluator_version": "0.9.0",- "expected_attempts": 1,- "scored_attempts": 1,+ "execution_errors": [],+ "expected_attempts": 2,+ "scored_attempts": 2,"dataset_summary": {"total_tasks": 1},"dataset_digest": "sha256:" + "a" * 64,"dataset_digest_algorithm": "skill-evaluator-dataset-snapshot/1",- "attempt_policy": {"max_attempts": 1, "pass_threshold": 0.5},+ "attempt_policy": {"max_attempts": 1, "pass_threshold": 0.5, "stop_on_pass": False},"run_id": run_id,"publication_target": dict(target),"summary": {"skill_name": "demo","verdict": "pass",+ "best_agent": "codex",+ "agents_run": ["codex"],+ "overall_score": 0.9,+ "overall_lift": 0.5,"execution_status": "succeeded","environment": "docker",- "expected_attempts": 1,- "scored_attempts": 1,+ "execution_errors": [],+ "expected_attempts": 2,+ "scored_attempts": 2,"run_id": run_id,"publication_target": dict(target),},@@ -928,11 +938,28 @@ def test_split_tier_aggregation_binds_every_result_to_one_source_snapshot(tmp_pa"codex": {"model": "gpt-codex","execution_status": "succeeded",- "expected_attempts": 1,- "scored_attempts": 1,+ "execution_errors": [],+ "expected_attempts": 2,+ "scored_attempts": 2,+ "conditions": {+ "with_skill": {+ "execution_status": "succeeded",+ "execution_errors": [],+ "expected_attempts": 1,+ "scored_attempts": 1,+ },+ "without_skill": {+ "execution_status": "succeeded",+ "execution_errors": [],+ "expected_attempts": 1,+ "scored_attempts": 1,+ },+ },+ "baseline": 0.4,"with_skill": 0.9,+ "lift": 0.5,"dimensions": [- {"id": dimension, "with_skill": 0.9}+ {"id": dimension, "with_skill": 0.9, "baseline": 0.4, "lift": 0.5}for dimension in ("security","correctness",@@ -943,16 +970,32 @@ def test_split_tier_aggregation_binds_every_result_to_one_source_snapshot(tmp_pa],}},+ "dimensions": [+ {"id": dimension, "with_skill": 0.9, "baseline": 0.4, "lift": 0.5}+ for dimension in (+ "security",+ "correctness",+ "discoverability",+ "effectiveness",+ "efficiency",+ )+ ],}return result- tier1 = _as_result(- "SCHEMA",- "Schema validation",- lambda _target: successful_result("SCHEMA", "schema"),- skill,- publication_check_id="schema",- )+ from skillevaluator.publication_evidence import tier1_required_checks++ # Publication requires the whole applicable Tier 1 lineup, not one check.+ tier1_results = [+ _as_result(+ check.upper(),+ f"{check} validation",+ lambda _target, check=check: successful_result(check.upper(), check),+ skill,+ publication_check_id=check,+ )+ for check in tier1_required_checks(skill_like=True)+ ]tier2 = _guarded_result("Similarity Check",skill,@@ -963,19 +1006,19 @@ def test_split_tier_aggregation_binds_every_result_to_one_source_snapshot(tmp_paassert unchanged_target is not Nonetier3 = tier3_result(unchanged_target)- benchmark = BenchmarkReporter(skill_name="demo", include_timestamp=False).render_all([tier1, tier2, tier3])+ benchmark = BenchmarkReporter(skill_name="demo", include_timestamp=False).render_all([*tier1_results, tier2, tier3])benchmark_path = tmp_path / "BENCHMARK.md"benchmark_path.write_text(benchmark, encoding="utf-8")_files, offenders = benchmark_gate.find_offenders([benchmark_path])- assert "Overall verdict: PASS" in benchmark+ assert "> ✅ **Overall verdict: PASS — Recommended for publication**" in benchmark+ assert "## Publication Recommendation" in benchmarkassert offenders == []- machine_report = json.loads(JSONReporter(include_timestamp=False).render_all([tier1, tier2, tier3]))- assert [result["publication_target"] for result in machine_report["results"]] == [- unchanged_target,- unchanged_target,- unchanged_target,- ]+ machine_report = json.loads(JSONReporter(include_timestamp=False).render_all([*tier1_results, tier2, tier3]))+ assert machine_report["publication_status"] == "pass"+ assert [result["publication_target"] for result in machine_report["results"]] == [unchanged_target] * (+ len(tier1_results) + 2+ )assert machine_report["tier3"]["run_id"] == "split-tier-fixture-run"(skill / "SKILL.md").write_text("---\nname: changed-between-jobs\n---\n", encoding="utf-8")@@ -990,7 +1033,7 @@ def test_split_tier_aggregation_binds_every_result_to_one_source_snapshot(tmp_pachanged_tier3 = tier3_result(changed_target)mixed = BenchmarkReporter(skill_name="demo", include_timestamp=False).render_all(- [tier1, changed_tier2, changed_tier3]+ [*tier1_results, changed_tier2, changed_tier3])assert "Overall verdict: INCOMPLETE" in mixeddiff --git a/tests/test_tier3_progress.py b/tests/test_tier3_progress.pyindex 845e2573..5556b3e3 100644--- a/tests/test_tier3_progress.py+++ b/tests/test_tier3_progress.py@@ -833,6 +833,44 @@ def test_runner_rejects_custom_in_skill_results_root_before_creating_output(assert not results_root.exists()+def test_run_result_bounds_multibyte_launch_errors_for_report_loader(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ github_token = "ghp_" + ("A" * 36)+ launch_errors = [f"launch {index}: {github_token}\x1b[2J" + ("😀" * 2_048) for index in range(256)]+ runner, skill = _stub_runner(+ monkeypatch,+ tmp_path,+ run_agent=lambda **_kwargs: launch_errors,+ )++ result = runner.run_harbor_eval(+ skill,+ ["codex"],+ output_dir=tmp_path / "results",+ agent_runtime_preflight=False,+ )++ result_path = Path(result["result_path"])+ serialized = result_path.read_bytes()+ persisted = json.loads(serialized)+ assert len(serialized) <= 2 * 1024 * 1024+ assert persisted["execution_status"] == "failed"+ assert persisted["execution_error_details_total"] == len(launch_errors)+ assert persisted["execution_error_details_shown"] == len(persisted["execution_errors"])+ assert persisted["execution_error_details_truncated"] is True+ assert persisted["error"] == persisted["execution_errors"][:1]+ assert github_token not in serialized.decode("utf-8")+ assert "\\u001b" not in serialized.decode("utf-8")++ from skillevaluator.tier3.harbor import report_data++ diagnostics: list[dict[str, Any]] = []+ assert report_data._load_bounded_json(result_path, diagnostics, artifact="result") == persisted+ assert diagnostics == []++def _configure_native_task_source(monkeypatch: pytest.MonkeyPatch,runner,@@ -2047,6 +2085,239 @@ def test_runner_persists_run_owned_publication_identity_in_final_result(}+ ("context_mode", "source_is_target_bound"),+ [("linked", False), ("full", False), ("full", True)],+)+def test_runner_fails_publication_closed_for_external_repo_runtime_context(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ context_mode: str,+ source_is_target_bound: bool,+) -> None:+ from skillevaluator.publication_identity import publication_target_from_path++ external_source = tmp_path / "shared-runtime.txt"+ external_source.write_text("agent-visible external input\n", encoding="utf-8")++ def emit_tasks(skill: Path, output: Path, **_kwargs: Any) -> list[Path]:+ task = output / "case-1"+ environment = task / "environment"+ environment.mkdir(parents=True)+ staged_source = skill / "SKILL.md" if source_is_target_bound else external_source+ (environment / "repo-context.json").write_text(+ json.dumps(+ {+ "mode": context_mode,+ "repo_root": str(tmp_path),+ "files": [+ {+ "source": str(staged_source),+ "container": "/workspace/repo/shared-runtime.txt",+ }+ ],+ }+ ),+ encoding="utf-8",+ )+ return [task]++ runner, skill = _stub_runner(monkeypatch, tmp_path, task_emitter=emit_tasks)+ (skill / "SKILL.md").write_text("# evaluated target\n", encoding="utf-8")+ expected_target = publication_target_from_path(skill)+ assert expected_target is not None++ result = runner.run_harbor_eval(skill, ["codex"], output_dir=tmp_path / "results")+ persisted = json.loads(Path(result["result_path"]).read_text(encoding="utf-8"))++ assert result["publication_target"] is None+ assert result["publication_target_conflict"] == {+ "run_start": expected_target,+ "run_end": None,+ "reason_code": "runtime_context_outside_publication_target",+ }+ assert persisted["publication_target"] is None+ assert persisted["publication_target_conflict"] == result["publication_target_conflict"]+++def test_runtime_context_binding_rejects_external_reference_and_workspace_skills(tmp_path: Path) -> None:+ from skillevaluator.tier3.harbor.runner import _runtime_context_is_bound_to_publication_target++ skill = tmp_path / "demo"+ skill.mkdir()+ references = tmp_path / "references"+ (references / "reference-skill").mkdir(parents=True)+ workspace = tmp_path / "workspace-skill"+ workspace.mkdir()++ assert not _runtime_context_is_bound_to_publication_target(+ skill,+ (),+ reference_skills_dir=references,+ workspace_skill_paths=(),+ )+ (references / "reference-skill").rmdir()+ assert not _runtime_context_is_bound_to_publication_target(+ skill,+ (),+ reference_skills_dir=references,+ workspace_skill_paths=(),+ )+ assert not _runtime_context_is_bound_to_publication_target(+ skill,+ (),+ reference_skills_dir=None,+ workspace_skill_paths=(workspace,),+ )++ internal_references = skill / "references"+ (internal_references / "reference-skill").mkdir(parents=True)+ internal_workspace = skill / "workspace-skill"+ internal_workspace.mkdir()+ assert _runtime_context_is_bound_to_publication_target(+ skill,+ (),+ reference_skills_dir=internal_references,+ workspace_skill_paths=(internal_workspace,),+ )++ assert not _runtime_context_is_bound_to_publication_target(+ skill,+ (),+ reference_skills_dir=tmp_path / "missing-references",+ workspace_skill_paths=(),+ )++ external_alias = tmp_path / "external-workspace-alias"+ try:+ external_alias.symlink_to(internal_workspace, target_is_directory=True)+ except OSError:+ pass+ else:+ assert not _runtime_context_is_bound_to_publication_target(+ skill,+ (),+ reference_skills_dir=None,+ workspace_skill_paths=(external_alias,),+ )+++ "excluded_parent",+ [+ Path("results"),+ Path(".results"),+ Path(".venv"),+ Path("node_modules"),+ Path("evals/results"),+ ],+)+def test_runtime_context_binding_rejects_workspace_skill_excluded_from_target_digest(+ tmp_path: Path,+ excluded_parent: Path,+) -> None:+ from skillevaluator.publication_identity import publication_target_from_path+ from skillevaluator.tier3.harbor.runner import _runtime_context_is_bound_to_publication_target++ skill = (tmp_path / "demo").resolve()+ workspace = skill / excluded_parent / "workspace-skill"+ workspace.mkdir(parents=True)+ (skill / "SKILL.md").write_text("# evaluated target\n", encoding="utf-8")+ workspace_manifest = workspace / "SKILL.md"+ workspace_manifest.write_text("# runtime input v1\n", encoding="utf-8")++ target_before = publication_target_from_path(skill)+ assert target_before is not None+ assert not _runtime_context_is_bound_to_publication_target(+ skill,+ (),+ reference_skills_dir=None,+ workspace_skill_paths=(workspace.resolve(),),+ )++ workspace_manifest.write_text("# attacker-controlled runtime input v2\n", encoding="utf-8")++ assert publication_target_from_path(skill) == target_before+ assert not _runtime_context_is_bound_to_publication_target(+ skill,+ (),+ reference_skills_dir=None,+ workspace_skill_paths=(workspace.resolve(),),+ )+++def test_runtime_context_binding_rejects_reference_child_excluded_from_target_digest(tmp_path: Path) -> None:+ from skillevaluator.tier3.harbor.runner import _runtime_context_is_bound_to_publication_target++ skill = (tmp_path / "demo").resolve()+ references = skill / "evals"+ excluded_reference = references / "results" / "reference-skill"+ excluded_reference.mkdir(parents=True)++ assert not _runtime_context_is_bound_to_publication_target(+ skill,+ (),+ reference_skills_dir=references,+ workspace_skill_paths=(),+ )+++def test_runtime_context_binding_fails_closed_for_unstable_relative_or_oversized_sources(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from skillevaluator.tier3.harbor import runner++ missing_skill = tmp_path / "missing-skill"+ assert not runner._runtime_context_is_bound_to_publication_target(+ missing_skill,+ (),+ reference_skills_dir=None,+ workspace_skill_paths=(),+ )++ skill = tmp_path / "demo"+ skill.mkdir()+ missing_manifest_task = tmp_path / "missing-manifest-task"+ (missing_manifest_task / "environment" / "repo").mkdir(parents=True)+ assert not runner._runtime_context_is_bound_to_publication_target(+ skill,+ (missing_manifest_task,),+ reference_skills_dir=None,+ workspace_skill_paths=(),+ )++ task = tmp_path / "task"+ environment = task / "environment"+ environment.mkdir(parents=True)+ (environment / "repo-context.json").write_text(+ json.dumps(+ {+ "mode": "linked",+ "repo_root": str(tmp_path),+ "files": [{"source": "demo/SKILL.md", "container": "/workspace/repo/demo/SKILL.md"}],+ }+ ),+ encoding="utf-8",+ )++ assert not runner._runtime_context_is_bound_to_publication_target(+ skill,+ (task,),+ reference_skills_dir=None,+ workspace_skill_paths=(),+ )++ monkeypatch.setattr(runner, "_MAX_REPO_CONTEXT_METADATA_BYTES", 32)+ (environment / "repo-context.json").write_text("{" + " " * 32 + "}", encoding="utf-8")+ assert not runner._runtime_context_is_bound_to_publication_target(+ skill,+ (task,),+ reference_skills_dir=None,+ workspace_skill_paths=(),+ )++def test_runner_rejects_source_change_after_private_snapshot_before_engine_launch(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,diff --git a/tests/validators/test_artifact_dir_exclusion.py b/tests/validators/test_artifact_dir_exclusion.pyindex e1fd3c34..304810cf 100644--- a/tests/validators/test_artifact_dir_exclusion.py+++ b/tests/validators/test_artifact_dir_exclusion.py@@ -158,6 +158,43 @@ class TestSkillspectorFilteredCopy:args = mock_run.call_args.args[0]assert args[args.index("scan") + 1] == str(skill.resolve())+ @patch.object(Tools.skillspector, "_path", "/usr/bin/skillspector")+ @patch.object(Tools.skillspector, "run")+ def test_report_filter_uses_scanned_filesystem_case_semantics(self, mock_run, tmp_path: Path) -> None:+ skill = tmp_path / "clean-skill"+ skill.mkdir()+ (skill / "SKILL.md").write_text("---\nname: clean-skill\n---\n")+ alias = skill / "benchmark.md"+ alias.write_text("authored or generated, depending on filesystem semantics\n")+ canonical = skill / "BENCHMARK.md"+ data = json.loads(_clean_spector_result().stdout)+ data["risk_assessment"] = {"score": 5, "severity": "LOW", "recommendation": "SAFE"}+ data["issues"] = [+ {+ "id": "SQP-2",+ "pattern": "Generated card warning",+ "severity": "LOW",+ "confidence": 1.0,+ "finding": "Generated card includes outputs",+ "location": {"file": "benchmark.md", "start_line": 1},+ }+ ]+ mock_run.return_value = ToolResult(+ success=True,+ stdout=json.dumps(data),+ stderr="",+ exit_code=0,+ )++ result = SecurityValidator()._run_skillspector(skill)++ if canonical.exists() and alias.samefile(canonical):+ assert result.findings == []+ assert any("ignored 1 generated artifact" in message for message in result.messages)+ else:+ assert len(result.findings) == 1+ assert result.findings[0].file_path == "benchmark.md"+@patch.object(Tools.skillspector, "_path", "/usr/bin/skillspector")@patch.object(Tools.skillspector, "run")def test_staged_scan_preserves_shipped_bytecode_for_sc8(self, mock_run, skill_with_artifacts):@@ -295,3 +332,78 @@ class TestSkillspectorArtifactIssueFilter:def test_live_issue_is_kept(self):issue = {"location": {"file": "scripts/deploy.py", "start_line": 3}}assert SecurityValidator._is_generated_artifact_issue(issue) is False++ @pytest.mark.parametrize("absolute_location", [False, True])+ def test_generated_file_case_alias_follows_filesystem_semantics(+ self,+ tmp_path: Path,+ absolute_location: bool,+ ) -> None:+ skill = tmp_path / "skill"+ skill.mkdir()+ alias = skill / "benchmark.md"+ alias.write_text("authored or generated, depending on filesystem semantics\n")+ canonical = skill / "BENCHMARK.md"+ reported = alias if absolute_location else alias.relative_to(skill)+ issue = {"location": {"file": str(reported), "start_line": 1}}++ filtered = SecurityValidator._is_generated_artifact_issue(issue, source_root=skill)++ if canonical.exists() and alias.samefile(canonical):+ assert filtered is True+ else:+ assert filtered is False++ def test_generated_directory_case_alias_follows_filesystem_semantics(self, tmp_path: Path) -> None:+ skill = tmp_path / "skill"+ alias = skill / "RESULTS"+ alias.mkdir(parents=True)+ finding = alias / "finding.md"+ finding.write_text("authored or generated, depending on filesystem semantics\n")+ canonical = skill / "results"+ issue = {"location": {"file": "RESULTS/finding.md", "start_line": 1}}++ filtered = SecurityValidator._is_generated_artifact_issue(issue, source_root=skill)++ if canonical.exists() and alias.samefile(canonical):+ assert filtered is True+ else:+ assert filtered is False++ def test_generated_name_outside_source_root_is_not_filtered(self, tmp_path: Path) -> None:+ skill = tmp_path / "skill"+ skill.mkdir()+ (tmp_path / "BENCHMARK.md").write_text("outside the scanned skill\n")+ issue = {"location": {"file": "../BENCHMARK.md", "start_line": 1}}++ assert SecurityValidator._is_generated_artifact_issue(issue, source_root=skill) is False++ @pytest.mark.parametrize(+ "reported_path",+ [+ "bad\x00/BENCHMARK.md",+ "/tmp/bad\x00/BENCHMARK.md",+ "bad\ud800/BENCHMARK.md",+ "/tmp/bad\ud800/BENCHMARK.md",+ "bad\nforged/BENCHMARK.md",+ "bad\x1b[31m/BENCHMARK.md",+ ],+ ids=[+ "relative-nul",+ "absolute-nul",+ "relative-surrogate",+ "absolute-surrogate",+ "newline",+ "terminal-escape",+ ],+ )+ def test_malformed_reported_path_is_not_filtered_or_probed(+ self,+ tmp_path: Path,+ reported_path: str,+ ) -> None:+ skill = tmp_path / "skill"+ skill.mkdir()+ issue = {"location": {"file": reported_path, "start_line": 1}}++ assert SecurityValidator._is_generated_artifact_issue(issue, source_root=skill) is Falsediff --git a/tests/validators/test_license.py b/tests/validators/test_license.pyindex 254d5a73..dbad4ee0 100644--- a/tests/validators/test_license.py+++ b/tests/validators/test_license.py@@ -319,6 +319,7 @@ class TestFrontmatterDetection:assert result.metadata.get("license") == "MIT"assert result.metadata.get("license_status") == "allowed"assert all(f.check_name != "frontmatter_license_missing" for f in result.findings)+ assert any(detail.check_name == "license_compliance" for detail in result.success_details)def test_detects_file_reference_in_frontmatter(self, skill_with_apache_license: Path):"""Test detection of license file reference in frontmatter."""diff --git a/tests/validators/test_security.py b/tests/validators/test_security.pyindex 244142b9..eca30b95 100644--- a/tests/validators/test_security.py+++ b/tests/validators/test_security.py@@ -3395,6 +3395,44 @@ Call us at 555-123-4567 or +1-555-987-6543assert result.status == "incomplete"assert any("location.file" in error for error in result.errors)+ @pytest.mark.parametrize(+ "file_path",+ [+ "bad\x00/BENCHMARK.md",+ "bad\ud800/BENCHMARK.md",+ "bad\nforged.py",+ "bad\x1b[31m.py",+ ],+ ids=["embedded-nul", "lone-surrogate", "newline", "terminal-escape"],+ )+ @patch("skillevaluator.validators.security.Tools")+ def test_skillspector_report_rejects_non_filesystem_safe_issue_path(+ self,+ mock_tools,+ sample_skill_dir: Path,+ file_path: str,+ ) -> None:+ payload = _skillspector_json_report(+ [+ {+ "id": "M1",+ "severity": "MEDIUM",+ "finding": "advisory",+ "location": {"file": file_path, "start_line": 1},+ }+ ]+ )+ payload["risk_assessment"] = {+ "score": 10,+ "severity": "LOW",+ "recommendation": "SAFE",+ }++ result = _validate_skillspector_payload(mock_tools, sample_skill_dir, payload)++ assert result.status == "incomplete"+ assert any("location.file" in error and "filesystem-safe" in error for error in result.errors)+@pytest.mark.parametrize(("skillspector_version", "case"),[diff --git a/tests/validators/test_security_validators.py b/tests/validators/test_security_validators.pyindex b0e5d7a7..5ff46610 100644--- a/tests/validators/test_security_validators.py+++ b/tests/validators/test_security_validators.py@@ -12,7 +12,7 @@ from unittest.mock import MagicMock, patchimport pytest-from skillevaluator.utils.tool_runner import Severity, Tools+from skillevaluator.utils.tool_runner import Severity, ToolResult, Toolsfrom skillevaluator.validators.base import ValidationResultfrom skillevaluator.validators.code_risk import CodeRiskValidatorfrom skillevaluator.validators.dependencies import DependencySecurityValidator@@ -92,6 +92,7 @@ class TestSecretsValidator:assert result.passedassert any("No secrets detected" in m for m in result.messages)+ assert any(detail.check_name == "gitleaks" for detail in result.success_details)def test_validate_skill_with_secrets(self, skill_with_security_issues: Path, mock_tool_available):"""Test detection of secrets in a skill."""@@ -167,6 +168,7 @@ class TestDependencySecurityValidator:assert result.passedassert any("No dependency files found" in m for m in result.messages)+ assert any(detail.check_name == "dependency_file_discovery" for detail in result.success_details)def test_validate_with_requirements(self, tmp_path: Path, mock_tool_available):"""Test validation with requirements.txt."""@@ -186,7 +188,7 @@ description: Test skillmock_result = MagicMock()mock_result.success = Truemock_result.exit_code = 0- mock_result.stdout = '{"dependencies": []}'+ mock_result.stdout = '{"dependencies": [], "fixes": []}'mock_result.error_message = Nonewith (@@ -196,6 +198,7 @@ description: Test skillresult = validator.validate(skill_dir)assert result.passed+ assert any(detail.check_name == "pip_audit" for detail in result.success_details)def test_validate_with_vulnerabilities(self, tmp_path: Path, mock_tool_available):"""Test detection of vulnerable dependencies."""@@ -227,7 +230,7 @@ description: Vulnerable skill}]}- ]}"""+ ], "fixes": []}"""with (mock_tool_available("pip_audit", "/usr/bin/pip-audit"),@@ -235,7 +238,9 @@ description: Vulnerable skill):result = validator.validate(skill_dir)+ assert not result.is_incompleteassert any("CVE" in e or "PYSEC" in e for e in result.errors + result.warnings)+ assert any(detail.check_name == "pip_audit" for detail in result.success_details)def test_no_tools_installed(self, tmp_path: Path, mock_tool_unavailable):"""Test graceful handling when no audit tools installed."""@@ -254,9 +259,180 @@ description: Testwith mock_tool_unavailable("pip_audit"), mock_tool_unavailable("safety"):result = validator.validate(skill_dir)- assert result.passed+ assert result.status == "incomplete"+ assert not result.passed+ assert result.incomplete_scans == ["pip-audit"]assert any("pip-audit not installed" in w for w in result.warnings)+ @pytest.mark.parametrize(+ "stdout",+ [+ "No known vulnerabilities found",+ "{}",+ '{"dependencies": "not-a-list"}',+ '{"dependencies": [{"name": "requests", "version": "2.32.0"}]}',+ '{"dependencies": [{"name": "requests", "version": "2.32.0", "vulns": [{}]}]}',+ '{"dependencies": [{"name": "requests", "version": "2.32.0", '+ '"vulns": [{"id": "PYSEC-1", "fix_versions": [], "severity": "urgent"}]}]}',+ '{"dependencies": [{"name": "requests", "version": "2.32.0", '+ '"vulns": [{"id": "PYSEC-1", "fix_versions": [], '+ '"aliases": [{"cvss": {"score": 11}}]}]}]}',+ '{"dependencies": [{"name": "requests", "version": "2.32.0", '+ '"vulns": [{"id": "PYSEC-1", "fix_versions": [], '+ '"aliases": [{"cvss": {"score": -0.1}}]}]}]}',+ '{"dependencies": [{"name": "requests", "version": "2.32.0", '+ '"vulns": [{"id": "PYSEC-1", "fix_versions": [], '+ '"aliases": [{"cvss": {"score": NaN}}]}]}]}',+ json.dumps(+ {+ "dependencies": [+ {+ "name": "requests",+ "version": "2.32.0",+ "vulns": [+ {+ "id": "PYSEC-1",+ "fix_versions": [],+ "aliases": [{"cvss": {"score": 10**400}}],+ }+ ],+ }+ ]+ }+ ),+ '{"dependencies": [{"name": "requests", "version": "2.32.0", '+ '"vulns": [{"id": "PYSEC-1", "fix_versions": [], '+ '"aliases": [{"cvss": {"score": '+ + "9" * 5000+ + "}}]}]}]}]}",+ ],+ ids=[+ "non-json",+ "missing-dependencies",+ "bad-dependencies",+ "missing-vulns",+ "bad-vulnerability",+ "unknown-severity",+ "cvss-too-high",+ "cvss-negative",+ "cvss-nan",+ "cvss-huge-integer",+ "cvss-over-parser-limit",+ ],+ )+ def test_malformed_pip_audit_reports_are_incomplete(+ self,+ sample_skill_dir: Path,+ mock_tool_available,+ stdout: str,+ ):+ """Malformed reports cannot certify successful dependency scanning."""+ (sample_skill_dir / "requirements.txt").write_text("requests==2.32.0\n")+ tool_result = ToolResult(success=True, stdout=stdout, stderr="", exit_code=0)++ with (+ mock_tool_available("pip_audit", "/usr/bin/pip-audit"),+ patch.object(Tools.pip_audit, "run", return_value=tool_result),+ ):+ result = DependencySecurityValidator(use_safety=False).validate(sample_skill_dir)++ assert result.status == "incomplete"+ assert result.incomplete_scans == ["pip-audit"]+ assert not any(detail.check_name == "pip_audit" for detail in result.success_details)++ @pytest.mark.parametrize(+ "tool_result",+ [+ ToolResult(success=False, stdout="", stderr="", exit_code=-1, error_message="pip-audit timed out"),+ ToolResult(+ success=True,+ stdout='{"dependencies": [], "fixes": []}',+ stderr="",+ exit_code=2,+ ),+ ],+ ids=["operational-error", "unexpected-exit-code"],+ )+ def test_incomplete_pip_audit_processes_do_not_publish_success(+ self,+ sample_skill_dir: Path,+ mock_tool_available,+ tool_result: ToolResult,+ ):+ """A failed process is incomplete even when stdout resembles a clean report."""+ (sample_skill_dir / "requirements.txt").write_text("requests==2.32.0\n")++ with (+ mock_tool_available("pip_audit", "/usr/bin/pip-audit"),+ patch.object(Tools.pip_audit, "run", return_value=tool_result),+ ):+ result = DependencySecurityValidator(use_safety=False).validate(sample_skill_dir)++ assert result.status == "incomplete"+ assert result.incomplete_scans == ["pip-audit"]+ assert not any(detail.check_name == "pip_audit" for detail in result.success_details)++ @pytest.mark.parametrize(+ ("exit_code", "stdout"),+ [+ (+ 0,+ '{"dependencies": [{"name": "demo", "version": "1", '+ '"vulns": [{"id": "PYSEC-1", "fix_versions": []}]}], "fixes": []}',+ ),+ (1, '{"dependencies": [], "fixes": []}'),+ ],+ ids=["clean-exit-with-findings", "findings-exit-without-findings"],+ )+ def test_pip_audit_exit_code_must_match_report(+ self,+ sample_skill_dir: Path,+ mock_tool_available,+ exit_code: int,+ stdout: str,+ ):+ """Contradictory process and report states fail closed."""+ (sample_skill_dir / "requirements.txt").write_text("demo==1\n")+ tool_result = ToolResult(success=True, stdout=stdout, stderr="", exit_code=exit_code)++ with (+ mock_tool_available("pip_audit", "/usr/bin/pip-audit"),+ patch.object(Tools.pip_audit, "run", return_value=tool_result),+ ):+ result = DependencySecurityValidator(use_safety=False).validate(sample_skill_dir)++ assert result.status == "incomplete"+ assert result.incomplete_scans == ["pip-audit"]+ assert not any(detail.check_name == "pip_audit" for detail in result.success_details)++ def test_skipped_dependencies_make_pip_audit_evidence_partial(+ self,+ sample_skill_dir: Path,+ mock_tool_available,+ ):+ """pip-audit skip entries describe missing coverage, not a completed scan."""+ (sample_skill_dir / "requirements.txt").write_text("local-package @ file:///tmp/local-package\n")+ tool_result = ToolResult(+ success=True,+ stdout=(+ '{"dependencies": [{"name": "local-package", '+ '"skip_reason": "Dependency not found on index"}], "fixes": []}'+ ),+ stderr="",+ exit_code=0,+ )++ with (+ mock_tool_available("pip_audit", "/usr/bin/pip-audit"),+ patch.object(Tools.pip_audit, "run", return_value=tool_result),+ ):+ result = DependencySecurityValidator(use_safety=False).validate(sample_skill_dir)++ assert result.status == "incomplete"+ assert result.incomplete_scans == ["pip-audit"]+ assert any("scan coverage is incomplete" in warning for warning in result.warnings)+ assert not any(detail.check_name == "pip_audit" for detail in result.success_details)+# =============================================================================# CODE RISK VALIDATOR TESTS@@ -288,6 +464,7 @@ class TestCodeRiskValidator:assert result.passedassert any("No code files found" in m for m in result.messages)+ assert any(detail.check_name == "code_file_discovery" for detail in result.success_details)def test_validate_no_tools_installed(self, skill_with_security_issues: Path, mock_tool_unavailable):"""Test graceful handling when no analysis tools installed."""@@ -318,6 +495,7 @@ class TestCodeRiskValidator:result = validator.validate(skill_with_security_issues)assert result.passed+ assert any(detail.check_name == "bandit" for detail in result.success_details)def test_validate_bandit_findings(self, skill_with_security_issues: Path, mock_tool_available):"""Test Bandit analysis with security findings."""@@ -544,7 +722,8 @@ class TestCodeRiskValidator:assert result.passedassert not result.errors- assert result.messages == ["Semgrep: No security issues found"]+ assert any(detail.check_name == "semgrep" for detail in result.success_details)+ assert result.messages == ["[OK] semgrep: Semgrep: No security issues found"]def test_validate_semgrep_findings(self, skill_with_security_issues: Path, mock_tool_available):"""Test Semgrep analysis with findings."""diff --git a/tests/validators/test_target_dependencies.py b/tests/validators/test_target_dependencies.pyindex 8a5b903a..2ff66305 100644--- a/tests/validators/test_target_dependencies.py+++ b/tests/validators/test_target_dependencies.py@@ -183,3 +183,27 @@ def test_folder_target_coverage_survives_report_exports(tmp_path, monkeypatch):json_data = json.loads(JSONReporter().render_all([result]))assert json_data["results"][0]["dependency_coverage"] == coverageassert HTMLReporter()._results_to_dict([result])[0]["dependency_coverage"] == coverage+++def test_pyproject_without_applicable_pins_records_execution_evidence(tmp_path, monkeypatch):+ from skillevaluator.reporting.base import result_has_execution_evidence++ result, calls = audit(tmp_path, "[project]\nname='example'\ndependencies=[]", monkeypatch)+ assert result.status == "passed"+ assert not calls+ assert [detail.check_name for detail in result.success_details] == ["pyproject_dependency_discovery"]+ assert result_has_execution_evidence(result)++ incomplete, _ = audit(tmp_path, '[project]\ndependencies=["requests>=2"]', monkeypatch)+ assert incomplete.status == "incomplete"+ assert not incomplete.success_details+++def test_contradictory_exit_code_does_not_count_batch_as_audited(tmp_path, monkeypatch):+ output = json.dumps(+ {"dependencies": [{"name": "idna", "version": "3.10", "vulns": [{"id": "PYSEC-TEST", "fix_versions": []}]}]}+ )+ result, _ = audit(tmp_path, '[project]\ndependencies=["idna==3.10"]', monkeypatch, output=output, exit_code=0)+ assert result.status == "incomplete"+ assert result.metadata["dependency_coverage"]["audited_pins"] == []+ assert not any(detail.check_name == "pip_audit" for detail in result.success_details)