Multi-tier framework for evaluating AI agent skills and plugins with quality gates, security scanning, harness compatibility checks, semantic overlap detection, synthetic evaluation dataset generation, and live agent evaluation that measures how skills affect agent behavior. Ships reusable CI templates that bring every check to any repository.
Python agent-evaluationagent-pluginsagent-securityagent-skillsagentic-aibenchmarkci-templatesclaude-codecodexevaluateevaluationharnesspluginplugin-evaluationsecurity-scannerskill-evalskill-evaluationskill-evaluatorskill-gap-analysisskills
feat(ci): add LLM security, gateway agents and benchmark PRs (#439)
Narendran Raghavan487910ef1dc4
diff --git a/.github/workflows/evaluate-all-tiers.yml b/.github/workflows/evaluate-all-tiers.ymlindex 9de0a046..2998f5e7 100644--- a/.github/workflows/evaluate-all-tiers.yml+++ b/.github/workflows/evaluate-all-tiers.yml@@ -39,15 +39,49 @@ on:model:type: stringdefault: ''+ base-url:+ description: Optional explicit chat API root; required for openai-compatible gateways+ type: string+ default: ''+ tier1-llm:+ description: Enable protected Tier 1 LLM security, SkillSpector enrichment and rubric checks+ type: boolean+ default: false+ tier1-provider:+ description: Tier 1 image provider override; openai, anthropic or nv_build+ type: string+ default: ''+ tier1-model:+ description: Tier 1 and SkillSpector model; empty preserves their provider defaults+ type: string+ default: ''embedding-provider:type: stringdefault: ''embedding-model:type: stringdefault: ''+ embedding-base-url:+ type: string+ default: ''+ tier3-provider:+ description: Optional independent live-agent and judge provider+ type: string+ default: ''+ tier3-model:+ description: Optional independent Tier 3 judge model; native agent models remain separate+ type: string+ default: ''+ tier3-base-url:+ type: string+ default: ''agents:type: stringdefault: ''+ agent-models:+ description: Newline-separated native AGENT=MODEL overrides for Tier 3 and doctor+ type: string+ default: ''runner:type: stringdefault: ubuntu-24.04@@ -75,6 +109,11 @@ on:required: falseNVIDIA_API_KEY:required: false+ LLM_API_KEY:+ description: Inference credential for an explicitly configured compatible gateway+ required: false+ EMBEDDING_API_KEY:+ required: falsepermissions:contents: readid-token: write@@ -89,7 +128,9 @@ jobs:min-score: ${{ inputs.min-score }}security-baselines: ${{ inputs.security-baselines }}scan-mode: ${{ needs.eligibility.outputs.scan-mode || inputs.scan-mode }}- artifact-name: skill-evaluator-tier1+ # Keep an unconditional keyless baseline. Eligible opt-in runs use the+ # protected enriched job's canonical evidence for the required gate.+ artifact-name: ${{ inputs.tier1-llm && needs.eligibility.outputs.allowed == 'true' && 'skill-evaluator-tier1-baseline' || 'skill-evaluator-tier1' }}llm: falseeligibility:runs-on: ubuntu-24.04@@ -188,10 +229,16 @@ jobs:SKILL_EVAL_ENV_MODE: ${{ inputs.env-mode }}SKILL_EVAL_PROVIDER: ${{ inputs.provider }}SKILL_EVAL_MODEL: ${{ inputs.model }}+ SKILL_EVAL_BASE_URL: ${{ inputs.base-url }}+ SKILL_EVAL_TIER3_PROVIDER: ${{ inputs.tier3-provider }}+ SKILL_EVAL_TIER3_MODEL: ${{ inputs.tier3-model }}+ SKILL_EVAL_TIER3_BASE_URL: ${{ inputs.tier3-base-url }}# Empty lets run_tiers choose the documented default (OpenAI for Anthropic chat).SKILL_EVAL_EMBEDDING_PROVIDER: ${{ inputs.embedding-provider }}SKILL_EVAL_EMBEDDING_MODEL: ${{ inputs.embedding-model }}+ SKILL_EVAL_EMBEDDING_BASE_URL: ${{ inputs.embedding-base-url }}SKILL_EVAL_AGENTS: ${{ inputs.agents }}+ SKILL_EVAL_AGENT_MODELS: ${{ inputs.agent-models }}SKILL_EVAL_TIER3_REQUIRED: 'false'SKILL_EVAL_N_ATTEMPTS: ${{ inputs.n-attempts }}SKILL_EVAL_N_CONCURRENT: ${{ inputs.n-concurrent }}@@ -228,7 +275,8 @@ jobs:python -I -m pip --isolated install --index-url https://pypi.org/simple uv==0.11.27env -i PATH="$PATH" python -I -m uv --no-config --cache-dir "$RUNNER_TEMP/uv-cache" sync --locked --no-dev --extra "tier${TIER}" --project "$GITHUB_WORKSPACE/evaluator" --python 3.12 --default-index https://pypi.org/simpleecho "$GITHUB_WORKSPACE/evaluator/.venv/bin" >> "$GITHUB_PATH"- - name: Recheck current head after environment approval+ - ¤t-head-check+ name: Recheck current head after environment approvalid: current-headenv:GH_TOKEN: ${{ github.token }}@@ -272,6 +320,8 @@ jobs:OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}NVIDIA_API_KEY: ${{ secrets.NVIDIA_API_KEY }}+ SKILL_EVAL_LLM_API_KEY: ${{ secrets.LLM_API_KEY }}+ SKILL_EVAL_EMBEDDING_API_KEY: ${{ secrets.EMBEDDING_API_KEY }}run: python -I evaluator/ci/bootstrap_tiers.py- name: Evaluate selected tier and retain native evidenceif: ${{ !cancelled() && steps.current-head.outputs.allowed == 'true' && contains(format(',{0},', inputs.tiers), format(',{0},', matrix.tier)) }}@@ -280,6 +330,8 @@ jobs:OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}NVIDIA_API_KEY: ${{ secrets.NVIDIA_API_KEY }}+ SKILL_EVAL_LLM_API_KEY: ${{ secrets.LLM_API_KEY }}+ SKILL_EVAL_EMBEDDING_API_KEY: ${{ secrets.EMBEDDING_API_KEY }}run: |# The job budget also covers setup; stop evaluation first so timeout evidence is retained.reserve=$(( SKILL_EVAL_TIMEOUT_MINUTES / 4 < 20 ? SKILL_EVAL_TIMEOUT_MINUTES / 4 : 20 ))@@ -293,8 +345,71 @@ jobs:path: ${{ runner.temp }}/skill-reports/if-no-files-found: warnretention-days: 14+ tier1-llm:+ needs: eligibility+ if: ${{ inputs.tier1-llm && needs.eligibility.outputs.allowed == 'true' && contains(format(',{0},', inputs.tiers), ',1,') }}+ # Match the keyless image job even when native Tier 3 uses a local runner.+ runs-on: ubuntu-24.04+ environment: ${{ inputs.environment }}+ permissions:+ contents: read+ pull-requests: read+ timeout-minutes: 60+ env:+ SKILL_EVAL_PATHS: ${{ inputs.paths }}+ SKILL_EVAL_SCAN_MODE: ${{ needs.eligibility.outputs.scan-mode || inputs.scan-mode }}+ SKILL_EVAL_MIN_SCORE: ${{ inputs.min-score }}+ SKILL_EVAL_PROVIDER: ${{ inputs.provider }}+ SKILL_EVAL_TIER1_PROVIDER: ${{ inputs.tier1-provider }}+ SKILL_EVAL_TIER1_MODEL: ${{ inputs.tier1-model }}+ DIFF_BASE_SHA: ${{ github.event.pull_request.base.sha }}+ DIFF_HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }}+ SECURITY_BASELINES: ${{ inputs.security-baselines }}+ POLICY_SOURCE_SHA: ${{ github.event.pull_request.base.sha || github.sha }}+ REPORT_COMMIT: ${{ github.event.pull_request.head.sha || github.sha }}+ REPORT_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}+ steps:+ - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0+ with:+ repository: ${{ inputs.tools-repository }}+ ref: ${{ inputs.tools-ref }}+ path: evaluator+ persist-credentials: false+ - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0+ with:+ ref: ${{ github.event.pull_request.head.sha || github.sha }}+ path: candidate+ fetch-depth: 0+ # Reviewed baselines read policy-commit blobs; the container cannot fetch.+ filter: ${{ !inputs.security-baselines && 'blob:none' || '' }}+ persist-credentials: false+ - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1+ with:+ python-version: '3.12'+ - name: Install the locked credential-free Tier 1 launcher+ run: |+ python -I -m pip --isolated install --index-url https://pypi.org/simple uv==0.11.27+ env -i PATH="$PATH" python -I -m uv --no-config --cache-dir "$RUNNER_TEMP/uv-cache" sync --locked --no-dev --project "$GITHUB_WORKSPACE/evaluator" --python 3.12 --default-index https://pypi.org/simple+ echo "$GITHUB_WORKSPACE/evaluator/.venv/bin" >> "$GITHUB_PATH"+ - *current-head-check+ - name: Evaluate enriched Tier 1 in the hardened image+ if: ${{ steps.current-head.outputs.allowed == 'true' }}+ env:+ IMAGE: ${{ inputs.image }}+ OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}+ ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}+ NVIDIA_API_KEY: ${{ secrets.NVIDIA_API_KEY }}+ run: python -I evaluator/ci/run_tier1_image.py --workspace "$GITHUB_WORKSPACE/candidate" --reports "$RUNNER_TEMP/skill-reports" --image "$IMAGE"+ - name: Retain enriched Tier 1 reports after failure+ if: ${{ always() }}+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9+ with:+ name: skill-evaluator-tier1-attempt-${{ github.run_attempt }}+ path: ${{ runner.temp }}/skill-reports/+ if-no-files-found: warn+ retention-days: 14aggregate:- needs: [tier1, paid-tiers]+ needs: [tier1, tier1-llm, paid-tiers]if: ${{ always() }}runs-on: ubuntu-24.04permissions:diff --git a/.github/workflows/publish-benchmarks.yml b/.github/workflows/publish-benchmarks.ymlnew file mode 100644index 00000000..bd0a3f7e--- /dev/null+++ b/.github/workflows/publish-benchmarks.yml@@ -0,0 +1,55 @@+# SPDX-License-Identifier: Apache-2.0+name: Trusted benchmark update proposals+on:+ workflow_call:+ inputs:+ tools-repository:+ type: string+ default: NVIDIA/SkillEvaluator+ tools-ref:+ type: string+ required: true+ trusted-workflow-ref:+ description: Exact reusable producer path at an immutable commit+ type: string+ required: true+ trusted-caller-blobs:+ description: Comma-separated reviewed caller Git blob IDs+ type: string+ required: true+permissions:+ contents: write+ actions: read+ pull-requests: write+jobs:+ benchmarks:+ # Updating a dedicated branch never changes the evaluated source PR.+ # The helper independently verifies the current default branch and attempt.+ if: ${{ github.event_name == 'workflow_run' && contains(fromJSON('["push","workflow_dispatch"]'), github.event.workflow_run.event) && github.event.workflow_run.head_repository.full_name == github.repository }}+ concurrency:+ group: skillevaluator-benchmark-updates-${{ github.repository }}+ cancel-in-progress: false+ queue: max+ runs-on: ubuntu-24.04+ steps:+ - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0+ with:+ repository: ${{ inputs.tools-repository }}+ ref: ${{ inputs.tools-ref }}+ persist-credentials: false+ - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1+ with:+ python-version: '3.12'+ - name: Install the locked trusted publication runtime+ run: |+ python -I -m pip --isolated install --index-url https://pypi.org/simple uv==0.11.27+ env -i PATH="$PATH" python -I -m uv --no-config --cache-dir "$RUNNER_TEMP/uv-cache" sync --locked --no-dev --extra publisher --project "$GITHUB_WORKSPACE" --python 3.12 --default-index https://pypi.org/simple+ echo "$GITHUB_WORKSPACE/.venv/bin" >> "$GITHUB_PATH"+ - name: Verify source evidence and propose benchmark updates+ env:+ GITHUB_TOKEN: ${{ github.token }}+ SOURCE_RUN_ID: ${{ github.event.workflow_run.id }}+ SOURCE_RUN_ATTEMPT: ${{ github.event.workflow_run.run_attempt }}+ SKILL_EVAL_TRUSTED_WORKFLOW_REF: ${{ inputs.trusted-workflow-ref }}+ SKILL_EVAL_TRUSTED_CALLER_BLOBS: ${{ inputs.trusted-caller-blobs }}+ run: python -I ci/benchmark_publish.py --repository "$GITHUB_REPOSITORY" --run-id "$SOURCE_RUN_ID" --run-attempt "$SOURCE_RUN_ATTEMPT"diff --git a/.github/workflows/skill-checks-all-tiers.yml b/.github/workflows/skill-checks-all-tiers.ymlindex 09bc951c..da786a5a 100644--- a/.github/workflows/skill-checks-all-tiers.yml+++ b/.github/workflows/skill-checks-all-tiers.yml@@ -21,7 +21,7 @@ permissions:actions: readjobs:skills:- uses: NVIDIA/SkillEvaluator/.github/workflows/evaluate-all-tiers.yml@c3b298c2b1a1a89d520bb22009f2668520127931+ uses: NVIDIA/SkillEvaluator/.github/workflows/evaluate-all-tiers.yml@e56ced7f72904e055b04a5024c688d7603d5b49awith:tiers: 1,2,3paths: skills@@ -32,16 +32,26 @@ jobs:embedding-provider: nv_buildmodel: nvidia/nemotron-3.5-lightning-30b-a3bembedding-model: ''- agents: ''+ agents: codex,claude-coderunner: ubuntu-24.04tools-repository: NVIDIA/SkillEvaluator- tools-ref: c3b298c2b1a1a89d520bb22009f2668520127931+ tools-ref: e56ced7f72904e055b04a5024c688d7603d5b49aimage: ghcr.io/nvidia/skillevaluator-tier1@sha256:9d5483243918937be4f2178f74cf7c622a531dee41e3176906994d52fa14950an-attempts: 1n-concurrent: 1timeout-minutes: 300environment: skillevaluator+ tier1-llm: true+ tier1-provider: nv_build+ tier1-model: nvidia/nemotron-3.5-super-vl-120b-a12b+ tier3-provider: openai-compatible+ tier3-model: us/aws/anthropic/eccn-claude-opus-4-8+ tier3-base-url: ${{ vars.SKILL_EVAL_TIER3_BASE_URL }}+ agent-models: |-+ codex=openai/openai/eccn-gpt-6.1-sol+ claude-code=aws/anthropic/eccn-claude-opus-5-5secrets:OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}NVIDIA_API_KEY: ${{ secrets.NVIDIA_API_KEY }}+ LLM_API_KEY: ${{ secrets[vars.SKILL_EVAL_GATEWAY_SECRET] }}diff --git a/.github/workflows/skill-feedback-all-tiers.yml b/.github/workflows/skill-feedback-all-tiers.ymlindex 63f7b3be..4d970614 100644--- a/.github/workflows/skill-feedback-all-tiers.yml+++ b/.github/workflows/skill-feedback-all-tiers.yml@@ -12,9 +12,20 @@ permissions:pull-requests: writejobs:feedback:- uses: NVIDIA/SkillEvaluator/.github/workflows/feedback-all-tiers.yml@c3b298c2b1a1a89d520bb22009f2668520127931+ uses: NVIDIA/SkillEvaluator/.github/workflows/feedback-all-tiers.yml@e56ced7f72904e055b04a5024c688d7603d5b49awith:tools-repository: NVIDIA/SkillEvaluator- tools-ref: c3b298c2b1a1a89d520bb22009f2668520127931- trusted-workflow-ref: NVIDIA/SkillEvaluator/.github/workflows/evaluate-all-tiers.yml@c3b298c2b1a1a89d520bb22009f2668520127931- trusted-caller-blobs: 09bc951c5df415090d7e6c8159d87ab0fd1e98f8+ tools-ref: e56ced7f72904e055b04a5024c688d7603d5b49a+ trusted-workflow-ref: NVIDIA/SkillEvaluator/.github/workflows/evaluate-all-tiers.yml@e56ced7f72904e055b04a5024c688d7603d5b49a+ trusted-caller-blobs: da786a5ab65cda8b4a2b9cbbb7c76db49e28f077+ benchmarks:+ uses: NVIDIA/SkillEvaluator/.github/workflows/publish-benchmarks.yml@e56ced7f72904e055b04a5024c688d7603d5b49a+ permissions:+ contents: write+ actions: read+ pull-requests: write+ with:+ tools-repository: NVIDIA/SkillEvaluator+ tools-ref: e56ced7f72904e055b04a5024c688d7603d5b49a+ trusted-workflow-ref: NVIDIA/SkillEvaluator/.github/workflows/evaluate-all-tiers.yml@e56ced7f72904e055b04a5024c688d7603d5b49a+ trusted-caller-blobs: da786a5ab65cda8b4a2b9cbbb7c76db49e28f077diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3b03212f..1ee5b02b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,16 @@ All notable changes to SkillEvaluator are documented in this file.### Added+- Capability-gated CI onboarding for protected Tier 1 `--llm`/SkillSpector+ checks, independent Tier 3 gateway/judge settings and native agent models.+ Combined reports retain source-bound `BENCHMARK.md` cards for every outcome;+ GitHub can optionally propose eligible cards through a separate trusted+ benchmark-update PR. Tier 2/3 remain advisory for CI. Retained JSON preserves+ Tier 1 required-check and unscanned-content scope for publication decisions.+ The repository's own candidate CI selects Build for Tier 1/2 and separate+ gateway-backed Claude Code/Codex models for Tier 3, without changing upstream+ provider defaults.+- HTML, Markdown, and terminal findings show recorded LLM verification verdicts,confidence, and reasoning, with an explanation of retained or downgraded severity.Medium-confidence false positives and uncertain verdicts retain existing gates.@@ -134,7 +144,7 @@ All notable changes to SkillEvaluator are documented in this file.onboarding and status recognize this filename collision without replacingreusable workflow definitions. Automatic comments activate after thelistener reaches the default branch.- Document the shared chat/judge/agent model input and model-availability+ Document independent chat, judge and agent model settings and model-availabilitytroubleshooting for provider-backed CI.- `skills/skillevaluator/` is an agent skill for operating SkillEvaluator: itroutes requests to the right tier, readiness check, dataset, report, or CIdiff --git a/ci/benchmark_publish.py b/ci/benchmark_publish.pynew file mode 100644index 00000000..2f4c99a2--- /dev/null+++ b/ci/benchmark_publish.py@@ -0,0 +1,406 @@+# SPDX-License-Identifier: Apache-2.0+# ruff: noqa: INP001, T201 -- pinned trusted CI entrypoint with fixed diagnostics.+"""Propose eligible native benchmark cards through a dedicated GitHub PR."""++from __future__ import annotations++import argparse+import hashlib+import http.client+import json+import os+import re+import sys+import urllib.error+import urllib.parse+from pathlib import Path++if __package__:+ from . import feedback, github_api, publish_reports+ from .benchmark_reports import benchmark_documents+else:+ sys.path.insert(0, str(Path(__file__).resolve().parent))+ import feedback+ import github_api+ import publish_reports+ from benchmark_reports import benchmark_documents++BRANCH = "skillevaluator/benchmark-update"+MARKER = "<!-- skillevaluator-benchmark-update -->"+PR_DISABLED = "Benchmark cards are ready on the dedicated bot branch. Enable GitHub Actions permission to create pull requests, or open a pull request from skillevaluator/benchmark-update manually."+_require = feedback._require+++def _sha(value):+ _require(isinstance(value, str) and github_api.COMMIT_SHA.fullmatch(value), "A Git object identity is invalid.")+ return value+++def _optional(api, path):+ try:+ return api.get(path)+ except urllib.error.HTTPError as error:+ if error.code != 404:+ raise+ return None+++def _head(api, root, branch):+ value = api.get(f"{root}/git/ref/heads/{urllib.parse.quote(branch, safe='/')}")+ _require(value.get("object", {}).get("type") == "commit", "A branch does not identify a commit.")+ return _sha(value["object"].get("sha"))+++def _tree(api, root, commit):+ value = api.get(f"{root}/git/commits/{commit}")+ sha = _sha(value.get("tree", {}).get("sha"))+ result = api.get(f"{root}/git/trees/{sha}?recursive=1")+ _require(+ result.get("truncated") is False and isinstance(result.get("tree"), list), "The repository tree is incomplete."+ )+ entries = {}+ for entry in result["tree"]:+ path = entry.get("path")+ # Unrelated repository paths are only compared, never written; written+ # card and receipt paths get their own _safe_path checks.+ _require(+ isinstance(path, str) and 0 < len(path) <= 4096 and path not in entries,+ "The repository tree has an invalid path.",+ )+ _sha(entry.get("sha"))+ entries[path] = entry+ return sha, entries+++def _regular_targets(entries, targets):+ for path in targets:+ parts = path.split("/")+ for index in range(1, len(parts)):+ ancestor = entries.get("/".join(parts[:index]))+ _require(+ ancestor is not None and ancestor.get("mode") == "040000" and ancestor.get("type") == "tree",+ "A benchmark parent is not a regular source directory.",+ )+ entry = entries.get(path)+ _require(+ entry is None or (entry.get("mode") in {"100644", "100755"} and entry.get("type") == "blob"),+ "An existing benchmark target is not a regular file.",+ )+++def _pull_identity(pull):+ base, user = pull.get("base") or {}, pull.get("user") or {}+ return (+ pull.get("number"),+ pull.get("state"),+ pull.get("title"),+ pull.get("body"),+ base.get("ref"),+ (base.get("repo") or {}).get("full_name"),+ user.get("login"),+ user.get("type"),+ )+++def _blob(content):+ payload = content.encode("utf-8")+ return hashlib.sha1(+ b"blob " + str(len(payload)).encode("ascii") + b"\0" + payload, usedforsecurity=False+ ).hexdigest()+++def github_benchmark_publish(api, repository: str, run_id: int, attempt: int) -> dict:+ """Authenticate evidence, regenerate cards, then propose only eligible cards.++ No source checkout or artifact Markdown is read. Updates fast-forward the+ dedicated branch; unrelated branch differences require manual reconciliation.+ """+ native = {}+ evidence = feedback.verify_github_evidence(+ api, repository, run_id, attempt, events=frozenset({"push", "workflow_dispatch"}), native_reports=native+ )+ run = evidence["run"]+ source = run["head_sha"]+ root = f"/repos/{repository}"+ info = api.get(root)+ default = info.get("default_branch")+ _require(+ isinstance(default, str)+ and feedback._safe_path(default)+ and default != BRANCH+ and run.get("head_branch") == default,+ "The producer must target the current default branch.",+ )++ def current():+ latest = api.get(f"{root}/actions/runs/{run_id}")+ return (+ _head(api, root, default) == source+ and latest.get("id") == run_id+ and latest.get("run_attempt") == attempt+ and latest.get("status") == "completed"+ and latest.get("head_sha") == source+ and latest.get("head_branch") == default+ and latest.get("event") == run["event"]+ and latest.get("repository", {}).get("full_name") == repository+ and latest.get("head_repository", {}).get("full_name") == repository+ )++ if not current():+ # A newer default-branch push or attempt supersedes this producer; that+ # is routine on an active branch, not a publication failure.+ return {+ "benchmark_action": "skipped",+ "benchmark_reason": "The source head, producer attempt or bot branch changed.",+ }+ targets = {}+ for document in benchmark_documents(evidence["manifest"], native):+ if not document["eligible"]:+ continue+ skill = document["path"]+ _require(skill == "." or feedback._safe_path(skill), "A benchmark source path is invalid.")+ path = "BENCHMARK.md" if skill == "." else skill + "/BENCHMARK.md"+ _require(+ path not in targets and isinstance(document["benchmark_content"], str), "A benchmark target is ambiguous."+ )+ targets[path] = document["benchmark_content"]+ if not targets:+ return {"benchmark_action": "unchanged", "benchmark_reason": "No eligible benchmark cards."}+ source_tree, source_entries = _tree(api, root, source)+ _regular_targets(source_entries, targets)+ # A card already identical on the default branch needs no review branch.+ if all(source_entries.get(path, {}).get("sha") == _blob(content) for path, content in targets.items()):+ return {"benchmark_action": "unchanged"}+ branch_ref = _optional(api, f"{root}/git/ref/heads/{BRANCH}")+ branch = None+ base_tree, entries = source_tree, source_entries+ if branch_ref is not None:+ _require(branch_ref.get("object", {}).get("type") == "commit", "The bot branch is not a commit.")+ branch = _sha(branch_ref["object"].get("sha"))+ previous = api.get(f"{root}/git/commits/{branch}")+ message = previous.get("message")+ _require(+ isinstance(message, str)+ and len(message.encode("utf-8")) <= 1024 * 1024+ and message.startswith("Update eligible SkillEvaluator benchmark cards\n\n"),+ "The bot branch lacks its publication source receipt.",+ )+ trailers = [line for line in message.splitlines() if line.startswith("Source:")]+ _require(+ len(trailers) == 1 and re.fullmatch(r"Source: [0-9a-f]{40}", trailers[0]),+ "The bot branch source trailer is missing or ambiguous.",+ )+ previous_source = trailers[0].removeprefix("Source: ")+ if previous_source != source:+ relation = api.get(f"{root}/compare/{previous_source}...{source}")+ _require(+ relation.get("status") == "ahead"+ and relation.get("merge_base_commit", {}).get("sha") == previous_source,+ "The recorded publication source is not in current default-branch history.",+ )+ _, prior_entries = _tree(api, root, previous_source)+ _, branch_entries = _tree(api, root, branch)+ # Validate the old proposal against its own immutable source, never+ # against the newer default tree. No old branch files are copied.+ receipts = [line for line in message.splitlines() if line.startswith("Benchmark-Cards:")]+ _require(+ len(receipts) == 1 and receipts[0].startswith("Benchmark-Cards: "),+ "The bot branch card receipt is missing or ambiguous.",+ )+ cards = github_api.strict_json(+ receipts[0].removeprefix("Benchmark-Cards: ").encode("utf-8"),+ feedback.FeedbackError,+ "The bot branch card receipt is invalid.",+ )+ _require(+ isinstance(cards, dict) and 0 < len(cards) <= feedback.MAX_SKILLS, "The bot branch card receipt is invalid."+ )+ for path, blob in cards.items():+ _require(+ feedback._safe_path(path) and path.rsplit("/", maxsplit=1)[-1] == "BENCHMARK.md",+ "The bot branch card receipt has an unsafe path.",+ )+ _sha(blob)+ entry = branch_entries.get(path, {})+ _require(+ entry.get("sha") == blob and entry.get("mode") == "100644" and entry.get("type") == "blob",+ "A previously generated card was changed or removed.",+ )+ _regular_targets(prior_entries, cards)+ _regular_targets(branch_entries, cards)+ ancestors = {"/".join(path.split("/")[:index]) for path in cards for index in range(1, len(path.split("/")))}++ def unrelated(rows):+ return {+ path: (row.get("mode"), row.get("type"), row.get("sha"))+ for path, row in rows.items()+ if path not in cards and path not in ancestors+ }++ _require(+ unrelated(branch_entries) == unrelated(prior_entries), "The bot branch contains unrelated source changes."+ )+ # Reuse a matching proposal on the same source; otherwise build the+ # complete desired tree from current source plus newly generated cards.+ desired_matches_branch = (+ previous_source == source+ and all(branch_entries.get(path, {}).get("sha") == _blob(content) for path, content in targets.items())+ and all(path in targets or branch_entries.get(path) == source_entries.get(path) for path in cards)+ )+ if desired_matches_branch:+ entries = branch_entries+ pulls = feedback._listing(+ api,+ f"{root}/pulls?state=open&head={urllib.parse.quote(repository.split('/', maxsplit=1)[0] + ':' + BRANCH, safe='')}",+ )+ _require(len(pulls) <= 1, "Multiple benchmark pull requests require reconciliation.")+ pull = pulls[0] if pulls else None+ if pull:+ _require(+ pull.get("state") == "open"+ and pull.get("head", {}).get("ref") == BRANCH+ and pull.get("base", {}).get("ref") == default+ and all(pull.get(part, {}).get("repo", {}).get("full_name") == repository for part in ("head", "base"))+ and pull.get("user", {}).get("type") == "Bot"+ and pull["user"].get("login") == "github-actions[bot]"+ and isinstance(pull.get("body"), str)+ and pull["body"].startswith(MARKER + "\n"),+ "The existing benchmark PR is not owned by this publisher.",+ )+ feedback._positive(pull.get("number"))+ changes = [+ {"path": path, "mode": "100644", "type": "blob", "content": content}+ for path, content in sorted(targets.items())+ if entries.get(path, {}).get("sha") != _blob(content)+ ]++ def guarded():+ if not current():+ return False+ # Ref rereads protect against concurrent human edits; force is never used.+ latest = _optional(api, f"{root}/git/ref/heads/{BRANCH}")+ return (+ latest is None if branch is None else latest is not None and latest.get("object", {}).get("sha") == branch+ )++ if not guarded():+ return {+ "benchmark_action": "skipped",+ "benchmark_reason": "The source head, producer attempt or bot branch changed.",+ }+ if changes:+ commit_message = (+ f"Update eligible SkillEvaluator benchmark cards\n\nSource: {source}\nRun: {run_id}/{attempt}\nBenchmark-Cards: "+ + json.dumps(+ {path: _blob(content) for path, content in targets.items()},+ sort_keys=True,+ ensure_ascii=True,+ separators=(",", ":"),+ )+ )+ _require(+ len(commit_message.encode("utf-8")) <= 1024 * 1024, "The benchmark commit receipt exceeds its size limit."+ )+ tree = api.post(f"{root}/git/trees", {"base_tree": base_tree, "tree": changes})+ if not guarded():+ return {+ "benchmark_action": "skipped",+ "benchmark_reason": "The source head, producer attempt or bot branch changed.",+ }+ commit = api.post(+ f"{root}/git/commits",+ {+ "message": commit_message,+ "tree": _sha(tree.get("sha")),+ "parents": list(dict.fromkeys([branch, source] if branch else [source])),+ },+ )+ if not guarded():+ return {+ "benchmark_action": "skipped",+ "benchmark_reason": "The source head, producer attempt or bot branch changed.",+ }+ commit_sha = _sha(commit.get("sha"))+ if branch is None:+ response = api.post(f"{root}/git/refs", {"ref": f"refs/heads/{BRANCH}", "sha": commit_sha})+ else:+ response = api.patch(f"{root}/git/refs/heads/{BRANCH}", {"sha": commit_sha, "force": False})+ _require(response.get("object", {}).get("sha") == commit_sha, "The bot branch update was not acknowledged.")+ branch = commit_sha+ if not guarded():+ return {+ "benchmark_action": "skipped",+ "benchmark_reason": "The source head, producer attempt or bot branch changed.",+ }+ report = f"https://github.com/{repository}/actions/runs/{run_id}/artifacts/{evidence['artifact']['id']}"+ body = f"{MARKER}\nRegenerated eligible benchmark cards from validated canonical native JSON.\n\nSource commit: `{source}`\n\n[Evaluation reports]({report}) · attempt {attempt}\n"+ payload = {"title": "Update SkillEvaluator benchmark cards", "body": body}+ if pull:+ if pull.get("body") == body and pull.get("title") == payload["title"]:+ return {+ "benchmark_action": "updated" if changes else "unchanged",+ "benchmark_pr_url": f"https://github.com/{repository}/pull/{pull['number']}",+ }+ check = api.get(f"{root}/pulls/{pull['number']}")+ # base.repo is the live repository object (pushed_at, counters), and the+ # branch update above is itself a push. Compare only stable PR identity.+ _require(_pull_identity(check) == _pull_identity(pull), "The benchmark PR changed before update.")+ _require(+ check.get("head", {}).get("ref") == BRANCH+ and check.get("head", {}).get("repo", {}).get("full_name") == repository+ and check.get("head", {}).get("sha") == branch,+ "The benchmark PR head changed before update.",+ )+ if not guarded():+ return {+ "benchmark_action": "skipped",+ "benchmark_reason": "The source head, producer attempt or bot branch changed.",+ }+ response = api.patch(f"{root}/pulls/{pull['number']}", payload)+ action = "updated"+ else:+ try:+ response = api.post(f"{root}/pulls", {**payload, "base": default, "head": BRANCH})+ except urllib.error.HTTPError as error:+ if error.code != 403:+ raise+ return {"benchmark_action": "branch_ready", "benchmark_reason": PR_DISABLED}+ action = "created"+ number = feedback._positive(response.get("number"))+ return {"benchmark_action": action, "benchmark_pr_url": f"https://github.com/{repository}/pull/{number}"}+++def main(argv=None) -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--repository", required=True)+ parser.add_argument("--run-id", required=True, type=int)+ parser.add_argument("--run-attempt", required=True, type=int)+ args = parser.parse_args(argv)+ try:+ token = os.environ.get("GITHUB_TOKEN", "").strip()+ _require(bool(token), "GITHUB_TOKEN is required.")+ result = github_benchmark_publish(+ publish_reports.GitHubAPI(args.repository, token), args.repository, args.run_id, args.run_attempt+ )+ print(json.dumps(result, sort_keys=True))+ return 0+ except (+ feedback.FeedbackError,+ publish_reports.PublicationError,+ OSError,+ ValueError,+ TypeError,+ KeyError,+ AttributeError,+ urllib.error.URLError,+ http.client.HTTPException,+ ):+ print(+ "Trusted benchmark publication could not validate its evidence, current default head, or dedicated bot branch.",+ file=sys.stderr,+ )+ return 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/ci/benchmark_reports.py b/ci/benchmark_reports.pynew file mode 100644index 00000000..232c34b6--- /dev/null+++ b/ci/benchmark_reports.py@@ -0,0 +1,242 @@+# SPDX-License-Identifier: Apache-2.0+# ruff: noqa: INP001 -- trusted CI reporting helper.+"""Compose source-bound cards from retained JSON, without opening skill sources."""++from __future__ import annotations++import copy+import json+import re+import unicodedata+from pathlib import Path, PurePosixPath++from skillevaluator.models import ValidationResult+from skillevaluator.reporting import BenchmarkReporter, JSONReporter+from skillevaluator.reporting.retained import retained_results+from skillevaluator.reporting.run_status import resolve_run_status+from skillevaluator.source_identity import (+ EVALUATED_SOURCE_FIELDS,+ EvaluatedSourceConflict,+ evaluated_source_carriers,+ merge_evaluated_sources,+ normalized_evaluated_source,+)++try:+ from github_api import strict_json+except ModuleNotFoundError:+ from ci.github_api import strict_json++_MAX_REPORT_BYTES = 32 * 1024 * 1024+++def _report_path(reports: Path, relative: str) -> Path:+ """Accept only canonical relative paths through regular retained directories."""+ if (+ not isinstance(relative, str)+ or not relative+ or any(character in relative for character in "\\:%?#")+ or relative.startswith("/")+ or any(part in {"", ".", ".."} for part in relative.split("/"))+ or PurePosixPath(relative).as_posix() != relative+ ):+ raise ValueError("Unsafe retained report path")+ path = reports+ for part in relative.split("/"):+ path /= part+ if path.is_symlink():+ raise ValueError("Linked retained report path")+ return path+++def _load_payload(reports: Path, relative: str) -> dict:+ path = _report_path(reports, relative)+ if not path.is_file() or path.stat().st_size > _MAX_REPORT_BYTES:+ raise ValueError("Missing or oversized retained report")+ return strict_json(path.read_bytes(), ValueError, "Invalid retained JSON")+++def _incomplete(tier: int) -> ValidationResult:+ """Record transport/execution gaps without certifying a native check."""+ name = {1: "CI Tier 1 Evidence", 2: "CI Similarity Evidence", 3: "CI Tier 3 Evidence"}[tier]+ metadata = {+ "incomplete_scans": [f"Tier {tier} retained evidence is missing, invalid or incomplete."],+ "gating": {"tier": tier, "blocking": tier == 1},+ }+ if tier == 3:+ metadata["agent_eval"] = {}+ return ValidationResult(validator_name=name, passed=False, metadata=metadata)+++def _bind_identity(results: list[ValidationResult], skill: str) -> str | None:+ """Preserve claims exactly and fail closed even on case-only source conflicts."""+ targets = []+ for result in results:+ metadata = result.metadata+ containers = [metadata]+ agent = metadata.get("agent_eval")+ if isinstance(agent, dict):+ containers += [agent, agent.get("summary", {})]+ targets.extend(container["publication_target"] for container in containers if "publication_target" in container)+ names = [target.get("skill_name") for target in targets if isinstance(target, dict)]+ expected = unicodedata.normalize("NFC", PurePosixPath(skill).name) if skill != "." else next(iter(names), None)+ if targets and (any(target != targets[0] for target in targets) or any(name != expected for name in names)):+ for result in results:+ result.metadata["publication_target_conflict"] = "Retained tiers identify conflicting source snapshots."+ return expected+++def _bind_evaluated_source(results: list[ValidationResult], manifest: dict) -> list[dict]:+ """Bind trusted run context; retain conflicting claims separately and fail closed.++ Reporters reject contradictory source carriers. The working render copy+ therefore moves those carriers into an explicit conflict record instead of+ silently replacing them. Canonical native inputs are never mutated.+ """+ source = {"repository": manifest.get("repository"), "commit": manifest.get("commit")}+ runtime = manifest.get("runtime")+ revision = runtime.get("tools_ref") if isinstance(runtime, dict) else None+ if isinstance(revision, str) and re.fullmatch(r"[0-9a-f]{40}|[0-9a-f]{64}", revision):+ source["evaluator_container_revision"] = revision+ trusted = normalized_evaluated_source(source)+ claims = [+ carrier for result in results for carrier in evaluated_source_carriers(result.metadata) if carrier is not None+ ]+ try:+ for claim in claims:+ normalized = normalized_evaluated_source(claim) or {}+ if not isinstance(claim, dict) or any(+ key in claim and key not in normalized for key, _predicate in EVALUATED_SOURCE_FIELDS+ ):+ raise EvaluatedSourceConflict("Malformed retained evaluated-source claim")+ bound = merge_evaluated_sources([trusted, *claims])+ except EvaluatedSourceConflict:+ conflicts = copy.deepcopy(claims)+ for result in results:+ metadata = result.metadata+ containers = [metadata]+ agent = metadata.get("agent_eval")+ if isinstance(agent, dict):+ containers += [agent, agent.get("summary", {})]+ for container in containers:+ container.pop("evaluated_source", None)+ metadata["publication_target_conflict"] = "Retained evaluated-source claims contradict the trusted run."+ if trusted:+ metadata["evaluated_source"] = dict(trusted)+ return conflicts+ if bound:+ for result in results:+ # This merge adds only compatible fields; original native values+ # and nested payload claims remain unchanged when they agree.+ result.metadata["evaluated_source"] = dict(bound)+ return []+++def _native_status(results: list[ValidationResult], tier: int) -> str:+ status = resolve_run_status(results).tiers[tier].status.value+ if tier == 3 and status == "passed":+ for result in results:+ agent = result.metadata.get("agent_eval", {})+ summary = agent.get("summary", {})+ if agent.get("verdict", summary.get("verdict")) == "neutral":+ return "neutral"+ return status+++def benchmark_documents(manifest: dict, native_reports: dict[str, dict]) -> list[dict]:+ """Compose trusted native JSON in memory; never trust artifact Markdown.++ The caller validates the CI manifest and bounds the native JSON mapping.+ Rows contain link metadata plus ``combined_content`` and+ ``benchmark_content`` strings. Policy and provenance logic is shared with+ the filesystem writer; CI gate flags never grant publication waivers.+ """+ grouped: dict[str, dict[int, dict]] = {}+ for tier in manifest["tiers"]:+ number = tier["tier"]+ for skill in tier["skills"]:+ grouped.setdefault(skill["path"], {})[number] = skill+ for selected in tier.get("selected", []):+ grouped.setdefault(selected, {}).setdefault(number, {"status": "incomplete", "report_json": None})+ documents = []+ for index, (skill, tiers) in enumerate(sorted(grouped.items()), 1):+ results = []+ for number in (1, 2, 3):+ row = tiers.get(number)+ if row is None:+ if number == 1:+ results.append(_incomplete(number))+ continue+ retained = []+ try:+ retained = retained_results(native_reports[row.get("report_json")], allowed_tiers={number})+ except (ValueError, TypeError, KeyError):+ # Worker-controlled errors may contain secrets. Keep fixed diagnostics.+ if row.get("status") != "skipped" or row.get("report_json") is not None:+ retained.append(_incomplete(number))+ contradictory_status = bool(retained) and row.get("status") != _native_status(retained, number)+ missing_lineup = number == 1 and any(+ result.metadata.get("publication_evidence", {}).get("tier") == 1+ and "tier1_required_checks" not in result.metadata+ for result in retained+ )+ if (+ retained+ and (+ row.get("status") not in {"passed", "failed", "neutral", "skipped"}+ or row.get("error")+ or contradictory_status+ or missing_lineup+ )+ and not any(result.is_incomplete for result in retained)+ ):+ retained.append(_incomplete(number))+ # Process gating is independent of the native publication policy.+ for result in retained:+ result.metadata["gating"] = {"tier": number, "blocking": number == 1}+ results.extend(retained)+ expected = _bind_identity(results, skill)+ conflicts = _bind_evaluated_source(results, manifest)+ combined = JSONReporter(include_timestamp=False, expected_skill_name=expected).render_all(results)+ if conflicts:+ payload = json.loads(combined)+ payload["evaluated_source_conflicts"] = conflicts+ combined = json.dumps(payload, indent=2, ensure_ascii=False)+ card = BenchmarkReporter(include_timestamp=False, skill_name=expected).render_all(results)+ directory = f"benchmarks/skill-{index:03}"+ paths = {"combined_json": f"{directory}/skillevaluator.json", "benchmark_md": f"{directory}/BENCHMARK.md"}+ publication = json.loads(combined)["publication"]+ documents.append(+ {+ "path": skill,+ **paths,+ "publication_status": publication["status"],+ "eligible": publication["eligible"],+ "combined_content": combined,+ "benchmark_content": card,+ }+ )+ return documents+++def write_benchmark_reports(reports: Path, manifest: dict) -> list[dict]:+ """Write deterministic per-skill reports and return only their link metadata."""+ native_reports = {}+ for tier in manifest["tiers"]:+ for row in tier["skills"]:+ relative = row.get("report_json")+ if relative is not None and relative not in native_reports:+ try:+ native_reports[relative] = _load_payload(reports, relative)+ except (OSError, ValueError, TypeError, KeyError):+ # Absence is turned into fixed incomplete evidence by the composer.+ continue+ links = []+ for document in benchmark_documents(manifest, native_reports):+ metadata = dict(document)+ for field, content_key in (("combined_json", "combined_content"), ("benchmark_md", "benchmark_content")):+ destination = _report_path(reports, metadata[field])+ destination.parent.mkdir(parents=True, exist_ok=True)+ destination.write_text(metadata.pop(content_key), encoding="utf-8")+ links.append(metadata)+ return linksdiff --git a/ci/bootstrap_tiers.py b/ci/bootstrap_tiers.pyindex 05dca424..0ec3c395 100644--- a/ci/bootstrap_tiers.py+++ b/ci/bootstrap_tiers.py@@ -8,6 +8,16 @@ from __future__ import annotationsimport osimport subprocessimport sys+from pathlib import Path++# Trust only the pinned tools sibling when isolated Python omits its directory.+if not __package__:+ sys.path.insert(0, str(Path(__file__).resolve().parent))++try:+ from model_config import agent_model_overrides, model_environment+except ModuleNotFoundError:+ from ci.model_config import agent_model_overrides, model_environmentfrom skillevaluator.tier3.commands import resolve_agentsfrom skillevaluator.tier3.harbor.local_runtime import managed_install_argv, managed_runtime_prefix@@ -31,17 +41,19 @@ def main() -> int:print("Three-tier CI supports docker and local environments only.")return 2try:+ doctor_env = model_environment(dict(os.environ), 3)+ models = agent_model_overrides(dict(os.environ))agents = resolve_agents(- os.environ.get("SKILL_EVAL_AGENTS") or None, provider=os.environ.get("SKILL_EVAL_PROVIDER", "openai")+ os.environ.get("SKILL_EVAL_AGENTS") or None, provider=doctor_env["SKILL_EVAL_LLM_PROVIDER"])if mode == "local":for agent in agents:install_agent(agent)- doctor_env = dict(os.environ)- doctor_env["SKILL_EVAL_LLM_PROVIDER"] = os.environ.get("SKILL_EVAL_PROVIDER", "openai")- doctor_env["PYTHON_DOTENV_DISABLED"] = "1"- if model := os.environ.get("SKILL_EVAL_MODEL"):- doctor_env["SKILL_EVAL_LLM_MODEL"] = model+ # Native local runtimes were installed under the runner's home. Keep that+ # location without inheriting the runner's arbitrary environment.+ if os.environ.get("HOME"):+ doctor_env["HOME"] = os.environ["HOME"]+ model_args = [argument for model in models for argument in ("--agent-model", model)]result = subprocess.run([sys.executable,@@ -49,10 +61,14 @@ def main() -> int:"-m","skillevaluator.cli","doctor",+ "--tier",+ "3",+ "--verify-models","--env-mode",mode,"--agents",",".join(agents),+ *model_args,],check=False,env=doctor_env,diff --git a/ci/eligible_gitlab.py b/ci/eligible_gitlab.pyindex 17e7dd4b..012041af 100644--- a/ci/eligible_gitlab.py+++ b/ci/eligible_gitlab.py@@ -1,7 +1,7 @@#!/usr/bin/env python3# SPDX-License-Identifier: Apache-2.0# ruff: noqa: T201 — command-line helper diagnostics-"""Fail closed before a provider-backed GitLab MR evaluation."""+"""Fail closed before a provider-backed GitLab evaluation."""from __future__ import annotations@@ -31,7 +31,19 @@ def eligible(env: Mapping[str, str], current: dict | None) -> bool:and current.get("sha") == env.get("CI_COMMIT_SHA"))return (- bool(env.get("CI_DEFAULT_BRANCH"))+ _default_branch_candidate(env)+ and isinstance(current, dict)+ and current.get("name") == env["CI_DEFAULT_BRANCH"]+ and current.get("protected") is True+ and isinstance(current.get("commit"), dict)+ and current["commit"].get("id") == env["CI_COMMIT_SHA"]+ )+++def _default_branch_candidate(env: Mapping[str, str]) -> bool:+ return (+ bool(env.get("CI_COMMIT_SHA"))+ and bool(env.get("CI_DEFAULT_BRANCH"))and env.get("CI_COMMIT_BRANCH") == env["CI_DEFAULT_BRANCH"]and env.get("CI_COMMIT_REF_PROTECTED") == "true"and env.get("CI_PIPELINE_SOURCE") in {"push", "web"}@@ -41,9 +53,15 @@ def eligible(env: Mapping[str, str], current: dict | None) -> bool:def main() -> int:env = os.environcurrent = None- if env.get("CI_PIPELINE_SOURCE") == "merge_request_event":+ is_mr = env.get("CI_PIPELINE_SOURCE") == "merge_request_event"+ if is_mr or _default_branch_candidate(env):+ kind = "merge-request" if is_mr else "default-branch"base = env.get("CI_API_V4_URL", "")- parsed = urllib.parse.urlsplit(base)+ try:+ parsed = urllib.parse.urlsplit(base)+ except ValueError:+ print("GitLab admission requires an HTTPS API endpoint.")+ return 2if (parsed.scheme != "https"or not parsed.hostname@@ -57,14 +75,19 @@ def main() -> int:return 2project = env.get("CI_PROJECT_ID", "")iid = env.get("CI_MERGE_REQUEST_IID", "")- if not project.isdigit() or not iid.isdigit():+ if not project.isdigit() or (is_mr and not iid.isdigit()):return 2- # GitLab added job-token authentication for this endpoint in 18.4.+ resource = (+ f"merge_requests/{iid}"+ if is_mr+ else "repository/branches/" + urllib.parse.quote(env["CI_DEFAULT_BRANCH"], safe="")+ )+ # GitLab added job-token authentication for the MR endpoint in 18.4.# Older servers use a separate project Reporter/read_api token, never# the publisher credential or the local onboarding user's PAT.read_token = env.get("SKILLEVALUATOR_GITLAB_READ_TOKEN", "").strip()headers = {"PRIVATE-TOKEN": read_token} if read_token else {"JOB-TOKEN": env.get("CI_JOB_TOKEN", "")}- request = urllib.request.Request(f"{base.rstrip('/')}/projects/{project}/merge_requests/{iid}", headers=headers)+ request = urllib.request.Request(f"{base.rstrip('/')}/projects/{project}/{resource}", headers=headers)try:with urllib.request.build_opener(_NoRedirect()).open(request, timeout=30) as response:payload = response.read(1024 * 1024 + 1)@@ -74,16 +97,19 @@ def main() -> int:if not isinstance(current, dict):raise ValueError("Invalid admission response")except urllib.error.HTTPError as error:- print(f"Current merge-request head could not be verified (HTTP {error.code}).")- print(- "GitLab before 18.4 requires a separate SKILLEVALUATOR_GITLAB_READ_TOKEN with project Reporter/read_api access."- )+ print(f"Current {kind} head could not be verified (HTTP {error.code}).")+ if is_mr or error.code in {401, 403, 404}:+ print(+ "Configure or verify SKILLEVALUATOR_GITLAB_READ_TOKEN with project Reporter/read_api access. "+ "This separate read token is required for MR admission before GitLab 18.4 and whenever "+ "CI_JOB_TOKEN cannot read the current-head endpoint."+ )return 2except urllib.error.URLError as error:- print(f"Current merge-request head could not be verified (transport {type(error.reason).__name__}).")+ print(f"Current {kind} head could not be verified (transport {type(error.reason).__name__}).")return 2except (OSError, ValueError) as error:- print(f"Current merge-request head could not be verified ({type(error).__name__}).")+ print(f"Current {kind} head could not be verified ({type(error).__name__}).")return 2if not eligible(env, current):print("Provider jobs require the current same-project MR head or a protected default branch.")diff --git a/ci/feedback.py b/ci/feedback.pyindex 3b1d6eec..f0337629 100644--- a/ci/feedback.py+++ b/ci/feedback.py@@ -29,23 +29,20 @@ from pathlib import Path# Isolated Python omits the script directory. Trust only this pinned helper# checkout for sibling imports, never the consumer working directory.-if not __package__:+if __package__:+ from . import github_api, publish_reports+ from .comment_summary import render_comment_summary+ from .summary_metrics import summarize_results+ from .tier_manifest import tier3_execution_complete, validate_manifest+ from .verify_provenance import ProvenanceError, verify_receipt+else:sys.path.insert(0, str(Path(__file__).resolve().parent))--try:import github_apiimport publish_reportsfrom comment_summary import render_comment_summaryfrom summary_metrics import summarize_resultsfrom tier_manifest import tier3_execution_complete, validate_manifestfrom verify_provenance import ProvenanceError, verify_receipt-except ModuleNotFoundError:- from ci.comment_summary import render_comment_summary- from ci.summary_metrics import summarize_results- from ci.tier_manifest import tier3_execution_complete, validate_manifest- from ci.verify_provenance import ProvenanceError, verify_receipt-- from ci import github_api, publish_reportsMARKER = "<!-- skillevaluator-all-tiers-report -->"RUN_MARKER = re.compile(r"<!-- skillevaluator-all-tiers-run:([1-9][0-9]*):([1-9][0-9]*) -->")@@ -58,7 +55,7 @@ MAX_BODY_BYTES = 60000# Markdown, SARIF, stdout and stderr) and JSON, HTML and Markdown for Tiers 2# and 3; GitLab archives also list each skill's directory once per tier.MAX_SKILLS = 100-MEMBERS_PER_SKILL = 6 + 3 + 3 + 3+MEMBERS_PER_SKILL = 6 + 3 + 3 + 3 + 3 # two generated files and their directoryMAX_AGGREGATE_MEMBERS = 64 # manifests, summaries, indexes and tier directoriesMAX_FILES = MAX_SKILLS * MEMBERS_PER_SKILL + MAX_AGGREGATE_MEMBERS# A Tier 2/3 skill whose execution failed or is incomplete, or whose worker exited@@ -122,7 +119,7 @@ def _safe_path(value):)-def read_results(raw: bytes, *, prefix: str = "") -> dict:+def read_results(raw: bytes, *, prefix: str = "", native_reports: dict | None = None) -> dict:"""Validate exact retained native JSON; never extract or interpret HTML."""_require(len(raw) <= MAX_BYTES, "The aggregate archive exceeds its size limit.")try:@@ -169,6 +166,7 @@ def read_results(raw: bytes, *, prefix: str = "") -> dict:from skillevaluator.reporting.retained import retained_resultsfrom skillevaluator.reporting.run_status import resolve_run_status+ validated_native = {}seen = set()for tier in result["tiers"]:# Comment counters come from validated native findings, never@@ -214,6 +212,7 @@ def read_results(raw: bytes, *, prefix: str = "") -> dict:tier3_execution_complete(native),"Tier 3 passing or neutral evidence lacks complete paired execution.",)+ validated_native[json_path] = nativeskill["metrics"] = summarize_results(retained, tier=tier["tier"], native=native)if skill["status"] in {"incomplete", "skipped", "not_run", "needs_action"}:skill["metrics"]["issue_count_known"] = False@@ -221,6 +220,8 @@ def read_results(raw: bytes, *, prefix: str = "") -> dict:skill["metrics"]["issue_count_known"] = Falseskill["metrics"].pop("score", None)skill["metrics"].pop("skill_lift", None)+ if native_reports is not None:+ native_reports.update(validated_native)return resultexcept FeedbackError:raise@@ -304,7 +305,7 @@ def _upsert(api, *, collection, member, owned, body, receipt, current, method="preturn {"comment_action": action, "comment_id": str(identifier)}-def _github_run(run, repository, run_id, attempt):+def _github_run(run, repository, run_id, attempt, *, events=frozenset({"pull_request"})):_require(isinstance(run, dict)and run.get("id") == run_id@@ -313,7 +314,7 @@ def _github_run(run, repository, run_id, attempt):"The run identity or latest attempt does not match the selected producer.",)_require(- run.get("event") == "pull_request"+ run.get("event") in eventsand run.get("status") == "completed"and run.get("path") == CALLER_PATHand isinstance(run.get("head_sha"), str)@@ -360,22 +361,21 @@ def _github_artifacts(api, root, run):return selected-def github_feedback(api, repository: str, run_id: int, attempt: int) -> dict:- """Authenticate immutable producer identity and upsert current same-repo PR feedback."""+def verify_github_evidence(+ api, repository, run_id, attempt, *, events=frozenset({"pull_request"}), native_reports=None+):+ """Authenticate one exact producer and validate all canonical retained JSON.++ This read-only helper grants no write policy; callers must check the current+ source head and latest attempt immediately before each visible mutation.+ """_require(isinstance(repository, str) and github_api.REPOSITORY.fullmatch(repository), "Invalid GitHub repository.")_positive(run_id)_positive(attempt)root = f"/repos/{repository}"run = api.get(f"{root}/actions/runs/{run_id}")- if isinstance(run, dict) and run.get("id") == run_id and run.get("repository", {}).get("full_name") == repository:- # Fork PRs get no receipt, and a re-run supersedes this attempt; neither is a feedback failure.- head = run.get("head_repository")- if not isinstance(head, dict) or head.get("full_name") != repository:- return {"comment_action": "skipped", "comment_reason": "Fork pull-request runs do not receive feedback."}- latest = run.get("run_attempt")- if (type(latest) is int and latest > attempt) or (latest == attempt and run.get("status") != "completed"):- return {"comment_action": "skipped", "comment_reason": "The producer attempt was superseded."}- _github_run(run, repository, run_id, attempt)+ _github_run(run, repository, run_id, attempt, events=events)+ _require(run.get("head_repository", {}).get("full_name") == repository, "Fork producers are not authorized.")reference = os.environ.get("SKILL_EVAL_TRUSTED_WORKFLOW_REF", "")match = re.fullmatch(r"([A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+/\.github/workflows/[A-Za-z0-9_.-]+\.yml)@([0-9a-f]{40})", reference@@ -415,7 +415,7 @@ def github_feedback(api, repository: str, run_id: int, attempt: int) -> dict:and caller.get("sha") in pins,"The executed caller workflow blob is not approved.",)- manifest = read_results(api.download_artifact(artifact["id"]))+ manifest = read_results(api.download_artifact(artifact["id"]), native_reports=native_reports)_require(all(manifest[k] == v@@ -429,6 +429,27 @@ def github_feedback(api, repository: str, run_id: int, attempt: int) -> dict:),"The report manifest does not match the exact producer attempt and revision.",)+ return {"run": run, "manifest": manifest, "artifact": artifact, "identity": identity}+++def github_feedback(api, repository: str, run_id: int, attempt: int) -> dict:+ """Authenticate immutable producer identity and upsert current same-repo PR feedback."""+ _require(isinstance(repository, str) and github_api.REPOSITORY.fullmatch(repository), "Invalid GitHub repository.")+ _positive(run_id)+ _positive(attempt)+ root = f"/repos/{repository}"+ run = api.get(f"{root}/actions/runs/{run_id}")+ if isinstance(run, dict) and run.get("id") == run_id and run.get("repository", {}).get("full_name") == repository:+ # Fork PRs get no receipt, and a re-run supersedes this attempt; neither is a feedback failure.+ head = run.get("head_repository")+ if not isinstance(head, dict) or head.get("full_name") != repository:+ return {"comment_action": "skipped", "comment_reason": "Fork pull-request runs do not receive feedback."}+ latest = run.get("run_attempt")+ if (type(latest) is int and latest > attempt) or (latest == attempt and run.get("status") != "completed"):+ return {"comment_action": "skipped", "comment_reason": "The producer attempt was superseded."}+ _github_run(run, repository, run_id, attempt)+ evidence = verify_github_evidence(api, repository, run_id, attempt)+ manifest, artifact = evidence["manifest"], evidence["artifact"]candidates = run.get("pull_requests") or api.get(f"{root}/commits/{run['head_sha']}/pulls")_require(isinstance(candidates, list) and len(candidates) == 1 and isinstance(candidates[0], dict),diff --git a/ci/gitlab/all-tiers.yml b/ci/gitlab/all-tiers.ymlindex 4e9e404f..dbf92d92 100644--- a/ci/gitlab/all-tiers.yml+++ b/ci/gitlab/all-tiers.yml@@ -11,9 +11,18 @@ variables:SKILL_EVAL_ENV_MODE: dockerSKILL_EVAL_PROVIDER: openaiSKILL_EVAL_MODEL: ''+ SKILL_EVAL_BASE_URL: ''+ SKILL_EVAL_TIER1_LLM: 'false'+ SKILL_EVAL_TIER1_PROVIDER: ''+ SKILL_EVAL_TIER1_MODEL: ''+ SKILL_EVAL_TIER3_PROVIDER: ''+ SKILL_EVAL_TIER3_MODEL: ''+ SKILL_EVAL_TIER3_BASE_URL: ''SKILL_EVAL_EMBEDDING_PROVIDER: ''SKILL_EVAL_EMBEDDING_MODEL: ''+ SKILL_EVAL_EMBEDDING_BASE_URL: ''SKILL_EVAL_AGENTS: ''+ SKILL_EVAL_AGENT_MODELS: ''SKILL_EVAL_N_ATTEMPTS: '1'SKILL_EVAL_N_CONCURRENT: '1'# Ends min(20 minutes, a quarter) before the 5-hour native job timeout so@@ -255,6 +264,69 @@ skill-evaluation-native-tier2:DOCKER_TLS_VERIFY: ''DOCKER_CERT_PATH: ''+skill-evaluation-tier1-llm:+ # Static Tier 1 remains available on every MR. Only this protected job sees+ # provider credentials; its evidence replaces the baseline in the aggregate.+ extends: .skill-evaluation-tools+ stage: test+ allow_failure: true+ timeout: 1 hour+ # Use the same untagged image runner as static Tier 1; the native local+ # runner selected for Tier 3 may have no Docker executor.+ image:+ name: "$SKILL_EVAL_IMAGE"+ entrypoint: [""]+ environment:+ name: $SKILL_EVAL_ENVIRONMENT+ action: prepare+ services: []+ script:+ - |+ set -eu+ python -I "$SKILL_EVAL_TOOLS_DIR/ci/eligible_gitlab.py"+ unset SKILLEVALUATOR_GITLAB_READ_TOKEN+ # The enriched evidence replaces the keyless gate; apply the same baselines.+ export SECURITY_BASELINES="${SKILL_EVAL_SECURITY_BASELINES:-false}"+ unset POLICY_SOURCE_SHA+ case "$SECURITY_BASELINES" in+ true|false) ;;+ *) echo "SKILL_EVAL_SECURITY_BASELINES must be true or false." >&2; exit 1 ;;+ esac+ if [ "$SECURITY_BASELINES" = true ]; then+ POLICY_SOURCE_SHA="$(python -I /opt/skillevaluator/ci/prepare_security_baselines.py)"+ export POLICY_SOURCE_SHA+ fi+ reports_dir="$(mktemp -d /tmp/skillevaluator-enriched-tier1.XXXXXX)"+ trap 'rm -rf "$reports_dir"' EXIT+ set +e+ python -I "$SKILL_EVAL_TOOLS_DIR/ci/run_tier1_image.py" --in-image \+ --workspace "$CI_PROJECT_DIR" --reports "$reports_dir" --image "$SKILL_EVAL_IMAGE"+ result=$?+ set -e+ artifact_dir="$CI_PROJECT_DIR/skill-evaluator-enriched-tier1"+ if [ -e "$artifact_dir" ] || [ -L "$artifact_dir" ]; then+ echo 'Use a clean checkout: skill-evaluator-enriched-tier1 already exists.' >&2+ exit 1+ fi+ mkdir "$artifact_dir"+ cp -R "$reports_dir/." "$artifact_dir/"+ exit "$result"+ artifacts:+ when: always+ paths: [skill-evaluator-enriched-tier1/]+ expire_in: 14 days+ rules:+ - if: '$SKILL_EVAL_FEEDBACK == "true"'+ when: never+ - if: '$SKILL_EVAL_TIER1_LLM != "true"'+ when: never+ - if: '$CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_SOURCE_PROJECT_ID != $CI_PROJECT_ID'+ when: never+ - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'+ # Match eligible_gitlab.py: only push and web default-branch pipelines are+ # admitted. Scheduled, API and trigger pipelines keep the keyless baseline.+ - if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH && $CI_COMMIT_REF_PROTECTED == "true" && ($CI_PIPELINE_SOURCE == "push" || $CI_PIPELINE_SOURCE == "web")'+skill-evaluation-aggregate:extends: .skill-evaluation-toolsstage: test@@ -269,6 +341,9 @@ skill-evaluation-aggregate:- job: skill-evaluation-native-tier2artifacts: trueoptional: true+ - job: skill-evaluation-tier1-llm+ artifacts: true+ optional: truescript:- |set -eu@@ -276,7 +351,24 @@ skill-evaluation-aggregate:env -i PATH="$PATH" python -I -m uv --no-config --cache-dir "$SKILL_EVAL_TOOLS_DIR/.uv-cache" sync --locked --no-dev --project "$SKILL_EVAL_TOOLS_DIR" --python 3.12 --default-index https://pypi.org/simpleexport PATH="$SKILL_EVAL_TOOLS_DIR/.venv/bin:$PATH"mkdir -p skill-evaluator-results/tier1- if [ -d skill-evaluator-report ]; then+ enriched=false+ if [ "$SKILL_EVAL_TIER1_LLM" = true ]; then+ if [ "${CI_PIPELINE_SOURCE:-}" = merge_request_event ] && [ "${CI_MERGE_REQUEST_SOURCE_PROJECT_ID:-}" = "$CI_PROJECT_ID" ]; then+ enriched=true+ elif [ "${CI_COMMIT_BRANCH:-}" = "$CI_DEFAULT_BRANCH" ] && [ "${CI_COMMIT_REF_PROTECTED:-}" = true ]; then+ # Same sources as the enriched job's rules and default-branch admission.+ case "${CI_PIPELINE_SOURCE:-}" in+ push|web) enriched=true ;;+ esac+ fi+ fi+ if [ "$enriched" = true ]; then+ # Missing authenticated evidence must fail the required gate instead of+ # silently substituting a successful static-only scan.+ if [ -d skill-evaluator-enriched-tier1 ]; then+ cp -R skill-evaluator-enriched-tier1/. skill-evaluator-results/tier1/+ fi+ elif [ -d skill-evaluator-report ]; thencp -R skill-evaluator-report/. skill-evaluator-results/tier1/fiif [ -d skill-evaluator-native ]; thendiff --git a/ci/model_config.py b/ci/model_config.pynew file mode 100644index 00000000..4e089703--- /dev/null+++ b/ci/model_config.py@@ -0,0 +1,178 @@+# SPDX-License-Identifier: Apache-2.0+# ruff: noqa: INP001 -- trusted reusable CI helper.+"""Bounded CI inputs mapped to an isolated runtime provider environment."""++from __future__ import annotations++import re+import unicodedata++from skillevaluator.provider_config import (+ ProviderConfigurationError,+ _normalize_anthropic_base_url,+ resolve_embedding_provider,+ resolve_llm_provider,+)++PROVIDER_KEYS = {+ "openai": "OPENAI_API_KEY",+ "anthropic": "ANTHROPIC_API_KEY",+ "nv_build": "NVIDIA_API_KEY",+ "openai-compatible": "SKILL_EVAL_LLM_API_KEY",+}+CREDENTIAL_KEYS = frozenset((*PROVIDER_KEYS.values(), "SKILL_EVAL_EMBEDDING_API_KEY"))+SAFE_ENV = frozenset(+ {+ "PATH",+ "LANG",+ "LC_ALL",+ "LC_CTYPE",+ "SSL_CERT_FILE",+ "SSL_CERT_DIR",+ "REQUESTS_CA_BUNDLE",+ "CURL_CA_BUNDLE",+ "HTTP_PROXY",+ "HTTPS_PROXY",+ "NO_PROXY",+ "http_proxy",+ "https_proxy",+ "no_proxy",+ "DOCKER_HOST",+ "DOCKER_CONTEXT",+ "DOCKER_CONFIG",+ "DOCKER_TLS_VERIFY",+ "DOCKER_CERT_PATH",+ "XDG_RUNTIME_DIR",+ "SYSTEMROOT",+ "SKILLEVALUATOR_RUNTIME_DIR",+ }+)+++def _model(value: str) -> str:+ if (+ not value.strip()+ or len(value) > 256+ or any(c.isspace() or unicodedata.category(c) in {"Cc", "Cf", "Cs"} for c in value)+ ):+ raise ValueError("Model configuration contains an unsupported value.")+ return value+++def _api_root(value: str) -> str:+ # Reuse the runtime's strict authority/path validation without Anthropic's+ # protocol-specific removal of the final /v1 segment.+ if len(value) > 4096:+ raise ValueError("Provider API root configuration is invalid.")+ try:+ _normalize_anthropic_base_url(value, variable="API root")+ except (ValueError, UnicodeError):+ raise ValueError("Provider API root configuration is invalid.") from None+ return value.rstrip("/")+++def required_credentials(child: dict[str, str], tier: int) -> frozenset[str]:+ """Credential variable names required by the selected tier, never values."""+ keys = {PROVIDER_KEYS[child["SKILL_EVAL_LLM_PROVIDER"]]}+ if tier == 2:+ embedding = child["SKILL_EVAL_EMBEDDING_PROVIDER"]+ keys.add("SKILL_EVAL_EMBEDDING_API_KEY" if embedding == "openai-compatible" else PROVIDER_KEYS[embedding])+ return frozenset(keys)+++def model_environment(env: dict[str, str], tier: int) -> dict[str, str]:+ """Forward selected provider settings, never ambient CI or vendor credentials."""+ if tier not in {1, 2, 3}:+ raise ValueError("Select a supported evaluation tier.")+ base_provider = env.get("SKILL_EVAL_PROVIDER") or "openai"+ provider = (env.get(f"SKILL_EVAL_TIER{tier}_PROVIDER") or base_provider) if tier != 2 else base_provider+ embedding = env.get("SKILL_EVAL_EMBEDDING_PROVIDER") or (+ "openai" if base_provider == "anthropic" else base_provider+ )+ if provider not in PROVIDER_KEYS or (tier == 2 and embedding not in {"openai", "nv_build", "openai-compatible"}):+ raise ValueError("Select supported chat and embedding providers.")+ child = {key: value for key, value in env.items() if key in SAFE_ENV}+ child.update(+ {+ "SKILL_EVAL_LLM_PROVIDER": provider,+ "PYTHON_DOTENV_DISABLED": "1",+ "PYTHONUNBUFFERED": "1",+ "NO_COLOR": "1",+ "SKILLEVALUATOR_TELEMETRY_DISABLED": "1",+ "SKILLEVALUATOR_HARBOR_VIEWER_UPLOAD": "false",+ }+ )+ selected_providers = {provider}+ if tier == 2:+ child["SKILL_EVAL_EMBEDDING_PROVIDER"] = embedding+ selected_providers.add(embedding)+ for selected in selected_providers - {"openai-compatible"}:+ key = PROVIDER_KEYS[selected]+ if env.get(key):+ child[key] = env[key]+ if provider == "openai-compatible" and env.get("SKILL_EVAL_LLM_API_KEY"):+ child["SKILL_EVAL_LLM_API_KEY"] = env["SKILL_EVAL_LLM_API_KEY"]+ same_provider = provider == base_provider+ model = env.get(f"SKILL_EVAL_TIER{tier}_MODEL") if tier != 2 else None+ # Tier 1 may opt into the provider default independently of Tier 2.+ tier1_default = tier == 1 and "SKILL_EVAL_TIER1_MODEL" in env+ model = model or (env.get("SKILL_EVAL_MODEL") if same_provider and not tier1_default else None)+ if model:+ child["SKILL_EVAL_LLM_MODEL"] = child["LLM_JUDGE_MODEL"] = _model(model)+ base_url = env.get(f"SKILL_EVAL_TIER{tier}_BASE_URL") if tier != 2 else None+ base_url = base_url or (env.get("SKILL_EVAL_BASE_URL") if same_provider else None)+ if base_url and provider != "nv_build":+ child["SKILL_EVAL_LLM_BASE_URL"] = _api_root(base_url)+ if tier == 2:+ if embedding == "openai-compatible":+ embedding_key = env.get("SKILL_EVAL_EMBEDDING_API_KEY") or env.get("SKILL_EVAL_LLM_API_KEY")+ if embedding_key:+ child["SKILL_EVAL_EMBEDDING_API_KEY"] = embedding_key+ embedding_url = env.get("SKILL_EVAL_EMBEDDING_BASE_URL") or env.get("SKILL_EVAL_BASE_URL")+ if embedding_url:+ child["SKILL_EVAL_EMBEDDING_BASE_URL"] = _api_root(embedding_url)+ elif embedding == "openai" and env.get("SKILL_EVAL_EMBEDDING_BASE_URL"):+ child["SKILL_EVAL_EMBEDDING_BASE_URL"] = _api_root(env["SKILL_EVAL_EMBEDDING_BASE_URL"])+ if env.get("SKILL_EVAL_EMBEDDING_MODEL"):+ child["SKILL_EVAL_EMBEDDING_MODEL"] = _model(env["SKILL_EVAL_EMBEDDING_MODEL"])+ # Validate through the native runtime with non-secret placeholders so absent+ # credentials remain a handled CI precondition rather than an exception.+ validation = dict(child)+ for key in CREDENTIAL_KEYS:+ validation.setdefault(key, "ci-validation-placeholder")+ try:+ resolve_llm_provider(validation)+ # Only Tier 2 executes embeddings. A chat-only job (for example the+ # Tier 1 image job, which receives no embedding settings) must not fail+ # on an embedding route it never uses.+ if tier == 2:+ resolve_embedding_provider(validation)+ except (ProviderConfigurationError, ValueError):+ raise ValueError("Selected provider configuration is incomplete or invalid.") from None+ # Only the selected tier's routes are validated or receive credentials.+ for key in CREDENTIAL_KEYS - required_credentials(child, tier):+ child.pop(key, None)+ return child+++def agent_model_overrides(env: dict[str, str]) -> tuple[str, ...]:+ """Parse bounded comma/newline native agent model choices without rewriting IDs."""+ raw = env.get("SKILL_EVAL_AGENT_MODELS", "")+ if not raw.strip():+ return ()+ error = "Native agent model configuration is invalid."+ if len(raw) > 4096 or any(unicodedata.category(c) in {"Cc", "Cf", "Cs"} and c != "\n" for c in raw):+ raise ValueError(error)+ from skillevaluator.tier3.commands import parse_agent_model_overrides++ entries = tuple(entry.strip() for entry in re.split(r"[,\n]", raw) if entry.strip())+ try:+ parsed = parse_agent_model_overrides(entries)+ if len(entries) > 3 or set(parsed) - {"claude-code", "codex", "opencode"}:+ raise ValueError(error)+ for models in parsed.values():+ for model in models:+ _model(model)+ except ValueError:+ raise ValueError(error) from None+ return entriesdiff --git a/ci/run_tier1_image.py b/ci/run_tier1_image.pynew file mode 100644index 00000000..e984dda6--- /dev/null+++ b/ci/run_tier1_image.py@@ -0,0 +1,219 @@+# SPDX-License-Identifier: Apache-2.0+# ruff: noqa: INP001, T201 -- trusted standalone CI launcher with fixed diagnostics.+"""Launch authorized LLM Tier 1 scans in the immutable complete scanner image.++Admission and protected-environment authorization belong to the calling job.+This helper checks the exact checkout before exposing the selected model key.+"""++from __future__ import annotations++import argparse+import os+import re+import subprocess+import sys+import tempfile+from pathlib import Path++# Isolated Python omits the script directory. Add only the pinned tools+# checkout's helpers, never the consumer working directory or PYTHONPATH.+if not __package__:+ sys.path.insert(0, str(Path(__file__).resolve().parent))++try:+ from model_config import PROVIDER_KEYS, model_environment+ from select_changed_skills import _git, _paths, setup_changed, skill_roots+except ModuleNotFoundError:+ from ci.model_config import PROVIDER_KEYS, model_environment+ from ci.select_changed_skills import _git, _paths, setup_changed, skill_roots++IMAGE = re.compile(r"ghcr\.io/nvidia/skillevaluator-tier1@sha256:[0-9a-f]{64}")+SHA = re.compile(r"(?:[0-9a-f]{40}|[0-9a-f]{64})")+CONTEXT = frozenset(+ {+ "DIFF_BASE_SHA",+ "DIFF_HEAD_SHA",+ "REPORT_COMMIT",+ "REPORT_RUN_URL",+ "REPORT_URL",+ "REPORT_BASE_URL",+ "CALLER_WORKFLOW_SHA",+ "GITHUB_ACTIONS",+ }+)+# Transport settings are only for Docker itself; no ambient credentials or+# user Docker configuration are inherited. Model keys never reach the pull.+HOST_ENV = frozenset({"PATH", "LANG", "LC_ALL", "LC_CTYPE", "SYSTEMROOT"})+++def _paths_safe(workspace: Path, reports: Path) -> tuple[Path, Path]:+ for path in (workspace, reports):+ if any(ord(c) < 32 or ord(c) == 127 or c == "," for c in str(path)):+ raise ValueError+ if any(parent.is_symlink() for parent in (path, *path.parents)):+ raise ValueError+ workspace = workspace.resolve(strict=True)+ reports = reports.resolve()+ if not workspace.is_dir() or reports.is_relative_to(workspace) or workspace.is_relative_to(reports):+ raise ValueError+ if reports.exists() and not reports.is_dir():+ raise ValueError+ return workspace, reports+++def _environment(workspace: Path, image: str, source: dict[str, str]) -> dict[str, str]:+ head = source.get("REPORT_COMMIT") or source.get("DIFF_HEAD_SHA", "")+ if not SHA.fullmatch(head):+ raise ValueError+ if any(value and value != head for value in (source.get("REPORT_COMMIT"), source.get("DIFF_HEAD_SHA"))):+ raise ValueError+ top = _git(workspace, "rev-parse", "--show-toplevel").decode().strip()+ if Path(top).resolve(strict=True) != workspace or _git(workspace, "rev-parse", "HEAD").decode().strip() != head:+ raise ValueError+ roots = source.get("SKILL_EVAL_PATHS", "skills")+ configured = skill_roots(workspace, roots)+ if _git(+ workspace, "status", "--porcelain=v1", "-z", "--untracked-files=all", "--ignored=matching", "--", *configured+ ):+ raise ValueError+ mode = source.get("SKILL_EVAL_SCAN_MODE", "auto")+ if mode not in {"auto", "all"}:+ raise ValueError+ pull_request = (+ source.get("GITHUB_EVENT_NAME") in {"pull_request", "pull_request_target"}+ or source.get("CI_PIPELINE_SOURCE") == "merge_request_event"+ or bool(source.get("DIFF_BASE_SHA"))+ )+ mode = "changed" if mode == "auto" and pull_request else "all"+ if mode == "changed":+ base = source.get("DIFF_BASE_SHA", "")+ if not SHA.fullmatch(base):+ raise ValueError+ changed = _paths(_git(workspace, "diff", "--name-only", "-z", "--no-renames", f"{base}...{head}", "--"))+ if setup_changed(changed):+ mode = "all"+ requested_provider = source.get("SKILL_EVAL_TIER1_PROVIDER") or source.get("SKILL_EVAL_PROVIDER") or "openai"+ if requested_provider == "openai-compatible":+ raise ValueError("gateway")+ selected = model_environment(source, 1)+ provider = selected["SKILL_EVAL_LLM_PROVIDER"]+ if provider not in {"openai", "anthropic", "nv_build"}:+ raise ValueError("gateway")+ if selected.get("SKILL_EVAL_LLM_BASE_URL") or source.get("SKILL_EVAL_TIER1_BASE_URL"):+ raise ValueError("gateway")+ key = selected.get(PROVIDER_KEYS[provider], "")+ if not key.strip():+ raise ValueError("key")+ # The enriched evidence replaces the keyless Tier 1 gate, so it must apply+ # the same reviewed baselines. The image validates the policy commit's+ # manifest; an inherited POLICY_SOURCE_SHA is ignored unless opted in.+ baselines = source.get("SECURITY_BASELINES", "false")+ if baselines not in {"true", "false"}:+ raise ValueError+ policy = source.get("POLICY_SOURCE_SHA", "") if baselines == "true" else ""+ if baselines == "true" and not SHA.fullmatch(policy):+ raise ValueError+ child = {name: source[name] for name in CONTEXT if name in source}+ child["SECURITY_BASELINES"] = baselines+ if policy:+ child["POLICY_SOURCE_SHA"] = policy+ child.update(+ REPORT_COMMIT=head,+ DIFF_HEAD_SHA=head,+ REPORT_IMAGE=image,+ SKILL_PATHS=roots,+ SCAN_MODE=mode,+ MIN_SCORE=source.get("SKILL_EVAL_MIN_SCORE", "70"),+ SCAN_WORKERS=source.get("SKILL_EVAL_SCAN_WORKERS", "4"),+ LLM_ENABLED="true",+ LLM_PROVIDER=provider,+ LLM_MODEL=selected.get("SKILL_EVAL_LLM_MODEL", ""),+ LLM_API_KEY=key,+ )+ return child+++def main(argv: list[str] | None = None) -> int:+ """Run the immutable image or its installed entrypoint; never execute candidate code."""+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--workspace", required=True, type=Path)+ parser.add_argument("--reports", required=True, type=Path)+ parser.add_argument("--image", required=True)+ parser.add_argument("--in-image", action="store_true")+ args = parser.parse_args(argv)+ try:+ if not IMAGE.fullmatch(args.image):+ raise ValueError+ workspace, reports = _paths_safe(args.workspace, args.reports)+ source = dict(os.environ)+ child = _environment(workspace, args.image, source)+ reports.mkdir(parents=True, exist_ok=True)+ host = {name: value for name, value in source.items() if name in HOST_ENV}+ host.setdefault("PATH", os.defpath)+ if args.in_image:+ # Keep sibling trusted helper imports; ignore Python environment and+ # user site packages, and do not add the consumer cwd to sys.path.+ host["PATH"] = (+ "/opt/skillevaluator/.venv/bin:/opt/semgrep/bin:/opt/skillspector/bin:/usr/local/bin:/usr/bin:/bin"+ )+ return subprocess.run(+ [+ "/opt/skillevaluator/.venv/bin/python",+ "-E",+ "-s",+ "/opt/skillevaluator/ci/run_tier1.py",+ "--workspace",+ str(workspace),+ "--reports",+ str(reports),+ ],+ cwd="/opt/skillevaluator",+ env={**host, **child},+ check=False,+ ).returncode+ with tempfile.TemporaryDirectory(prefix="skillevaluator-anonymous-docker-") as docker_config:+ docker = ["docker", "--config", docker_config]+ pulled = subprocess.run([*docker, "pull", args.image], cwd=reports.parent, env=host, check=False)+ if pulled.returncode:+ return 1+ command = [+ *docker,+ "run",+ "--rm",+ "--user",+ f"{os.getuid()}:{os.getgid()}",+ "--read-only",+ "--tmpfs",+ "/tmp:rw,nosuid,noexec,size=1g",+ "--tmpfs",+ "/audit-tmp:rw,nosuid,noexec,mode=1777,size=1g",+ "--env",+ "TMPDIR=/audit-tmp",+ "--cap-drop",+ "ALL",+ "--security-opt",+ "no-new-privileges",+ "--mount",+ f"type=bind,src={workspace},dst=/workspace,readonly",+ "--mount",+ f"type=bind,src={reports},dst=/reports",+ ]+ for name in sorted(child):+ command.extend(["--env", name])+ command.append(args.image)+ return subprocess.run(command, cwd=reports.parent, env={**host, **child}, check=False).returncode+ except ValueError as error:+ message = {+ "gateway": "Tier 1 image supports openai, anthropic, and nv_build with their default endpoints only.",+ "key": "Tier 1 LLM evaluation requires the selected provider credential.",+ }.get(str(error), "Tier 1 image configuration or evaluated checkout is invalid.")+ print(message)+ return 1+ except Exception:+ print("Tier 1 image evaluation could not start or complete; no result is claimed.")+ return 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/ci/run_tiers.py b/ci/run_tiers.pyindex d8384a2d..8c9c7897 100644--- a/ci/run_tiers.py+++ b/ci/run_tiers.py@@ -35,6 +35,7 @@ from skillevaluator.utils.secret_redaction import Redactortry:from diagnostics import TierBudget, retain_diagnosticsfrom github_api import strict_json+ from model_config import CREDENTIAL_KEYS, agent_model_overrides, model_environment, required_credentialsfrom run_tier1 import discover_skillsfrom secret_redaction import collect_sensitive_valuesfrom select_changed_skills import (@@ -48,6 +49,7 @@ try:except ModuleNotFoundError:from ci.diagnostics import TierBudget, retain_diagnosticsfrom ci.github_api import strict_json+ from ci.model_config import CREDENTIAL_KEYS, agent_model_overrides, model_environment, required_credentialsfrom ci.run_tier1 import discover_skillsfrom ci.secret_redaction import collect_sensitive_valuesfrom ci.select_changed_skills import (@@ -61,31 +63,6 @@ except ModuleNotFoundError:SHA = re.compile(r"[0-9a-f]{40}")MAX_JSON_BYTES = 32 * 1024 * 1024-PROVIDER_KEYS = {"openai": "OPENAI_API_KEY", "anthropic": "ANTHROPIC_API_KEY", "nv_build": "NVIDIA_API_KEY"}-SAFE_ENV = {- "PATH",- "LANG",- "LC_ALL",- "LC_CTYPE",- "SSL_CERT_FILE",- "SSL_CERT_DIR",- "REQUESTS_CA_BUNDLE",- "CURL_CA_BUNDLE",- "HTTP_PROXY",- "HTTPS_PROXY",- "NO_PROXY",- "http_proxy",- "https_proxy",- "no_proxy",- "DOCKER_HOST",- "DOCKER_CONTEXT",- "DOCKER_CONFIG",- "DOCKER_TLS_VERIFY",- "DOCKER_CERT_PATH",- "XDG_RUNTIME_DIR",- "SYSTEMROOT",- "SKILLEVALUATOR_RUNTIME_DIR",-}SUCCESS = {"passed", "skipped"}# Worker diagnostics explain execution problems, not complete failed or neutral verdicts.EXECUTION_FAILURES = {"incomplete", "not_run"}@@ -111,39 +88,12 @@ def boolean(env: dict, key: str, default: bool = False) -> bool:return value == "true"-def child_environment(env: dict[str, str]) -> dict[str, str]:- """Forward explicit provider configuration, never CI or publisher tokens."""- child = {key: value for key, value in env.items() if key in SAFE_ENV}- provider = env.get("SKILL_EVAL_PROVIDER", "openai")- embedding = env.get("SKILL_EVAL_EMBEDDING_PROVIDER") or ("openai" if provider == "anthropic" else provider)- if provider not in PROVIDER_KEYS or embedding not in {"openai", "nv_build"}:- raise ConfigurationError("Select supported chat and embedding providers.")- for selected in {provider, embedding}:- key = PROVIDER_KEYS[selected]- if env.get(key):- child[key] = env[key]- child.update(- {- "SKILL_EVAL_LLM_PROVIDER": provider,- "SKILL_EVAL_EMBEDDING_PROVIDER": embedding,- "PYTHON_DOTENV_DISABLED": "1",- "PYTHONUNBUFFERED": "1",- "NO_COLOR": "1",- "SKILLEVALUATOR_TELEMETRY_DISABLED": "1",- "SKILLEVALUATOR_HARBOR_VIEWER_UPLOAD": "false",- }- )- for source, target in (- ("SKILL_EVAL_MODEL", "SKILL_EVAL_LLM_MODEL"),- ("SKILL_EVAL_MODEL", "LLM_JUDGE_MODEL"),- ("SKILL_EVAL_EMBEDDING_MODEL", "SKILL_EVAL_EMBEDDING_MODEL"),- ):- if env.get(source):- value = env[source]- if len(value) > 256 or any(ord(c) < 32 for c in value):- raise ConfigurationError("Model configuration contains an unsupported value.")- child[target] = value- return child+def child_environment(env: dict[str, str], tier: int = 2) -> dict[str, str]:+ """Forward explicit selected provider configuration without CI credentials."""+ try:+ return model_environment(env, tier)+ except ValueError as exc:+ raise ConfigurationError(str(exc)) from Nonedef select_skills(workspace: Path, env: dict) -> tuple[list[Path], dict]:@@ -290,6 +240,7 @@ def tier3_options(skill: Path, output: Path, env: dict):# Native resolution adds adapter namespaces and honors authored agent# overrides; a global CLI override would bypass that resolution.model=None,+ agent_model=agent_model_overrides(env),skip_baseline=False,skip_with_skill=False,max_cases=None,@@ -317,7 +268,7 @@ def native_tier3(skill: Path, output: Path, env: dict) -> int:)if result is None:reason = service.failure_reason(engine) or "Tier 3 did not retain a canonical live evaluation result."- secrets = {os.environ[key] for key in PROVIDER_KEYS.values() if os.environ.get(key)}+ secrets = {os.environ[key] for key in CREDENTIAL_KEYS if os.environ.get(key)}result = advisory_skip_result(Redactor(secrets).text(reason)[:2000], skill_name=skill.name)result.mark_scan_incomplete("Tier 3 execution")result.metadata["gating"] = {"tier": 3, "blocking": False}@@ -484,11 +435,9 @@ def evaluate(tier: int, workspace: Path, reports: Path, env: dict[str, str]) ->row["reason"] = "Use native per-skill evals directories; central dataset mappings require explicit conversion."retain()return int(required)- child = child_environment(env)- provider_tokens = {child[key] for key in PROVIDER_KEYS.values() if child.get(key)}- needed = {PROVIDER_KEYS[child["SKILL_EVAL_LLM_PROVIDER"]]}- if tier == 2:- needed.add(PROVIDER_KEYS[child["SKILL_EVAL_EMBEDDING_PROVIDER"]])+ child = child_environment(env, tier)+ provider_tokens = {child[key] for key in CREDENTIAL_KEYS if child.get(key)}+ needed = required_credentials(child, tier)if tier > 1 and not all(child.get(key) for key in needed):row["reason"] = "A required provider credential is missing; configure CI secrets before evaluation."retain()@@ -564,6 +513,8 @@ def evaluate(tier: int, workspace: Path, reports: Path, env: dict[str, str]) ->]if env.get("SKILL_EVAL_AGENTS"):args += ["--agents", env["SKILL_EVAL_AGENTS"]]+ for model in agent_model_overrides(env):+ args += ["--agent-model", model]command_log = scratch / "doctor.log"if run_command(args,@@ -580,6 +531,7 @@ def evaluate(tier: int, workspace: Path, reports: Path, env: dict[str, str]) ->config_keys = ("SKILL_EVAL_ENV_MODE","SKILL_EVAL_AGENTS",+ "SKILL_EVAL_AGENT_MODELS","SKILL_EVAL_MODEL","SKILL_EVAL_N_ATTEMPTS","SKILL_EVAL_N_CONCURRENT",@@ -788,6 +740,12 @@ def aggregate(reports: Path, tiers: tuple[int, ...], env: dict) -> int:}result["tiers"].append(row)result["overall_passed"] = all(not r["required"] or r["status"] in SUCCESS for r in result["tiers"])+ try:+ from benchmark_reports import write_benchmark_reports+ except ModuleNotFoundError:+ from ci.benchmark_reports import write_benchmark_reports+ result = validate_manifest(result)+ result["benchmarks"] = write_benchmark_reports(reports, result)write_reports(reports, validate_manifest(result))return int(not result["overall_passed"])diff --git a/ci/templates/all-tiers/README.md b/ci/templates/all-tiers/README.mdindex fd150f95..8b749d61 100644--- a/ci/templates/all-tiers/README.md+++ b/ci/templates/all-tiers/README.md@@ -131,6 +131,42 @@ NVIDIA Build uses OpenCode. CI installs Tier 2 or Tier 3 extras from the reviewetools commit. Tier 3 checks the selected environment with `doctor`; local modealso installs pinned native CLIs into an isolated runtime directory.+For a reviewed candidate with `ci-model-routing-v1`, independently configure+Tier 1 LLM checks and Tier 3 gateway agents. These options run locally during+setup; CI later reads the committed configuration:++```bash+skillevaluator ci init --tiers 1,2,3 --mode preview --no-input \+ --paths skills --provider nv_build --embedding-provider nv_build \+ --model "$DEDUP_MODEL" \+ --tier1-llm --tier1-provider nv_build --tier1-model "$SECURITY_MODEL" \+ --tier3-provider openai-compatible --tier3-base-url "$GATEWAY_API_ROOT" \+ --tier3-model "$JUDGE_MODEL" --gateway-secret MY_INFERENCE_KEY \+ --agents claude-code,codex \+ --agent-model "claude-code=$CLAUDE_MODEL" --agent-model "codex=$CODEX_MODEL"+```++Set those model variables to exact accessible catalog IDs and the gateway+variable to its API root, commonly ending in `/v1`. `MY_INFERENCE_KEY` is the+name of a CI secret, not its value. Configure that repository Actions secret+and the Build secret `NVIDIA_API_KEY`; never pass a key value to `ci init`.+Use `--mode pr` after reviewing the preview. `--base-url` and+`--embedding-base-url` configure shared chat and embedding endpoints when+needed. Tier 1's immutable image uses native provider endpoints, so choose a+supported `--tier1-provider` when other tiers use a custom gateway.++The separate `--tier3-model` selects judging. Repeatable `--agent-model`+selects each native agent's model without replacing it with the judge's model.+`--tier1-model` also reaches SkillSpector; an empty value keeps the image's+provider defaults. Confirm that the pinned image supports the selected model.++Every combined report retains benchmark cards. On GitHub, add+`--benchmark-pr` with a `ci-benchmark-pr-v1` candidate to propose eligible cards+beside their skills through a dedicated update PR after default-branch runs.+The setup still contains two entry files. GitLab retains cards in its aggregate+artifact; automated benchmark-update MRs are not provided by this option.+Older descriptors reject these new options before writing unsupported CI files.+`--timeout-minutes` sets the native job duration (10 to 360, 300 by default).The evaluator's runtime budget ends 20 minutes, or a quarter of a shorterduration, earlier so setup and retained evidence fit. If setup outlasts that@@ -146,6 +182,11 @@ certificates. Local mode needs a compatible native runner with Node/npm;the generated GitLab local configuration removes the Docker service. Cloudsandbox backends are outside this onboarding path.+`--runner` selects the native Tier 2/3 runner. Static and LLM-enriched Tier 1+keep their separate image-capable runner: GitHub uses `ubuntu-24.04`, and+GitLab uses an untagged image runner. Choosing a local Tier 3 runner therefore+does not add a Docker prerequisite to that native runner.+Merge both generated files onto the default branch **before opening the demo**.The first setup PR/MR can show evaluation checks, but automatic comments needthe trusted feedback entrypoint to exist on the default branch. GitLab also@@ -153,9 +194,13 @@ needs a protected default branch and a project access token with `api` scopeand the Maintainer role, stored as a scoped, protected`SKILLEVALUATOR_GITLAB_TOKEN` limited to the `skillevaluator-feedback`environment. GitLab before 18.4 also needs a separate project Reporter/read_api-`SKILLEVALUATOR_GITLAB_READ_TOKEN`, scoped to the protected execution environment-(`skillevaluator` by default). The read credential is removed before provider work.-Newer servers use `CI_JOB_TOKEN` by default. Online init/status report the server+`SKILLEVALUATOR_GITLAB_READ_TOKEN` for current-MR admission, scoped to the protected+execution environment (`skillevaluator` by default). The same read token is needed+on any GitLab version when the current protected default-branch API check rejects+`CI_JOB_TOKEN`, for example with HTTP 403. Configure or verify the read token's+project access rather than using the feedback publisher token. The read credential+is removed before provider work. Newer servers use `CI_JOB_TOKEN` by default where+the endpoint permits it. Online init/status report the serverversion prerequisite; offline preview/save leave admission readiness unverified.The MR jobs receive no comment token. GitLab's feedback request uses itsshort-lived job token; the initiating user needs permission to create a pipeline@@ -221,15 +266,23 @@ publisher at `.github/workflows/feedback-all-tiers.yml`. The CLI selects thisalternate filename when the conventional feedback file already defines areusable workflow, and `ci status --tiers 1,2,3` recognizes it.-The repository callers pin a reviewed `main` commit for the evaluator workflows-and tools, and the verified released Tier 1 image. They use Docker, NVIDIA Build,-one attempt and one concurrent task, and the committed native datasets. The-caller's explicit `model` input selects chat, judging and the default live-agent-model together; embeddings use the separate `embedding-model` input. Add-`NVIDIA_API_KEY` as a repository Actions secret before expecting provider-backed-results. Without it, Tier 2 and Tier 3-remain incomplete/advisory; a passing Tier 1 gate is not an all-tier evaluation-pass. Forks retain keyless Tier 1 checks. On PRs, ordinary software changes+The repository callers pin reviewed evaluator workflows and tools, and the+verified released Tier 1 image. They use Docker, one attempt and one concurrent+task, and the committed native datasets. Tier 1 enables `--llm` and SkillSpector+with its own NVIDIA Build model. Tier 2 uses a separate NVIDIA Build chat model+and embeddings. Tier 3 selects both Codex and Claude Code through a configured+gateway, with explicit agent models and a separate judge model.++For this repository's profile, `NVIDIA_API_KEY` is a repository Actions+**secret**. Set the repository Actions **variable** `SKILL_EVAL_TIER3_BASE_URL`+to the gateway's versioned API root, and `SKILL_EVAL_GATEWAY_SECRET` to the name+of the existing repository Actions secret holding the gateway key. The selector+contains only a secret name, never the key itself. The caller resolves+`secrets[vars.SKILL_EVAL_GATEWAY_SECRET]` into the reusable workflow's generic+`LLM_API_KEY`; other repositories can select their own gateway and secret names+during local onboarding. Missing+prerequisites remain visible in the reports. A passing Tier 1 gate is not an+all-tier evaluation pass. Forks retain keyless Tier 1 checks. On PRs, ordinary software changesselect no skills, skill changes select the affected skills, and CI configurationchanges select the collection. Pushes to `main` and manual runs scan the collection.@@ -291,7 +344,9 @@ preferring one whose marker verifies, and leaves any other report commentsuntouched. Report comments with unverifiable markers are never deferred to.Merge this feedback file onto the default branch before expecting the firstautomatic comment. Changes to the caller must refresh its approved Git blob in-`trusted-caller-blobs`.+`trusted-caller-blobs` in both trusted jobs. An upgrade that changes the approved+caller or producer revision starts automatic feedback only after the updated+listener reaches the default branch; earlier candidate runs retain their artifacts.A missing provider key, unavailable runtime, or missing committed native datasetmust remain visible as an incomplete or needs-action result. Local `ci init`,@@ -299,6 +354,42 @@ must remain visible as an incomplete or needs-action result. Local `ci init`,is not evidence that the three tiers passed. Optional Pages hosting remains aseparate opt-in; artifact feedback works without it.+### LLM security, gateway agents and benchmark cards++A candidate descriptor advertising `ci-model-routing-v1` supports+`--tier1-llm`, independent Tier 1 provider/model inputs, and separate Tier 3+gateway and judge settings. The protected Tier 1 job reuses the hardened image+with LLM security, SkillSpector semantic findings, verification and rubric+checks. An unconditional keyless baseline remains available for forks and+denied admission. For an authorized LLM run, missing or failed enriched evidence+fails the required Tier 1 gate; it is never replaced with a passing static scan.+The image supports OpenAI, Anthropic and NVIDIA Build at their native endpoints.++Tier 2 chat/embeddings can use one provider while Tier 3 uses an+`openai-compatible` gateway. Set `tier3-provider`, `tier3-base-url` and+`tier3-model` for the judge, then `agents` and `agent-models` for the actual+Claude Code/Codex models. A gateway must serve Chat Completions for judging,+Responses for Codex, and Anthropic Messages for Claude Code, including tool+calls. A model catalog listing alone does not verify these APIs or your key's+model access. The generic `LLM_API_KEY` reusable-workflow secret maps to the+repository secret selected by local `ci init --gateway-secret`.++The combined artifact includes `benchmarks/skill-NNN/BENCHMARK.md` and its+combined native JSON. The index links to both. Failed or incomplete evidence+retains a card with its actual publication status. Publication still requires+complete required-tier evidence even when Tier 2/3 are advisory CI jobs.+Older Tier 1 images that omit required-check scope cannot certify a passing+card; use a compatible image rather than inferring coverage from a green gate.++With capability `ci-benchmark-pr-v1`, `ci init --benchmark-pr` adds an optional+job to the same feedback file. After a verified current default-branch run, a+separate trusted publisher regenerates eligible cards from native JSON and+opens a benchmark-update PR. It never changes the evaluated source PR or pushes+to the default branch. This job needs `contents: write` and+`pull-requests: write`; the existing comment job keeps read-only contents+permission. GitHub must allow Actions to create PRs. If that setting is+disabled, the job reports its prepared branch and a manual PR action.+## GitLab checks and feedbackThis path requires **GitLab 17.0 or later** for validated include inputs.@@ -378,6 +469,29 @@ retains `skill-evaluator-results/ci-results.json`, `index.html`, `summary.md`,and each tier's native reports for 14 days. Reports stay behind your normalGitLab artifact access controls.+A reviewed `ci-model-routing-v1` candidate can opt into+`SKILL_EVAL_TIER1_LLM: "true"`, with independent+`SKILL_EVAL_TIER1_PROVIDER` and `SKILL_EVAL_TIER1_MODEL` settings. The additional+Tier 1 image job runs in the protected execution environment, rechecks current+MR/default-branch eligibility, and uses no Docker-in-Docker service. Its+enriched evidence determines the Tier 1 gate for an eligible run; missing+evidence cannot fall back to a passing static baseline. Default-branch enrichment+is limited to `push` and `web` pipelines, matching provider admission. Scheduled,+API, trigger and downstream default-branch pipelines retain the keyless Tier 1+baseline, as do forks.++Use `SKILL_EVAL_TIER3_PROVIDER`, `SKILL_EVAL_TIER3_BASE_URL` and+`SKILL_EVAL_TIER3_MODEL` for a separate live-agent/judge route, and+`SKILL_EVAL_AGENT_MODELS` for newline-separated `AGENT=MODEL` selections.+Generic gateways use environment-scoped `SKILL_EVAL_LLM_API_KEY`; chat and+embedding settings can remain independent. These variables are also generated+by the [local onboarding options](#opt-in-to-three-tier-ci).++The aggregate retains source-bound `BENCHMARK.md` cards and combined JSON under+`benchmarks/skill-NNN/`. Publication requirements remain separate from advisory+CI policy. GitLab currently publishes these cards as authenticated artifacts;+the optional `--benchmark-pr` source-update feature is GitHub-only.+Trusted MR feedback uses one summary table with a row per skill. Each row hasone-line results for Static and Security Validation, Deduplication, and LiveAgent Evaluation, with status, recorded issue count and the main finding or@@ -426,8 +540,14 @@ uses this read credential once, refuses HTTP redirects, and the job removes itbefore runtime installation, doctor or provider execution.GitLab 18.4 and later support the default short-lived `CI_JOB_TOKEN` path for-this MR endpoint; the separate read token remains optional. `ci init --mode pr`-and `ci status` check the server version through the local authenticated API.+this MR endpoint. Admission also verifies the current protected default-branch+head through the repository branches API. If a job token cannot read either+endpoint, such as an HTTP 403 response, configure or verify the same separate+`SKILLEVALUATOR_GITLAB_READ_TOKEN` with project Reporter/read_api access. This+default-branch prerequisite can apply on newer GitLab versions too; use the+execution environment's read credential, never the feedback publisher token.+`ci init --mode pr` and `ci status` check the server version through the local+authenticated API.Offline preview/save keep the version unverified. These local commands reportthe prerequisite and do not claim to validate a stored CI secret's privileges.The setup still consists of two consumer files.@@ -529,6 +649,13 @@ names it `skill-evaluator-results-attempt-N`; GitLab retains the aggregate job'sactual artifact download for that run. Authentication and artifact expiry stillapply; this link does not imply publicly hosted HTML.+Current candidate aggregates also retain `benchmarks/skill-NNN/BENCHMARK.md`+and `benchmarks/skill-NNN/skillevaluator.json` for each selected skill. The+index links these source-bound cards and combined JSON alongside native tier+reports. Cards retain failed and incomplete publication states. A passing+Tier 1 CI gate does not certify benchmark eligibility; inspect the combined+JSON's `publication.status` and `publication.eligible`.+The PR or MR comment presents one summary table with a row for each skill.Each row shows a one-line status, issue count and the most important availablefinding or blocker for **Tier 1 — Static and Security Validation**,diff --git a/ci/templates/all-tiers/feedback-all-tiers.yml b/ci/templates/all-tiers/feedback-all-tiers.ymlindex 4a3e6c64..cec90f15 100644--- a/ci/templates/all-tiers/feedback-all-tiers.yml+++ b/ci/templates/all-tiers/feedback-all-tiers.yml@@ -17,3 +17,16 @@ jobs:tools-ref: RELEASE_WORKFLOW_SHAtrusted-workflow-ref: NVIDIA/SkillEvaluator/.github/workflows/evaluate-all-tiers.yml@RELEASE_WORKFLOW_SHAtrusted-caller-blobs: REVIEWED_CALLER_GIT_BLOB+ # Optional: generated by ci init --benchmark-pr on GitHub only.+ # Requires immutable pins declaring ci-benchmark-pr-v1.+ # benchmarks:+ # uses: NVIDIA/SkillEvaluator/.github/workflows/publish-benchmarks.yml@RELEASE_WORKFLOW_SHA+ # permissions:+ # contents: write+ # actions: read+ # pull-requests: write+ # with:+ # tools-repository: NVIDIA/SkillEvaluator+ # tools-ref: RELEASE_WORKFLOW_SHA+ # trusted-workflow-ref: NVIDIA/SkillEvaluator/.github/workflows/evaluate-all-tiers.yml@RELEASE_WORKFLOW_SHA+ # trusted-caller-blobs: REVIEWED_CALLER_GIT_BLOBdiff --git a/ci/templates/all-tiers/gitlab-all-tiers.yml b/ci/templates/all-tiers/gitlab-all-tiers.ymlindex 07e8089d..a92ae692 100644--- a/ci/templates/all-tiers/gitlab-all-tiers.yml+++ b/ci/templates/all-tiers/gitlab-all-tiers.yml@@ -21,6 +21,22 @@ variables:SKILL_EVAL_TIERS: '1,2,3'SKILL_EVAL_ENV_MODE: dockerSKILL_EVAL_PROVIDER: openai+ # Optional; requires immutable pins declaring ci-model-routing-v1.+ # SKILL_EVAL_TIER1_LLM: "true"+ # SKILL_EVAL_TIER1_PROVIDER: openai+ # SKILL_EVAL_TIER1_MODEL: YOUR_TIER1_MODEL+ # SKILL_EVAL_BASE_URL: https://gateway.example/v1+ # SKILL_EVAL_EMBEDDING_PROVIDER: openai-compatible+ # SKILL_EVAL_EMBEDDING_BASE_URL: https://embedding.example/v1+ # SKILL_EVAL_TIER3_PROVIDER: openai-compatible+ # SKILL_EVAL_TIER3_MODEL: YOUR_JUDGE_MODEL+ # SKILL_EVAL_TIER3_BASE_URL: https://gateway.example/v1+ # SKILL_EVAL_AGENT_MODELS: |+ # claude-code=YOUR_CLAUDE_AGENT_MODEL+ # codex=YOUR_CODEX_AGENT_MODEL+ # Set SKILL_EVAL_LLM_API_KEY and SKILL_EVAL_EMBEDDING_API_KEY in CI settings.+ # Only a generic chat route with a custom secret needs an alias here:+ # SKILL_EVAL_LLM_API_KEY: "$YOUR_GATEWAY_SECRET_NAME"SKILL_EVAL_RUNNER: dockerSKILL_EVAL_ENVIRONMENT: skillevaluator# Job minutes minus min(20, minutes / 4): leave time to retain evidence.diff --git a/ci/templates/all-tiers/skill-checks-all-tiers.yml b/ci/templates/all-tiers/skill-checks-all-tiers.ymlindex 743611e0..05a4459c 100644--- a/ci/templates/all-tiers/skill-checks-all-tiers.yml+++ b/ci/templates/all-tiers/skill-checks-all-tiers.yml@@ -1,5 +1,6 @@# SPDX-License-Identifier: Apache-2.0# Opt-in candidate template. Use a capability-bearing release, replacing pins.+# Model routing options require a release declaring ci-model-routing-v1.# Tier 1 is required; Tier 2 and Tier 3 are advisory.name: Skill checks (all tiers)on:@@ -26,9 +27,26 @@ jobs:scan-mode: autoenv-mode: dockerprovider: openai+ # Optional with ci-model-routing-v1; omit unused inputs for older pins.+ # tier1-llm: true+ # tier1-provider: openai+ # tier1-model: YOUR_TIER1_MODEL+ # base-url: https://gateway.example/v1+ # embedding-provider: openai-compatible+ # embedding-base-url: https://embedding.example/v1+ # tier3-provider: openai-compatible+ # tier3-model: YOUR_JUDGE_MODEL+ # tier3-base-url: https://gateway.example/v1+ # agent-models: |+ # claude-code=YOUR_CLAUDE_AGENT_MODEL+ # codex=YOUR_CODEX_AGENT_MODELrunner: ubuntu-24.04environment: skillevaluatorsecrets:OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}NVIDIA_API_KEY: ${{ secrets.NVIDIA_API_KEY }}+ # Add only when provider or tier3-provider is openai-compatible:+ # LLM_API_KEY: ${{ secrets.SKILL_EVAL_LLM_API_KEY }}+ # Add only when embedding-provider is openai-compatible:+ # EMBEDDING_API_KEY: ${{ secrets.SKILL_EVAL_EMBEDDING_API_KEY }}diff --git a/ci/tier_manifest.py b/ci/tier_manifest.pyindex 21824493..55a6c538 100644--- a/ci/tier_manifest.py+++ b/ci/tier_manifest.py@@ -111,6 +111,7 @@ def validate_manifest(payload: dict) -> dict:"Invalid expected_tiers",)seen = set()+ known_skills = set()for record in tiers:_require(isinstance(record, dict), "Tier must be an object")tier = record.get("tier")@@ -136,12 +137,18 @@ def validate_manifest(payload: dict) -> dict:_require(isinstance(record["metrics"], dict), "Invalid tier metrics")skills = record.get("skills")_require(isinstance(skills, list) and len(skills) <= 1000, "Invalid skills")+ if "selected" in record:+ selected = record["selected"]+ _require(isinstance(selected, list) and len(selected) <= 1000, "Invalid selected skill paths")+ for selected_path in selected:+ known_skills.add(_path(selected_path, "selected skill path", skill=True))paths = set()for skill in skills:_require(isinstance(skill, dict), "Skill must be an object")path = _path(skill.get("path"), "skill path", skill=True)_require(path not in paths, "Duplicate skill path")paths.add(path)+ known_skills.add(path)_require(isinstance(skill.get("status"), str) and skill["status"] in _STATUSES, "Invalid skill status")for key in ("report_json", "report_html"):_require(key in skill, f"Missing {key}")@@ -158,6 +165,28 @@ def validate_manifest(payload: dict) -> dict:not record.get("error") and not any(skill.get("error") for skill in skills),"Passed tier contains execution errors",)+ if "benchmarks" in payload:+ cards = payload["benchmarks"]+ _require(isinstance(cards, list) and len(cards) <= 100, "Invalid benchmark cards")+ card_skills, card_paths = set(), set()+ for card in cards:+ _require(isinstance(card, dict), "Invalid benchmark card")+ skill = _path(card.get("path"), "benchmark skill path", skill=True)+ _require(skill in known_skills and skill not in card_skills, "Foreign or duplicate benchmark skill")+ card_skills.add(skill)+ combined = _path(card.get("combined_json"), "combined report path")+ match = re.fullmatch(r"(benchmarks/skill-[0-9]{3})/skillevaluator\.json", combined)+ _require(match is not None and combined not in card_paths, "Invalid or duplicate combined report path")+ card_paths.add(combined)+ _require(card.get("benchmark_md") == match[1] + "/BENCHMARK.md", "Invalid benchmark Markdown path")+ _require(+ card.get("publication_status") in {"pass", "fail", "neutral", "incomplete"},+ "Invalid publication status",+ )+ _require(type(card.get("eligible")) is bool, "Invalid publication eligibility")+ _require(+ not card["eligible"] or card["publication_status"] == "pass", "Contradictory publication eligibility"+ )required = [record for record in tiers if record["required"]]missing = set(expected) & {1} - seen@@ -376,6 +405,24 @@ def render_markdown(payload: dict, report_url: str = "") -> str:lines.append(f"| {_md(skill['path'])} | {skill['status']} | {' · '.join(links) or 'Unavailable'} | {_md(detail) or '—'} |")+ if payload.get("benchmarks"):+ lines.extend(+ [+ "",+ "## Benchmark cards",+ "",+ "Publication eligibility is separate from the required CI gate.",+ "",+ "| Skill | Publication | Reports |",+ "| --- | --- | --- |",+ ]+ )+ for card in payload["benchmarks"]:+ links = " · ".join(+ f"[{label}]({base + quote(card[field], safe='/-._~')})"+ for field, label in (("benchmark_md", "BENCHMARK.md"), ("combined_json", "Combined JSON"))+ )+ lines.append(f"| {_md(card['path'])} | {card['publication_status']} | {links} |")lines.extend(["", f"Commit: `{payload['commit']}` · Environment: {payload['environment']}", ""])return "\n".join(lines)@@ -415,6 +462,21 @@ def _render_html(payload: dict) -> str:f"<tr><td>{h(skill['path'])}</td><td>{skill['status']}</td><td>{' · '.join(links) or 'Unavailable'}</td><td>{h(detail)}</td></tr>")lines.append("</tbody></table></div>")+ if payload.get("benchmarks"):+ lines.extend(+ [+ "<h2>Benchmark cards</h2>",+ "<p>Publication eligibility is separate from the required CI gate.</p>",+ '<div class="table"><table><thead><tr><th>Skill</th><th>Publication</th><th>Reports</th></tr></thead><tbody>',+ ]+ )+ for card in payload["benchmarks"]:+ links = " · ".join(+ f'<a href="{h(quote(card[field], safe="/-._~"), quote=True)}">{label}</a>'+ for field, label in (("benchmark_md", "BENCHMARK.md"), ("combined_json", "Combined JSON"))+ )+ lines.append(f"<tr><td>{h(card['path'])}</td><td>{card['publication_status']}</td><td>{links}</td></tr>")+ lines.append("</tbody></table></div>")lines.append(f'<p>Commit: <code>{payload["commit"]}</code> · Environment: {payload["environment"]}</p><p><a href="ci-results.json">Run manifest (JSON)</a> · <a href="summary.md">Markdown summary</a></p></body></html>')diff --git a/docs/benchmark-rollout.mdx b/docs/benchmark-rollout.mdxindex e5a0dada..b4c97775 100644--- a/docs/benchmark-rollout.mdx+++ b/docs/benchmark-rollout.mdx@@ -8,6 +8,29 @@ redesign, and publication gate is available. Existing `BENCHMARK.md` files aregenerated artifacts; merging the renderer does not rewrite cards alreadypublished in skill repositories.+## Generate cards in repository CI++The candidate three-tier CI aggregate composes each skill's actual retained+Tier 1/2/3 results into `benchmarks/skill-NNN/skillevaluator.json` and+`benchmarks/skill-NNN/BENCHMARK.md`. Find both through the combined report's+index. Generation requires no model calls and never reads mutable skill files.+It preserves exact source, dataset, run and coverage identities; contradictory+or missing evidence produces an honest incomplete card.++Tier 2/3 advisory CI policy does not waive benchmark publication requirements.+Automation must use `publication.status` and `publication.eligible` in the+combined JSON. A passing required CI gate alone cannot approve publication.+In particular, older Tier 1 images that do not retain required-check scope+produce incomplete cards until a compatible image is selected.++On GitHub, local onboarding can opt into `--benchmark-pr` with a reviewed+`ci-benchmark-pr-v1` descriptor. A trusted default-branch publisher verifies the+producer, exact source head, current attempt and native JSON, regenerates+eligible cards, and opens a dedicated PR containing only `BENCHMARK.md`+updates. Source PRs and the default branch are never edited directly. Artifact+Markdown is never trusted as write-ready content. GitLab currently retains+cards in the aggregate artifact. See the [GitHub benchmark-card reference](https://github.com/NVIDIA/SkillEvaluator/blob/main/ci/templates/all-tiers/README.md#llm-security-gateway-agents-and-benchmark-cards).+## Before and afterThe legacy card led with dense tier output and mixed verdict evidence into thediff --git a/docs/environment-variables.mdx b/docs/environment-variables.mdxindex 4e8ee122..6557b275 100644--- a/docs/environment-variables.mdx+++ b/docs/environment-variables.mdx@@ -273,7 +273,7 @@ Keep credentials out of skill repositories and CI configuration files. Export pr| Variable | Purpose || --- | --- |-| `SKILLEVALUATOR_GITLAB_READ_TOKEN` | Optional project Reporter/read_api credential for current-MR admission; required on GitLab before 18.4, scoped to the execution environment and removed before provider subprocesses. |+| `SKILLEVALUATOR_GITLAB_READ_TOKEN` | Optional project Reporter/read_api credential for current-MR and default-branch admission; required on GitLab before 18.4, or when `CI_JOB_TOKEN` cannot read the default branch, scoped to the execution environment and removed before provider subprocesses. || `SKILLEVALUATOR_GITLAB_TOKEN` | Separate project-scoped publisher credential in the protected feedback environment; never used by evaluation jobs. |Local onboarding can use `SKILLEVALUATOR_GITLAB_TOKEN` or `GITLAB_TOKEN` in itsdiff --git a/docs/superpowers/plans/2026-11-10-three-tier-ci-benchmarks.md b/docs/superpowers/plans/2026-11-10-three-tier-ci-benchmarks.mdnew file mode 100644index 00000000..36715d53--- /dev/null+++ b/docs/superpowers/plans/2026-11-10-three-tier-ci-benchmarks.md@@ -0,0 +1,93 @@+# Three-tier CI gateways and benchmarks implementation plan++> **For agentic workers:** Use test-driven changes and independent review. Check off completed tasks; keep provider credentials out of reports and source control.++**Goal:** Provide thin consumer CI that runs LLM-enriched Tier 1, Tier 2 deduplication, paired Claude Code/Codex Tier 3 through a configurable gateway, and publishes source-bound benchmark cards alongside combined reports.++**Architecture:** Extend the shared orchestration and existing native reporting APIs. Keep native agent models separate from evaluator/judge models. Generate benchmark cards from retained typed evidence without model calls or executing consumer code in the publisher.++**Tech stack:** Python, GitHub Actions, GitLab CI, existing SkillEvaluator reporters and provenance validation.++**Spec:** User-approved three-tier onboarding plan in this chat, with the subsequent requirements for Tier 1 `--llm`, gateway-backed Claude/GPT agents, the reference pipeline's separate evaluation/report/publication stages, and `BENCHMARK.md` publication.++## Global constraints++- Only Tier 1 blocks CI. Tier 2/3 remain advisory in every report and adapter.+- Tier 3 supports Docker and local, with complete treatment/baseline coverage for every selected agent/case.+- Preserve two thin consumer entry files; no copied scripts, bundled wheels, or consumer-built images.+- Keep generic gateway settings in OSS; no internal endpoint, model entitlement, or credential defaults.+- Keep keyless scans for forks and unauthorized/stale commits. Authorize and recheck provider-backed work before exposing credentials.+- Retain reports for 14 days, including failed/incomplete evidence. Never derive publication eligibility from the advisory CI gate.+- Pin evaluator/runtime/workflow/tool revisions. Validate candidate orchestration separately from claims about released/latest-main runtime support.+- Never send a Slack message or manually rewrite a bot result comment.++## Review focus++- Missing or contradictory Tier 1 required-check declarations must survive JSON round trips and remain incomplete.+- Missing tier/agent/baseline evidence must never become a passing benchmark.+- Multiple skills and reordered tier rows must compose by exact skill identity, not ordinal.+- Generic gateway keys/base URLs must reach only the selected provider and never inherit CI feedback credentials.+- Benchmark publication must reject stale/fork/foreign evidence and must not cause an evaluated source PR to update itself in a loop.++### Task 1: Preserve publication evidence through retained JSON++Files: `src/skillevaluator/reporting/json_reporter.py`, `src/skillevaluator/reporting/retained.py`, reporting/publication regression tests.++- [x] Reproduce loss of `tier1_required_checks` and `tier1_unscanned_paths` through JSON -> retained results.+- [x] Preserve typed bounded string lists; reject malformed declarations.+- [x] Verify in-memory and retained publication outcomes agree for complete, omitted-check and unscanned-content cases.++### Task 2: Compose combined skill reports and benchmark cards++Files: new `ci/benchmark_reports.py`, new `tests/ci/test_benchmark_reports.py`; root integrates `ci/run_tiers.py` and retained index/feedback contracts.++Interface: `write_benchmark_reports(reports: Path, manifest: dict) -> list[dict]`; output rows identify exact skill path, combined JSON, and `BENCHMARK.md` paths.++- [x] Test real retained Tier 1/2/3 composition, reordered/multiple skills, missing tiers, source conflicts, and advisory failures.+- [x] Reuse `retained_results`, `JSONReporter` and `BenchmarkReporter`; never read skill source or call a model while reporting.+- [x] Preserve source/policy/run provenance. Keep required tiers publication-required regardless of CI gate policy.+- [x] Retain honest non-PASS cards for incomplete evidence, and expose cards beside the existing combined report.++### Task 3: Support configurable gateway routing and per-tier models++Files: new `ci/model_config.py`, `ci/run_tiers.py` environment plumbing, `ci/bootstrap_tiers.py`, dedicated model-config/bootstrap tests.++Interface: `model_environment(env: dict[str, str], tier: int) -> dict[str, str]` provides only safe runtime settings and selected credentials. `child_environment(env, tier=2)` retains its existing API with a compatible optional tier argument.++- [x] Add generic `openai-compatible` chat/embedding support and explicit API root/key settings.+- [x] Add Tier 3 provider/model/base-URL overrides while preserving existing provider defaults and separate native agent model defaults.+- [x] Use the same sanitized selection for doctor and evaluation; preserve selected embedding credentials independently.+- [x] Test absent keys, malformed URLs, provider isolation, empty/inherited overrides, and absence of CI/publisher credentials.++### Task 4: Wire shared workflows, onboarding and Tier 1 LLM++Files: shared GitHub/GitLab workflows, CLI/template/descriptor helpers, workflow/onboarding tests.++- [x] Expose opt-in Tier 1 LLM and generic gateway/per-tier inputs without invalidating old pinned callers.+- [x] Reuse the hardened Tier 1 image for LLM/SkillSpector execution with protected admission and a current-head recheck; retain keyless baseline for denied admission.+- [x] Keep native Tier 2/3 independent and advisory, preserve failure diagnostics and source-attempt reuse.+- [x] Integrate benchmark generation in credential-free aggregation and trusted feedback links.+- [x] Implement the chosen benchmark publication surface; only a trusted publisher may propose source-file updates from validated evidence.++### Task 5: Documentation, review and live validation++Files: existing onboarding, GitHub/GitLab, reports and benchmark guides; changelog.++- [x] Explain local setup -> prerequisites -> merge setup -> test PR -> reports/cards, including separate chat/judge/agent settings and gateway APIs.+- [x] Run focused tests, Ruff, formatting, benchmark lints and Fern checks.+- [x] Review each task and the final diff; fix findings before opening the implementation PR.+- [ ] Exercise candidate configuration with real provider credentials in dedicated fixtures, verify native completion and exact model routing, and report any remaining release/runtime dependency honestly.++## Handoff status++Implementation and local verification are complete. The repository callers pin+the reviewed feature-source commit and retain the released Tier 1 image. Both+feedback jobs approve the exact committed caller; API-created setup PRs also bind+both jobs to the uploaded bytes when local Git filters differ.++Live gateway model access and complete paired Tier 3 execution remain pending.+The current released Tier 1 image predates required-check scope serialization;+its incomplete publication evidence must not produce an eligible benchmark card.+A compatible image release and a current default-branch run are required to+verify an actual benchmark-update PR. Automatic feedback for the new caller+requires the updated trusted listener on the default branch.diff --git a/src/skillevaluator/_ci_onboarding_all_tiers.py b/src/skillevaluator/_ci_onboarding_all_tiers.pyindex 957d78f0..01149402 100644--- a/src/skillevaluator/_ci_onboarding_all_tiers.py+++ b/src/skillevaluator/_ci_onboarding_all_tiers.py@@ -25,6 +25,19 @@ GL_FEEDBACK = ".gitlab/skill-feedback.yml"SETUP_BRANCH = "ci/skillevaluator-all-tiers-setup"DEMO_BRANCH = "ci/skillevaluator-all-tiers-test"SHA = re.compile(r"[0-9a-f]{40}")+MODEL_ROUTING_CAPABILITY = "ci-model-routing-v1"+BENCHMARK_PR_CAPABILITY = "ci-benchmark-pr-v1"+MODEL_ROUTING_OPTIONS = (+ "tier1_llm",+ "tier1_provider",+ "tier1_model",+ "base_url",+ "embedding_base_url",+ "tier3_provider",+ "tier3_model",+ "tier3_base_url",+ "agent_model",+)# Feedback pipelines run on the protected default branch; other root jobs must skip them.GL_FEEDBACK_GUARD = {"if": '$SKILL_EVAL_FEEDBACK == "true"', "when": "never"}GL_NOT_FEEDBACK = ".skill-evaluation-not-feedback"@@ -45,6 +58,7 @@ _GL_EVALUATOR_JOBS = {"skill-evaluation","skill-evaluation-native","skill-evaluation-native-tier2",+ "skill-evaluation-tier1-llm","skill-evaluation-aggregate","skill-evaluation-request-feedback","skill-evaluation-feedback",@@ -93,7 +107,14 @@ def validate_release(data: dict) -> dict:):raise git.SetupError("All-tier onboarding needs an explicit schema_version 2 CI release descriptor.")caps = data.get("capabilities")- if not isinstance(caps, list) or not caps or any(c not in {"all-tiers-github", "all-tiers-gitlab"} for c in caps):+ if (+ not isinstance(caps, list)+ or not caps+ or any(+ c not in {"all-tiers-github", "all-tiers-gitlab", MODEL_ROUTING_CAPABILITY, BENCHMARK_PR_CAPABILITY}+ for c in caps+ )+ ):raise git.SetupError("The all-tier release descriptor must declare supported capabilities.")for key in ("workflow_ref", "feedback_ref", "gitlab_ref", "tools_ref"):if not SHA.fullmatch(str(data.get(key, ""))):@@ -399,6 +420,17 @@ def render(wizard, repo, release, platform, branch, roots, options):"timeout-minutes": options["timeout_minutes"],"environment": options["environment"],}+ common.update(+ {+ key.replace("_", "-"): options[key]+ for key in MODEL_ROUTING_OPTIONS+ if key != "agent_model" and options.get(key)+ }+ )+ if options.get("agent_model"):+ common["agent-models"] = "\n".join(options["agent_model"])+ generic_chat = "openai-compatible" in {options["provider"], options.get("tier3_provider")}+ generic_embedding = options["embedding_provider"] == "openai-compatible"header = "# Generated by SkillEvaluator all-tier CI onboarding.\n"if platform == "github":feedback_path = _github_feedback_path(repo)@@ -423,6 +455,11 @@ def render(wizard, repo, release, platform, branch, roots, options):}},}+ secrets = scan["jobs"]["skills"]["secrets"]+ if generic_chat:+ secrets["LLM_API_KEY"] = "${{ secrets." + options.get("gateway_secret", "SKILL_EVAL_LLM_API_KEY") + " }}"+ if generic_embedding:+ secrets["EMBEDDING_API_KEY"] = "${{ secrets.SKILL_EVAL_EMBEDDING_API_KEY }}"scan_text = header + wizard.yaml_text(scan)feedback = {"name": "Skill feedback (all tiers)",@@ -440,6 +477,12 @@ def render(wizard, repo, release, platform, branch, roots, options):}},}+ if options.get("benchmark_pr"):+ feedback["jobs"]["benchmarks"] = {+ "uses": f"{release['repository']}/.github/workflows/publish-benchmarks.yml@{release['feedback_ref']}",+ "permissions": {"contents": "write", "actions": "read", "pull-requests": "write"},+ "with": dict(feedback["jobs"]["feedback"]["with"]),+ }return {SCAN: scan_text, feedback_path: header + wizard.yaml_text(feedback)}variables = {"SKILL_EVAL_" + key.upper().replace("-", "_"): str(value).lower() if isinstance(value, bool) else str(value)@@ -457,6 +500,8 @@ def render(wizard, repo, release, platform, branch, roots, options):"SKILL_EVAL_RUNNER": options["runner"],})+ if generic_chat and options.get("gateway_secret", "SKILL_EVAL_LLM_API_KEY") != "SKILL_EVAL_LLM_API_KEY":+ variables["SKILL_EVAL_LLM_API_KEY"] = "$" + options["gateway_secret"]upstream = f"https://raw.githubusercontent.com/{release['repository']}/{release['gitlab_ref']}/ci/gitlab/"scan = {"include": [@@ -599,6 +644,37 @@ def initialize(platform, origin, name = remote(repo, platform)if "all-tiers-" + platform not in release["capabilities"]:raise git.SetupError(f"The all-tier release does not declare {platform} support.")+ if options.get("benchmark_pr"):+ if platform != "github":+ raise git.SetupError(+ "benchmark-update PR publication currently requires GitHub; GitLab cards retained in reports."+ )+ if BENCHMARK_PR_CAPABILITY not in release["capabilities"]:+ raise git.SetupError(f"--benchmark-pr requires a release declaring {BENCHMARK_PR_CAPABILITY}.")+ secret = options.get("gateway_secret", "SKILL_EVAL_LLM_API_KEY")+ if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", secret) or secret.upper().startswith("GITHUB_"):+ raise git.SetupError(+ "--gateway-secret must name a valid CI secret (letters, digits, underscores; no GITHUB_ prefix)."+ )+ routing = (+ any(options.get(key) for key in MODEL_ROUTING_OPTIONS)+ or any(options.get(key) == "openai-compatible" for key in ("provider", "embedding_provider"))+ or secret != "SKILL_EVAL_LLM_API_KEY"+ )+ if routing and MODEL_ROUTING_CAPABILITY not in release["capabilities"]:+ raise git.SetupError(+ f"These options require a release declaring {MODEL_ROUTING_CAPABILITY}; old pinned workflows cannot accept them."+ )+ selected_agents = set()+ for entry in options.get("agent_model", ()):+ if not re.fullmatch(r"(?:claude-code|codex|opencode)=[^\s=,]+", entry) or len(entry) > 280:+ raise git.SetupError(+ "--agent-model requires a supported AGENT=MODEL without whitespace (claude-code, codex, opencode)."+ )+ agent = entry.split("=", 1)[0]+ if agent in selected_agents:+ raise git.SetupError(f"--agent-model: specify only one model for {agent}.")+ selected_agents.add(agent)branch = git.infer_branch(repo, default_branch)roots = git.discover(repo)for index, item in enumerate(roots, 1):@@ -696,7 +772,9 @@ def initialize(# Git API commits bypass local clean filters; approve the uploaded bytes.feedback_path = ALTERNATE_FEEDBACK if ALTERNATE_FEEDBACK in files else FEEDBACKfeedback = yaml.safe_load(files[feedback_path])- feedback["jobs"]["feedback"]["with"]["trusted-caller-blobs"] = wizard.blob_id(files[SCAN])+ caller_blob = wizard.blob_id(files[SCAN])+ for job in feedback["jobs"].values():+ job["with"]["trusted-caller-blobs"] = caller_blobfiles[feedback_path] = "# Generated by SkillEvaluator all-tier CI onboarding.\n" + wizard.yaml_text(feedback)diff --git a/src/skillevaluator/ci-release-all-tiers.json b/src/skillevaluator/ci-release-all-tiers.jsonindex 664155a7..c7d26ef7 100644--- a/src/skillevaluator/ci-release-all-tiers.json+++ b/src/skillevaluator/ci-release-all-tiers.json@@ -1,16 +1,18 @@{"repository": "NVIDIA/SkillEvaluator",- "workflow_ref": "157bab5730759cb46b40645beb1c65542fb21520",+ "workflow_ref": "e56ced7f72904e055b04a5024c688d7603d5b49a","publisher_ref": "8096c6966a498f35f6f7dc1a596d1cc4da85cf11","image": "ghcr.io/nvidia/skillevaluator-tier1@sha256:9d5483243918937be4f2178f74cf7c622a531dee41e3176906994d52fa14950a","schema_version": 2,"capabilities": ["all-tiers-github",- "all-tiers-gitlab"+ "all-tiers-gitlab",+ "ci-model-routing-v1",+ "ci-benchmark-pr-v1"],- "feedback_ref": "157bab5730759cb46b40645beb1c65542fb21520",- "gitlab_ref": "157bab5730759cb46b40645beb1c65542fb21520",- "tools_ref": "157bab5730759cb46b40645beb1c65542fb21520",+ "feedback_ref": "e56ced7f72904e055b04a5024c688d7603d5b49a",+ "gitlab_ref": "e56ced7f72904e055b04a5024c688d7603d5b49a",+ "tools_ref": "e56ced7f72904e055b04a5024c688d7603d5b49a","report_contract": "skillevaluator-ci-v1","evaluator_version": "0.8.0","runtime_lock_sha256": "4b22e964d4aa2e78c5a6a73fe2f1ee979e72090aac85b6558e91d885e72cd966"diff --git a/src/skillevaluator/ci_onboarding.py b/src/skillevaluator/ci_onboarding.pyindex f5112396..ab9c9174 100644--- a/src/skillevaluator/ci_onboarding.py+++ b/src/skillevaluator/ci_onboarding.py@@ -859,6 +859,17 @@ ALL_TIER_ONLY_OPTIONS = ("n_concurrent","timeout_minutes","environment",+ "tier1_llm",+ "tier1_provider",+ "tier1_model",+ "base_url",+ "embedding_base_url",+ "tier3_provider",+ "tier3_model",+ "tier3_base_url",+ "agent_model",+ "gateway_secret",+ "benchmark_pr",)@@ -866,10 +877,25 @@ ALL_TIER_ONLY_OPTIONS = (@click.option("--tiers", default=None, help="Opt in with 1,2,3; requires a compatible candidate/release descriptor.")@click.option("--platform", type=click.Choice(["auto", "github", "gitlab"]), default="auto")@click.option("--env-mode", type=click.Choice(["docker", "local"]), default="docker")[email protected]("--provider", type=click.Choice(["openai", "anthropic", "nv_build"]), default="openai")[email protected]("--embedding-provider", type=click.Choice(["openai", "nv_build"]), default=None)+ "--provider", type=click.Choice(["openai", "anthropic", "nv_build", "openai-compatible"]), default="openai"+)[email protected]("--embedding-provider", type=click.Choice(["openai", "nv_build", "openai-compatible"]), default=None)@click.option("--model", default=None)@click.option("--embedding-model", default=None)[email protected]("--tier1-llm", is_flag=True, help="Opt into protected Tier 1 LLM checks.")[email protected]("--tier1-provider", type=click.Choice(["openai", "anthropic", "nv_build"]), default=None)[email protected]("--tier1-model", default="")[email protected]("--base-url", default="", help="Chat API root for the selected provider.")[email protected]("--embedding-base-url", default="")+ "--tier3-provider", type=click.Choice(["openai", "anthropic", "nv_build", "openai-compatible"]), default=None+)[email protected]("--tier3-model", default="")[email protected]("--tier3-base-url", default="")[email protected]("--agent-model", multiple=True, metavar="AGENT=MODEL", help="Repeat for native agent model overrides.")[email protected]("--gateway-secret", default="SKILL_EVAL_LLM_API_KEY", help="CI secret name for the generic gateway key.")[email protected]("--benchmark-pr", is_flag=True, help="Opt into benchmark-update PR publication on GitHub.")@click.option("--agents", default=None)@click.option("--runner", default=None, help="GitHub runner label or GitLab runner tag.")@click.option(@@ -913,6 +939,17 @@ def init(embedding_provider,model,embedding_model,+ tier1_llm,+ tier1_provider,+ tier1_model,+ base_url,+ embedding_base_url,+ tier3_provider,+ tier3_model,+ tier3_base_url,+ agent_model,+ gateway_secret,+ benchmark_pr,agents,runner,tier3_required,@@ -962,6 +999,17 @@ def init(embedding_provider=embedding_provider,model=model,embedding_model=embedding_model,+ tier1_llm=tier1_llm,+ tier1_provider=tier1_provider,+ tier1_model=tier1_model,+ base_url=base_url,+ embedding_base_url=embedding_base_url,+ tier3_provider=tier3_provider,+ tier3_model=tier3_model,+ tier3_base_url=tier3_base_url,+ agent_model=agent_model,+ gateway_secret=gateway_secret,+ benchmark_pr=benchmark_pr,agents=agents,runner=runner,tier3_required=False,diff --git a/src/skillevaluator/reporting/json_reporter.py b/src/skillevaluator/reporting/json_reporter.pyindex b4230ee5..d878c8e0 100644--- a/src/skillevaluator/reporting/json_reporter.py+++ b/src/skillevaluator/reporting/json_reporter.py@@ -18,7 +18,11 @@ import jsonfrom datetime import UTC, datetimefrom typing import TYPE_CHECKING, Any-from skillevaluator.publication_evidence import result_publication_evidence_dict+from skillevaluator.publication_evidence import (+ TIER1_REQUIRED_CHECKS_KEY,+ TIER1_UNSCANNED_PATHS_KEY,+ result_publication_evidence_dict,+)from skillevaluator.reporting.base import (ReporterBase,assess_publication,@@ -63,6 +67,22 @@ def _json_safe_benchmark_policy(value: object) -> dict[str, bool] | None:return policy or None+def _tier1_scope_strings(value: object, field: str) -> list[str]:+ """Copy bounded scope evidence without narrowing its publication meaning.++ Reject malformed declarations rather than dropping them: absence has legacy+ semantics and could otherwise turn incomplete evidence into a passing run.+ Semantic lineup validation remains the publication assessor's responsibility.+ """+ if (+ not isinstance(value, list)+ or len(value) > 20_000+ or any(not isinstance(item, str) or not 1 <= len(item) <= 4096 for item in value)+ ):+ raise ValueError(f"Invalid {field}: expected a bounded list of nonempty strings")+ return list(value)++class JSONReporter(ReporterBase):"""JSON export for machine-readable output.@@ -325,6 +345,10 @@ class JSONReporter(ReporterBase):if result.metadata.get("confirmed_failure") is True:data["confirmed_failure"] = True+ for key in (TIER1_REQUIRED_CHECKS_KEY, TIER1_UNSCANNED_PATHS_KEY):+ if key in result.metadata:+ data[key] = _tier1_scope_strings(result.metadata[key], key)+skillspector_version = result.metadata.get("skillspector_version")if isinstance(skillspector_version, str):data["skillspector_version"] = skillspector_versiondiff --git a/src/skillevaluator/reporting/retained.py b/src/skillevaluator/reporting/retained.pyindex cee7c198..5de3a474 100644--- a/src/skillevaluator/reporting/retained.py+++ b/src/skillevaluator/reporting/retained.py@@ -14,8 +14,10 @@ from functools import partialfrom typing import Anyfrom skillevaluator.models import Finding, SuccessDetail, ValidationResult, ValidationSummary+from skillevaluator.publication_evidence import TIER1_REQUIRED_CHECKS_KEY, TIER1_UNSCANNED_PATHS_KEYfrom skillevaluator.reporting.base import is_cleanly_skipped, is_tier2_result, is_tier3_result, passes_required_gatefrom skillevaluator.reporting.html import HTMLReporter+from skillevaluator.reporting.json_reporter import _tier1_scope_stringsfrom skillevaluator.reporting.run_status import resolve_run_status, result_statusfrom skillevaluator.skillspector_provenance import sanitize_skillspector_provenance_metadatafrom skillevaluator.skillspector_reference_caveats import sanitize_reference_caveat_metadata@@ -267,6 +269,12 @@ def retained_results(for key in ("incomplete_scans", "gate_failures"):if key in row:metadata[key] = _strings(row[key], key)+ for key in (TIER1_REQUIRED_CHECKS_KEY, TIER1_UNSCANNED_PATHS_KEY):+ if key in row:+ try:+ metadata[key] = _tier1_scope_strings(row[key], key)+ except ValueError as exc:+ raise RetainedReportError(str(exc)) from excif "scanners" in row:_require(isinstance(row["scanners"], dict)diff --git a/tests/ci/test_all_tier_preflight.py b/tests/ci/test_all_tier_preflight.pyindex 9c1d8d85..15672252 100644--- a/tests/ci/test_all_tier_preflight.py+++ b/tests/ci/test_all_tier_preflight.py@@ -29,7 +29,20 @@ def test_docker_bootstrap_uses_selected_mode_without_host_agent_install(monkeypa)assert bootstrap.main() == 0assert calls == [- [sys.executable, "-I", "-m", "skillevaluator.cli", "doctor", "--env-mode", "docker", "--agents", "codex"]+ [+ sys.executable,+ "-I",+ "-m",+ "skillevaluator.cli",+ "doctor",+ "--tier",+ "3",+ "--verify-models",+ "--env-mode",+ "docker",+ "--agents",+ "codex",+ ]]@@ -55,7 +68,20 @@ def test_local_bootstrap_installs_only_the_selected_native_runtime(monkeypatch):assert bootstrap.main() == 0assert calls == ["claude-code",- [sys.executable, "-I", "-m", "skillevaluator.cli", "doctor", "--env-mode", "local", "--agents", "claude-code"],+ [+ sys.executable,+ "-I",+ "-m",+ "skillevaluator.cli",+ "doctor",+ "--tier",+ "3",+ "--verify-models",+ "--env-mode",+ "local",+ "--agents",+ "claude-code",+ ],]@@ -95,9 +121,11 @@ def test_gitlab_admission_allows_only_protected_default_branch_without_mr():"CI_COMMIT_BRANCH": "main","CI_DEFAULT_BRANCH": "main","CI_COMMIT_REF_PROTECTED": "true",+ "CI_COMMIT_SHA": "a" * 40,}- assert gate.eligible(env, None)- assert not gate.eligible({**env, "CI_COMMIT_REF_PROTECTED": "false"}, None)+ current = {"name": "main", "protected": True, "commit": {"id": "a" * 40}}+ assert gate.eligible(env, current)+ assert not gate.eligible({**env, "CI_COMMIT_REF_PROTECTED": "false"}, current)def test_actual_workflow_bootstrap_ignores_consumer_pythonpath(tmp_path):@@ -215,3 +243,33 @@ def test_provider_child_excludes_both_gitlab_read_and_feedback_credentials():assert not any(key in child for key in ("SKILLEVALUATOR_GITLAB_READ_TOKEN", "SKILLEVALUATOR_GITLAB_TOKEN", "CI_JOB_TOKEN"))+++def test_bootstrap_doctor_uses_isolated_tier3_gateway_and_native_model_choices(monkeypatch):+ bootstrap = module("bootstrap_tiers")+ captured = []+ monkeypatch.setenv("SKILL_EVAL_ENV_MODE", "docker")+ monkeypatch.setenv("SKILL_EVAL_PROVIDER", "nv_build")+ monkeypatch.setenv("SKILL_EVAL_TIER3_PROVIDER", "openai-compatible")+ monkeypatch.setenv("SKILL_EVAL_TIER3_MODEL", "catalog/judge")+ monkeypatch.setenv("SKILL_EVAL_TIER3_BASE_URL", "https://gateway.example/v1")+ monkeypatch.setenv("SKILL_EVAL_LLM_API_KEY", "gateway-secret")+ monkeypatch.setenv("SKILL_EVAL_AGENTS", "claude-code,codex")+ monkeypatch.setenv("SKILL_EVAL_AGENT_MODELS", "claude-code=aws/anthropic/opus,codex=openai/openai/gpt")+ monkeypatch.setenv("GITHUB_TOKEN", "must-not-leak")+ monkeypatch.setenv("ANTHROPIC_API_KEY", "must-not-leak")+ monkeypatch.setenv("HOME", "/home/runner")++ def doctor(args, **kwargs):+ captured.append((args, kwargs["env"]))+ return subprocess.CompletedProcess(args, 0)++ monkeypatch.setattr(bootstrap.subprocess, "run", doctor)+ assert bootstrap.main() == 0+ args, child = captured[0]+ assert args[-4:] == ["--agent-model", "claude-code=aws/anthropic/opus", "--agent-model", "codex=openai/openai/gpt"]+ assert child["SKILL_EVAL_LLM_PROVIDER"] == "openai-compatible"+ assert child["SKILL_EVAL_LLM_MODEL"] == "catalog/judge"+ assert child["SKILL_EVAL_LLM_API_KEY"] == "gateway-secret"+ assert child["HOME"] == "/home/runner"+ assert not set(child) & {"GITHUB_TOKEN", "ANTHROPIC_API_KEY", "SKILL_EVAL_AGENT_MODELS"}diff --git a/tests/ci/test_all_tier_workflows.py b/tests/ci/test_all_tier_workflows.pyindex af09b49a..74e1c3fc 100644--- a/tests/ci/test_all_tier_workflows.py+++ b/tests/ci/test_all_tier_workflows.py@@ -45,7 +45,7 @@ def test_aggregate_retains_every_tier_after_failure():workflow = load(".github/workflows/evaluate-all-tiers.yml")aggregate = workflow["jobs"]["aggregate"]assert aggregate["if"] == "${{ always() }}"- assert set(aggregate["needs"]) == {"tier1", "paid-tiers"}+ assert set(aggregate["needs"]) == {"tier1", "tier1-llm", "paid-tiers"}downloads = [s for s in aggregate["steps"] if s.get("uses", "").startswith("actions/download-artifact@")]assert [s["with"]["pattern"] for s in downloads] == ["skill-evaluator-tier[123]-attempt-*"]assert downloads[0]["with"]["path"] == "${{ runner.temp }}/skill-artifacts"@@ -68,7 +68,9 @@ def test_aggregate_reuses_tier_evidence_from_jobs_not_rerun():pattern = download["with"]["pattern"]tier1 = load(".github/workflows/evaluate-skills.yml")["jobs"]["tier1"]["steps"]produced = [- s["with"]["name"].replace("${{ inputs.artifact-name }}", workflow["jobs"]["tier1"]["with"]["artifact-name"])+ # The default/fork path retains canonical static evidence. Protected+ # enrichment emits the same canonical name from its separate job.+ s["with"]["name"].replace("${{ inputs.artifact-name }}", "skill-evaluator-tier1")for s in tier1if s.get("uses", "").startswith("actions/upload-artifact@")]@@ -300,6 +302,7 @@ def test_gitlab_aggregate_downloads_evidence_from_both_advisory_tiers():{"job": "skill-evaluation", "artifacts": "true", "optional": "true"},{"job": "skill-evaluation-native", "artifacts": "true", "optional": "true"},{"job": "skill-evaluation-native-tier2", "artifacts": "true", "optional": "true"},+ {"job": "skill-evaluation-tier1-llm", "artifacts": "true", "optional": "true"},]diff --git a/tests/ci/test_benchmark_publish.py b/tests/ci/test_benchmark_publish.pynew file mode 100644index 00000000..90a0929d--- /dev/null+++ b/tests/ci/test_benchmark_publish.py@@ -0,0 +1,748 @@+# SPDX-License-Identifier: Apache-2.0+"""Benchmark publication regenerates evidence and restricts all repository writes."""++import copy+import importlib+import json+import subprocess+import sys+import urllib.error++import pytest+from tests.ci.test_feedback import BLOB, REPO, SHA, WORKFLOW, GitHub+++def adapter():+ return importlib.import_module("ci.benchmark_publish")+++class Publisher(GitHub):+ def __init__(self):+ super().__init__()+ self.run.update(event="push", head_branch="main", pull_requests=[])+ self.entries = [+ {"path": "skills", "mode": "040000", "type": "tree", "sha": "e" * 40},+ {"path": "skills/demo", "mode": "040000", "type": "tree", "sha": "f" * 40},+ {"path": "skills/demo/SKILL.md", "mode": "100644", "type": "blob", "sha": BLOB},+ ]+ self.branch = None+ self.commit_count = 0+ self.commit_messages = {}+ self.generated_entries = None+ self.pull = None+ self.current_sha = SHA+ self.calls = 0+ self.stale_at = None++ def get(self, path):+ root = "/repos/" + REPO+ if path.startswith(root + "/contents/.github/workflows/"):+ assert path.endswith("?ref=" + SHA)+ return {"type": "file", "path": ".github/workflows/skill-checks-all-tiers.yml", "sha": BLOB}+ if path == root:+ return {"default_branch": "main", "full_name": REPO}+ if path == root + "/git/ref/heads/main":+ self.calls += 1+ return {"object": {"type": "commit", "sha": "9" * 40 if self.stale_at == self.calls else self.current_sha}}+ if path == root + "/git/ref/heads/skillevaluator/benchmark-update":+ if self.branch is None:+ raise urllib.error.HTTPError("", 404, "", {}, None)+ return {"object": {"type": "commit", "sha": self.branch}}+ if path.startswith(root + "/git/commits/"):+ return {+ "tree": {"sha": "1" * 40 if path.endswith(SHA) else "2" * 40},+ "message": self.commit_messages.get(+ path.rsplit("/", 1)[-1],+ "Update eligible SkillEvaluator benchmark cards\n\nSource: "+ + SHA+ + "\nRun: 123/1\nBenchmark-Cards: "+ + json.dumps({"skills/demo/BENCHMARK.md": adapter()._blob("generated card\n")}),+ ),+ }+ if path.startswith(root + "/git/trees/"):+ return {+ "truncated": False,+ "tree": copy.deepcopy(+ self.generated_entries+ if "/" + "2" * 40 in path and self.generated_entries is not None+ else self.entries+ ),+ }+ if path == root + "/pulls/8":+ return copy.deepcopy(self.pull)+ if path.startswith(root + "/pulls?"):+ return [copy.deepcopy(self.pull)] if self.pull else []+ return super().get(path)++ def post(self, path, payload):+ self.writes.append(("post", path, payload))+ if path.endswith("/git/trees"):+ self.generated_entries = copy.deepcopy(self.entries)+ changed = {row["path"] for row in payload["tree"]}+ self.generated_entries = [row for row in self.generated_entries if row["path"] not in changed]+ self.generated_entries.extend(+ {"path": row["path"], "mode": row["mode"], "type": row["type"], "sha": adapter()._blob(row["content"])}+ for row in payload["tree"]+ )+ return {"sha": "2" * 40}+ if path.endswith("/git/commits"):+ self.commit_count += 1+ sha = ("3" if self.commit_count == 1 else "8") * 40+ self.commit_messages[sha] = payload["message"]+ return {"sha": sha}+ if path.endswith("/git/refs"):+ self.branch = payload["sha"]+ return {"object": {"sha": self.branch}}+ if path.endswith("/pulls"):+ self.pull = {+ "number": 8,+ "html_url": f"https://github.com/{REPO}/pull/8",+ "state": "open",+ "head": {"ref": "skillevaluator/benchmark-update", "repo": {"full_name": REPO}, "sha": self.branch},+ "base": {"ref": "main", "repo": {"full_name": REPO}},+ **{k: v for k, v in payload.items() if k not in {"head", "base"}},+ "user": {"login": "github-actions[bot]", "type": "Bot"},+ }+ return self.pull+ raise AssertionError(path)++ def patch(self, path, payload):+ self.writes.append(("patch", path, payload))+ if "/git/refs/" in path:+ self.branch = payload["sha"]+ if self.pull:+ self.pull["head"]["sha"] = self.branch+ return {"object": {"sha": self.branch}}+ if "/pulls/" in path:+ self.pull.update(payload)+ return self.pull+ raise AssertionError(path)+++def trusted(monkeypatch):+ monkeypatch.setenv("SKILL_EVAL_TRUSTED_WORKFLOW_REF", WORKFLOW)+ monkeypatch.setenv("SKILL_EVAL_TRUSTED_CALLER_BLOBS", BLOB)+ from ci import feedback++ monkeypatch.setattr(feedback, "verify_receipt", lambda *_a, **_kw: {"workflow_sha": SHA})+ return Publisher()+++def documents(monkeypatch, *, eligible=True):+ module = adapter()+ monkeypatch.setattr(+ module,+ "benchmark_documents",+ lambda _manifest, _native: [+ {"path": "skills/demo", "eligible": eligible, "benchmark_content": "generated card\n"}+ ],+ )+ return module+++def test_only_regenerated_cards_written_and_reviewable_pr(trusted, monkeypatch):+ module = documents(monkeypatch)+ result = module.github_benchmark_publish(trusted, REPO, 123, 1)+ assert result["benchmark_action"] == "created"+ tree = next(payload for _, path, payload in trusted.writes if path.endswith("/git/trees"))+ assert tree["tree"] == [+ {"path": "skills/demo/BENCHMARK.md", "mode": "100644", "type": "blob", "content": "generated card\n"}+ ]+ assert all("/contents/" not in path for _, path, _ in trusted.writes)+ pr = next(payload for _, path, payload in trusted.writes if path.endswith("/pulls"))+ assert pr["base"] == "main" and pr["head"] == module.BRANCH+ assert SHA in pr["body"] and "/actions/runs/123/artifacts/21" in pr["body"]++[email protected]("change", ["fork", "attempt", "event", "archive"])+def test_rejects_unauthorized_evidence_without_writes(trusted, monkeypatch, change):+ module = documents(monkeypatch)+ if change == "fork":+ trusted.run["head_repository"]["full_name"] = "foreign/repo"+ elif change == "attempt":+ trusted.run["run_attempt"] = 2+ elif change == "event":+ trusted.run["event"] = "pull_request"+ else:+ trusted.payload = b"not zip"+ with pytest.raises(ValueError):+ module.github_benchmark_publish(trusted, REPO, 123, 1)+ assert trusted.writes == []+++def test_initial_stale_default_head_is_successful_no_write_skip(trusted, monkeypatch, capsys):+ module = documents(monkeypatch)+ trusted.current_sha = "9" * 40+ monkeypatch.setenv("GITHUB_TOKEN", "publisher-token")+ monkeypatch.setattr(module.publish_reports, "GitHubAPI", lambda *_args: trusted)++ def unexpected_documents(*_args):+ pytest.fail("A stale producer must skip before regenerating cards.")++ monkeypatch.setattr(module, "benchmark_documents", unexpected_documents)+ assert module.main(["--repository", REPO, "--run-id", "123", "--run-attempt", "1"]) == 0+ output = capsys.readouterr()+ assert json.loads(output.out)["benchmark_action"] == "skipped"+ assert output.err == ""+ assert trusted.writes == []+++def test_ineligible_noop(trusted, monkeypatch):+ module = documents(monkeypatch, eligible=False)+ assert module.github_benchmark_publish(trusted, REPO, 123, 1)["benchmark_action"] == "unchanged"+ assert trusted.writes == []+++def test_stale_after_read_never_mutates(trusted, monkeypatch):+ module = documents(monkeypatch)+ trusted.stale_at = 2+ assert module.github_benchmark_publish(trusted, REPO, 123, 1)["benchmark_action"] == "skipped"+ assert trusted.writes == []++[email protected]("mode,kind", [("120000", "blob"), ("040000", "tree"), ("160000", "commit")])+def test_target_requires_regular_file(trusted, monkeypatch, mode, kind):+ module = documents(monkeypatch)+ trusted.entries.append({"path": "skills/demo/BENCHMARK.md", "mode": mode, "type": kind, "sha": BLOB})+ with pytest.raises(ValueError):+ module.github_benchmark_publish(trusted, REPO, 123, 1)+ assert trusted.writes == []+++def native_archive(tmp_path, *, tamper=False, conflict=False):+ import json++ from tests.ci.test_benchmark_reports import retain+ from tests.ci.test_feedback import archive, manifest++ payload = manifest()+ payload["tiers"] = retain(tmp_path)["tiers"]+ extra = {}+ for tier in payload["tiers"]:+ for skill in tier["skills"]:+ relative = skill["report_json"]+ skill["report_html"] = relative.removesuffix(".json") + ".html"+ native = json.loads((tmp_path / relative).read_text())+ if tier["tier"] == 3:+ native["tier3"]["mode"] = "both"+ native["tier3"]["summary"]["mode"] = "both"+ for result in native["results"]:+ result["tier3"]["mode"] = "both"+ result["tier3"]["summary"]["mode"] = "both"+ if conflict:+ native["evaluated_source"] = {"repository": "foreign/repo", "commit": SHA}+ if tamper and tier["tier"] == 1:+ native["results"][0]["passed"] = False+ extra[relative] = json.dumps(native)+ extra[skill["report_html"]] = "native html not interpreted"+ extra["benchmarks/skill-001/BENCHMARK.md"] = "MALICIOUS CARD CONTENT"+ extra["benchmarks/skill-001/skillevaluator.json"] = '{"publication":{"eligible":true}}'+ return archive(payload, extra)+++def test_real_native_reports_regenerate_and_ignore_artifact_cards(trusted, tmp_path):+ trusted.payload = native_archive(tmp_path)+ module = adapter()+ assert module.github_benchmark_publish(trusted, REPO, 123, 1)["benchmark_action"] == "created"+ tree = next(payload for _, path, payload in trusted.writes if path.endswith("/git/trees"))+ card = tree["tree"][0]["content"]+ assert "MALICIOUS" not in card+ assert "Source digest:" in card+++def test_conflicting_native_source_cannot_publish(trusted, tmp_path):+ trusted.payload = native_archive(tmp_path, conflict=True)+ assert adapter().github_benchmark_publish(trusted, REPO, 123, 1)["benchmark_action"] == "unchanged"+ assert trusted.writes == []+++def test_invalid_native_report_cannot_publish(trusted, tmp_path):+ trusted.payload = native_archive(tmp_path, tamper=True)+ with pytest.raises(ValueError):+ adapter().github_benchmark_publish(trusted, REPO, 123, 1)+ assert trusted.writes == []+++def test_read_results_exposes_only_fully_validated_native_reports(tmp_path):+ from ci import feedback++ native = {}+ feedback.read_results(native_archive(tmp_path), native_reports=native)+ assert len(native) == 3+ assert all(path.startswith("tier") for path in native)+ retained = {"unchanged": {}}+ with pytest.raises(ValueError):+ feedback.read_results(native_archive(tmp_path, tamper=True), native_reports=retained)+ assert retained == {"unchanged": {}}+++def test_unchanged_cards_do_not_create_branch(trusted, monkeypatch):+ module = documents(monkeypatch)+ trusted.entries.append(+ {"path": "skills/demo/BENCHMARK.md", "mode": "100644", "type": "blob", "sha": module._blob("generated card\n")}+ )+ assert module.github_benchmark_publish(trusted, REPO, 123, 1)["benchmark_action"] == "unchanged"+ assert trusted.writes == []+++def test_rerun_reuses_owned_branch_and_pr(trusted, monkeypatch):+ module = documents(monkeypatch)+ module.github_benchmark_publish(trusted, REPO, 123, 1)+ source_entries = copy.deepcopy(trusted.entries)+ branch_entries = [+ *source_entries,+ {"path": "skills/demo/BENCHMARK.md", "mode": "100644", "type": "blob", "sha": module._blob("generated card\n")},+ ]+ original_get = trusted.get++ def get(path):+ if "/git/trees/" in path:+ return {"truncated": False, "tree": branch_entries if "/" + "2" * 40 in path else source_entries}+ return original_get(path)++ monkeypatch.setattr(trusted, "get", get)+ trusted.writes.clear()+ assert module.github_benchmark_publish(trusted, REPO, 123, 1)["benchmark_action"] == "unchanged"+ assert trusted.writes == []+++def test_existing_branch_unrelated_changes_rejected(trusted, monkeypatch):+ module = documents(monkeypatch)+ trusted.branch = "3" * 40+ original_get = trusted.get++ def get(path):+ result = original_get(path)+ if "/git/trees/" + "2" * 40 in path:+ result["tree"].append({"path": "unrelated.txt", "mode": "100644", "type": "blob", "sha": BLOB})+ return result++ monkeypatch.setattr(trusted, "get", get)+ with pytest.raises(ValueError):+ module.github_benchmark_publish(trusted, REPO, 123, 1)+ assert trusted.writes == []+++def test_actions_cannot_create_pr_fixed_manual_fallback(trusted, monkeypatch):+ module = documents(monkeypatch)+ original_post = trusted.post++ def post(path, payload):+ if path.endswith("/pulls"):+ raise urllib.error.HTTPError("", 403, "secret provider text", {}, None)+ return original_post(path, payload)++ monkeypatch.setattr(trusted, "post", post)+ result = module.github_benchmark_publish(trusted, REPO, 123, 1)+ assert result == {"benchmark_action": "branch_ready", "benchmark_reason": module.PR_DISABLED}+ assert "secret" not in str(result)+ assert trusted.branch is not None+++def test_manual_run_on_current_default_branch_is_eligible(trusted, monkeypatch):+ module = documents(monkeypatch)+ trusted.run["event"] = "workflow_dispatch"+ assert module.github_benchmark_publish(trusted, REPO, 123, 1)["benchmark_action"] == "created"+++def test_recheck_superseded_attempt_before_writes(trusted, monkeypatch):+ module = documents(monkeypatch)+ original_get = trusted.get++ def get(path):+ result = original_get(path)+ if "/git/trees/" in path:+ trusted.run["run_attempt"] = 2+ return result++ monkeypatch.setattr(trusted, "get", get)+ assert module.github_benchmark_publish(trusted, REPO, 123, 1)["benchmark_action"] == "skipped"+ assert trusted.writes == []+++def test_foreign_existing_pr_is_not_modified(trusted, monkeypatch):+ module = documents(monkeypatch)+ module.github_benchmark_publish(trusted, REPO, 123, 1)+ trusted.pull["user"] = {"login": "human", "type": "User"}+ trusted.writes.clear()+ with pytest.raises(ValueError):+ module.github_benchmark_publish(trusted, REPO, 123, 1)+ assert trusted.writes == []+++def test_owned_pr_updated_without_touching_source_pr(trusted, monkeypatch):+ module = documents(monkeypatch)+ module.github_benchmark_publish(trusted, REPO, 123, 1)+ monkeypatch.setattr(+ module,+ "benchmark_documents",+ lambda _manifest, _native: [{"path": "skills/demo", "eligible": True, "benchmark_content": "new card\n"}],+ )+ trusted.pull["body"] = module.MARKER + "\nOld evaluation report"+ trusted.writes.clear()+ assert module.github_benchmark_publish(trusted, REPO, 123, 1)["benchmark_action"] == "updated"+ updates = [(path, payload) for method, path, payload in trusted.writes if method == "patch"]+ assert updates[-1][0] == "/repos/" + REPO + "/pulls/8"+ assert all("/pulls/7" not in path for _, path, _ in trusted.writes)+ branch = next(payload for method, path, payload in trusted.writes if method == "patch" and "/git/refs/" in path)+ assert branch["force"] is False+++def test_existing_pr_update_tolerates_live_repository_and_user_metadata(trusted, monkeypatch):+ module = documents(monkeypatch)+ module.github_benchmark_publish(trusted, REPO, 123, 1)+ trusted.pull["body"] = module.MARKER + "\nOld evaluation report"+ trusted.pull["base"]["repo"].update(+ pushed_at="2026-11-09T20:30:00Z", updated_at="2026-11-09T20:30:00Z", open_issues_count=8+ )+ trusted.pull["user"]["avatar_url"] = "https://avatars.githubusercontent.com/u/old"+ monkeypatch.setattr(+ module,+ "benchmark_documents",+ lambda _manifest, _native: [{"path": "skills/demo", "eligible": True, "benchmark_content": "new card\n"}],+ )+ original_patch = trusted.patch++ def patch(path, payload):+ response = original_patch(path, payload)+ if "/git/refs/" in path:+ # A push updates live repository metadata included in a fresh PR response.+ trusted.pull["base"]["repo"].update(+ pushed_at="2026-11-09T20:34:00Z", updated_at="2026-11-09T20:34:00Z", open_issues_count=9+ )+ trusted.pull["user"]["avatar_url"] = "https://avatars.githubusercontent.com/u/current"+ return response++ monkeypatch.setattr(trusted, "patch", patch)+ trusted.writes.clear()+ result = module.github_benchmark_publish(trusted, REPO, 123, 1)+ assert result["benchmark_action"] == "updated"+ assert SHA in trusted.pull["body"] and "attempt 1" in trusted.pull["body"]+ assert trusted.writes[-1][0:2] == ("patch", "/repos/" + REPO + "/pulls/8")+ branch = next(payload for _, path, payload in trusted.writes if "/git/refs/" in path)+ assert branch["force"] is False+++ "field,value",+ [+ (("number",), 9),+ (("body",), "Human edit"),+ (("title",), "Human title"),+ (("state",), "closed"),+ (("base", "ref"), "other"),+ (("base", "repo", "full_name"), "foreign/repo"),+ (("user", "login"), "another[bot]"),+ (("user", "type"), "User"),+ (("head", "ref"), "other"),+ (("head", "repo", "full_name"), "foreign/repo"),+ (("head", "sha"), "9" * 40),+ ],+)+def test_changed_pr_before_patch_is_not_overwritten(trusted, monkeypatch, field, value):+ module = documents(monkeypatch)+ module.github_benchmark_publish(trusted, REPO, 123, 1)+ trusted.pull["body"] = module.MARKER + "\nOld evaluation report"+ trusted.writes.clear()+ original_get = trusted.get++ def get(path):+ result = original_get(path)+ if path.endswith("/pulls/8"):+ target = result+ for part in field[:-1]:+ target = target[part]+ target[field[-1]] = value+ return result++ monkeypatch.setattr(trusted, "get", get)+ with pytest.raises(ValueError, match=r"PR (head )?changed"):+ module.github_benchmark_publish(trusted, REPO, 123, 1)+ assert all("/pulls/" not in path for _, path, _ in trusted.writes)+++def test_unrelated_repository_filenames_are_preserved_during_publication(trusted, monkeypatch):+ module = documents(monkeypatch)+ unrelated = [+ {"path": "docs", "mode": "040000", "type": "tree", "sha": "7" * 40},+ *[+ {"path": path, "mode": "100644", "type": "blob", "sha": BLOB}+ for path in (+ "docs/c#-notes.md",+ "docs/100%-notes.md",+ "docs/why?.md",+ "docs/colon:notes.md",+ r"docs/back\slash.md",+ )+ ],+ ]+ trusted.entries.extend(copy.deepcopy(unrelated))+ assert module.github_benchmark_publish(trusted, REPO, 123, 1)["benchmark_action"] == "created"+ monkeypatch.setattr(+ module,+ "benchmark_documents",+ lambda _manifest, _native: [{"path": "skills/demo", "eligible": True, "benchmark_content": "new card\n"}],+ )+ trusted.writes.clear()+ assert module.github_benchmark_publish(trusted, REPO, 123, 1)["benchmark_action"] == "updated"+ assert all(entry in trusted.generated_entries for entry in unrelated)+ tree = next(payload for _, path, payload in trusted.writes if path.endswith("/git/trees"))+ assert tree == {+ "base_tree": "1" * 40,+ "tree": [{"path": "skills/demo/BENCHMARK.md", "mode": "100644", "type": "blob", "content": "new card\n"}],+ }+ assert all("/heads/main" not in path and "/pulls/7" not in path for _, path, _ in trusted.writes)++[email protected]("path", [None, "", "x" * 4097, "skills/demo/SKILL.md"])+def test_invalid_or_duplicate_repository_tree_paths_rejected(trusted, monkeypatch, path):+ module = documents(monkeypatch)+ trusted.entries.append({"path": path, "mode": "100644", "type": "blob", "sha": BLOB})+ with pytest.raises(ValueError, match="invalid path"):+ module.github_benchmark_publish(trusted, REPO, 123, 1)+ assert trusted.writes == []+++def test_unrelated_tree_entry_still_requires_git_object_identity(trusted, monkeypatch):+ module = documents(monkeypatch)+ trusted.entries.append({"path": "notes.md", "mode": "100644", "type": "blob", "sha": "invalid"})+ with pytest.raises(ValueError, match="object identity"):+ module.github_benchmark_publish(trusted, REPO, 123, 1)+ assert trusted.writes == []+++def test_superseded_default_head_skips_without_writes(trusted, monkeypatch):+ # A newer default-branch push during a long run is routine, not a failure.+ module = documents(monkeypatch)+ trusted.current_sha = "9" * 40+ assert module.github_benchmark_publish(trusted, REPO, 123, 1)["benchmark_action"] == "skipped"+ assert trusted.writes == []+++def test_unrelated_repository_paths_do_not_block_publication(trusted, monkeypatch):+ module = documents(monkeypatch)+ trusted.entries[:0] = [+ {"path": "docs", "mode": "040000", "type": "tree", "sha": "c" * 40},+ {"path": "docs/c#-notes 100%.md", "mode": "100644", "type": "blob", "sha": "d" * 40},+ ]+ assert module.github_benchmark_publish(trusted, REPO, 123, 1)["benchmark_action"] == "created"+++def test_owned_pr_update_ignores_live_repository_metadata(trusted, monkeypatch):+ # GitHub returns base.repo as the live repository; the branch push changes pushed_at.+ module = documents(monkeypatch)+ module.github_benchmark_publish(trusted, REPO, 123, 1)+ monkeypatch.setattr(+ module,+ "benchmark_documents",+ lambda _manifest, _native: [{"path": "skills/demo", "eligible": True, "benchmark_content": "new card\n"}],+ )+ trusted.pull["body"] = module.MARKER + "\nOld evaluation report"+ trusted.pull["base"]["repo"]["pushed_at"] = "2026-11-10T00:00:00Z"+ trusted.writes.clear()+ original_get = trusted.get++ def get(path):+ result = original_get(path)+ if path.endswith("/pulls/8"):+ result["base"]["repo"]["pushed_at"] = "2026-11-10T00:05:00Z"+ result["base"]["sha"] = "b" * 40+ return result++ monkeypatch.setattr(trusted, "get", get)+ assert module.github_benchmark_publish(trusted, REPO, 123, 1)["benchmark_action"] == "updated"+ assert any(method == "patch" and path.endswith("/pulls/8") for method, path, _ in trusted.writes)+++def test_changed_pr_body_before_patch_is_not_overwritten(trusted, monkeypatch):+ module = documents(monkeypatch)+ module.github_benchmark_publish(trusted, REPO, 123, 1)+ trusted.pull["body"] = module.MARKER + "\nOld evaluation report"+ trusted.writes.clear()+ original_get = trusted.get++ def get(path):+ result = original_get(path)+ if path.endswith("/pulls/8"):+ result["body"] = "Human edit"+ return result++ monkeypatch.setattr(trusted, "get", get)+ with pytest.raises(ValueError, match="PR changed"):+ module.github_benchmark_publish(trusted, REPO, 123, 1)+ assert all("/pulls/" not in path for _, path, _ in trusted.writes)+++def previous_source_branch(trusted, monkeypatch, *, unrelated=False, trailer=None):+ module = documents(monkeypatch)+ old_source = "4" * 40+ trusted.branch = "3" * 40+ trusted.commit_count = 1+ trusted.pull = {+ "number": 8,+ "state": "open",+ "title": "Update SkillEvaluator benchmark cards",+ "body": module.MARKER + "\nSource commit: " + old_source,+ "head": {"ref": module.BRANCH, "repo": {"full_name": REPO}, "sha": trusted.branch},+ "base": {"ref": "main", "repo": {"full_name": REPO}},+ "user": {"login": "github-actions[bot]", "type": "Bot"},+ }+ old_entries = copy.deepcopy(trusted.entries)+ trusted.entries[-1]["sha"] = "6" * 40 # current main advanced its skill source+ old_branch = [+ *copy.deepcopy(old_entries),+ {"path": "skills/demo/BENCHMARK.md", "mode": "100644", "type": "blob", "sha": BLOB},+ {"path": "BENCHMARK.md", "mode": "100644", "type": "blob", "sha": BLOB},+ ]+ if unrelated:+ old_branch[-3]["sha"] = "7" * 40+ original_get = trusted.get++ def get(path):+ if path.endswith("/compare/" + old_source + "..." + SHA):+ return {"status": "ahead", "merge_base_commit": {"sha": old_source}}+ if path.endswith("/git/commits/" + old_source):+ return {"tree": {"sha": "5" * 40}}+ if path.endswith("/git/commits/" + "3" * 40):+ return {+ "tree": {"sha": "2" * 40},+ "message": trailer+ if trailer is not None+ else "Update eligible SkillEvaluator benchmark cards\n\nSource: "+ + old_source+ + "\nRun: 122/1\nBenchmark-Cards: "+ + json.dumps({"skills/demo/BENCHMARK.md": BLOB, "BENCHMARK.md": BLOB}),+ "parents": [{"sha": old_source}],+ }+ if "/git/trees/" + "5" * 40 in path:+ return {"truncated": False, "tree": old_entries}+ if "/git/trees/" + "2" * 40 in path:+ return {"truncated": False, "tree": old_branch}+ return original_get(path)++ monkeypatch.setattr(trusted, "get", get)+ return module+++def test_previous_publication_source_advances_without_old_source_overwrite(trusted, monkeypatch):+ module = previous_source_branch(trusted, monkeypatch)+ assert module.github_benchmark_publish(trusted, REPO, 123, 1)["benchmark_action"] == "updated"+ tree = next(payload for _, path, payload in trusted.writes if path.endswith("/git/trees"))+ assert tree["base_tree"] == "1" * 40+ assert [row["path"] for row in tree["tree"]] == ["skills/demo/BENCHMARK.md"]+ commit = next(payload for _, path, payload in trusted.writes if path.endswith("/git/commits"))+ assert commit["parents"] == ["3" * 40, SHA]+ assert "Source: " + SHA in commit["message"]+ receipt_line = next(line for line in commit["message"].splitlines() if line.startswith("Benchmark-Cards: "))+ assert json.loads(receipt_line.removeprefix("Benchmark-Cards: ")) == {+ "skills/demo/BENCHMARK.md": module._blob("generated card\n")+ }+ update = next(payload for _, path, payload in trusted.writes if "/git/refs/" in path)+ assert update["force"] is False+++def test_previous_source_branch_unrelated_code_edit_rejected(trusted, monkeypatch):+ module = previous_source_branch(trusted, monkeypatch, unrelated=True)+ with pytest.raises(ValueError):+ module.github_benchmark_publish(trusted, REPO, 123, 1)+ assert trusted.writes == []+++ "trailer",+ [+ "Unknown commit",+ "Update eligible SkillEvaluator benchmark cards\n\nSource: invalid",+ "Update eligible SkillEvaluator benchmark cards\n\nSource: " + SHA + "\nSource: " + SHA,+ ],+)+def test_previous_source_missing_or_ambiguous_trailer_rejected(trusted, monkeypatch, trailer):+ module = previous_source_branch(trusted, monkeypatch, trailer=trailer)+ with pytest.raises(ValueError):+ module.github_benchmark_publish(trusted, REPO, 123, 1)+ assert trusted.writes == []+++def test_source_advance_during_prior_branch_read_skips(trusted, monkeypatch):+ module = previous_source_branch(trusted, monkeypatch)+ trusted.stale_at = 2+ assert module.github_benchmark_publish(trusted, REPO, 123, 1)["benchmark_action"] == "skipped"+ assert trusted.writes == []+++def test_recorded_source_must_be_current_default_history(trusted, monkeypatch):+ module = previous_source_branch(trusted, monkeypatch)+ original_get = trusted.get++ def get(path):+ if "/compare/" in path:+ return {"status": "diverged", "merge_base_commit": {"sha": "8" * 40}}+ return original_get(path)++ monkeypatch.setattr(trusted, "get", get)+ with pytest.raises(ValueError, match="default-branch history"):+ module.github_benchmark_publish(trusted, REPO, 123, 1)+ assert trusted.writes == []+++def test_existing_pr_tracks_new_head_sha_and_receives_current_body(trusted, monkeypatch):+ module = previous_source_branch(trusted, monkeypatch)+ old_head = trusted.pull["head"]["sha"]+ assert module.github_benchmark_publish(trusted, REPO, 123, 1)["benchmark_action"] == "updated"+ assert trusted.pull["head"]["sha"] != old_head+ assert SHA in trusted.pull["body"] and "attempt 1" in trusted.pull["body"]++[email protected]("manual_change", ["new_card", "modified_owned_card"])+def test_unproven_card_edits_are_not_discarded(trusted, monkeypatch, manual_change):+ module = previous_source_branch(trusted, monkeypatch)+ original_get = trusted.get++ def get(path):+ result = copy.deepcopy(original_get(path))+ if "/git/trees/" + "2" * 40 in path:+ if manual_change == "new_card":+ result["tree"].append(+ {"path": "skills/BENCHMARK.md", "mode": "100644", "type": "blob", "sha": "7" * 40}+ )+ else:+ next(row for row in result["tree"] if row["path"] == "skills/demo/BENCHMARK.md")["sha"] = "7" * 40+ return result++ monkeypatch.setattr(trusted, "get", get)+ with pytest.raises(ValueError):+ module.github_benchmark_publish(trusted, REPO, 123, 1)+ assert trusted.writes == []+++def test_package_import_identity_after_bootstrap_import():+ code = "import sys; from pathlib import Path; from ci import bootstrap_tiers; sys.path.insert(0, str(Path(bootstrap_tiers.__file__).parent)); from ci import benchmark_publish, feedback; assert benchmark_publish.feedback is feedback"+ completed = subprocess.run([sys.executable, "-c", code], check=False, capture_output=True, text=True)+ assert completed.returncode == 0, completed.stderr++[email protected]("receipt", [None, "duplicate", "invalid-json", "unsafe-path"])+def test_prior_card_receipt_required_and_unambiguous(trusted, monkeypatch, receipt):+ module = previous_source_branch(trusted, monkeypatch)+ original_get = trusted.get++ def get(path):+ result = original_get(path)+ if path.endswith("/git/commits/" + "3" * 40):+ message = result["message"]+ original = next(line for line in message.splitlines() if line.startswith("Benchmark-Cards:"))+ if receipt is None:+ result["message"] = message.replace("\n" + original, "")+ elif receipt == "duplicate":+ result["message"] += "\n" + original+ elif receipt == "invalid-json":+ result["message"] = message.replace(original, "Benchmark-Cards: {invalid}")+ else:+ result["message"] = message.replace(original, 'Benchmark-Cards: {"../BENCHMARK.md":"' + BLOB + '"}')+ return result++ monkeypatch.setattr(trusted, "get", get)+ with pytest.raises(ValueError):+ module.github_benchmark_publish(trusted, REPO, 123, 1)+ assert trusted.writes == []diff --git a/tests/ci/test_benchmark_report_links.py b/tests/ci/test_benchmark_report_links.pynew file mode 100644index 00000000..32feea0d--- /dev/null+++ b/tests/ci/test_benchmark_report_links.py@@ -0,0 +1,84 @@+# SPDX-License-Identifier: Apache-2.0+"""Benchmark artifact links remain bounded, source-scoped and explicit."""++import pytest++from ci import tier_manifest+++def manifest():+ return {+ "schema_version": 1,+ "report_contract": "skillevaluator-ci-v1",+ "commit": "a" * 40,+ "base_commit": None,+ "repository": "acme/skills",+ "platform": "github",+ "run_id": "123",+ "run_attempt": "1",+ "environment": "docker",+ "tiers": [{"tier": 1, "status": "skipped", "required": True, "skills": [], "reason": "No work"}],+ "benchmarks": [],+ }+++def card():+ return {+ "path": "skills/demo",+ "combined_json": "benchmarks/skill-001/skillevaluator.json",+ "benchmark_md": "benchmarks/skill-001/BENCHMARK.md",+ "publication_status": "incomplete",+ "eligible": False,+ }+++def with_card():+ payload = manifest()+ payload["tiers"][0].update(+ status="passed",+ skills=[+ {+ "path": "skills/demo",+ "status": "passed",+ "report_json": "tier1/skill-001/skillevaluator-tier1.json",+ "report_html": "tier1/skill-001/skillevaluator-tier1.html",+ }+ ],+ )+ payload["benchmarks"] = [card()]+ return payload+++def test_cards_link_from_both_aggregate_surfaces_without_claiming_a_pass():+ payload = with_card()+ assert tier_manifest.validate_manifest(payload)["overall_passed"] is True+ markdown = tier_manifest.render_markdown(payload)+ html = tier_manifest._render_html(tier_manifest.validate_manifest(payload))+ assert "benchmarks/skill-001/BENCHMARK.md" in markdown+ assert "benchmarks/skill-001/BENCHMARK.md" in html+ assert "Publication" in markdown and "incomplete" in markdown+++ "change",+ [+ {"benchmark_md": "../BENCHMARK.md"},+ {"benchmark_md": "https://other.example/card"},+ {"benchmark_md": "benchmarks/skill-002/BENCHMARK.md"},+ {"path": "skills/foreign"},+ {"eligible": True},+ {"publication_status": "successful"},+ ],+)+def test_benchmark_links_reject_unsafe_foreign_or_contradictory_entries(change):+ payload = with_card()+ payload["benchmarks"][0].update(change)+ with pytest.raises(ValueError):+ tier_manifest.validate_manifest(payload)+++def test_duplicate_card_targets_are_rejected():+ payload = with_card()+ payload["benchmarks"].append(card())+ with pytest.raises(ValueError):+ tier_manifest.validate_manifest(payload)diff --git a/tests/ci/test_benchmark_reports.py b/tests/ci/test_benchmark_reports.pynew file mode 100644index 00000000..e3bde746--- /dev/null+++ b/tests/ci/test_benchmark_reports.py@@ -0,0 +1,387 @@+# SPDX-License-Identifier: Apache-2.0+"""Combined cards use retained evidence and exact manifest skill identities."""++import copy+import json+from pathlib import Path++import pytest++from ci import benchmark_reports+from skillevaluator.models import ValidationResult+from skillevaluator.publication_evidence import stamp_publication_evidence, tier1_required_checks+from skillevaluator.reporting import JSONReporter+from skillevaluator.reporting.retained import retained_results+++def results(tier, name="demo", *, digest="a", verdict="pass"):+ target = {+ "skill_name": name,+ "skill_digest": "sha256:" + digest * 64,+ "skill_digest_algorithm": "skill-evaluator-source-tree/2",+ }+ if tier == 1:+ checks = tier1_required_checks(skill_like=True)+ rows = []+ for check in checks:+ row = ValidationResult(validator_name=check.upper())+ row.add_success(check, "Completed")+ stamp_publication_evidence([row], tier=1, check_id=check)+ row.metadata["tier1_required_checks"] = checks+ rows.append(row)+ elif tier == 2:+ rows = [ValidationResult(validator_name="Similarity Check")]+ rows[0].add_success("similarity", "Completed")+ stamp_publication_evidence(rows, tier=2, check_id="similarity")+ else:+ score = 0.9 if verdict == "pass" else 0.2+ coverage = {+ "execution_status": "succeeded",+ "execution_errors": [],+ "expected_attempts": 2,+ "scored_attempts": 2,+ }+ summary = {+ **coverage,+ "skill_name": name,+ "verdict": verdict,+ "run_id": "retained-live-run",+ "publication_target": target,+ "environment": "docker",+ "agents_run": ["codex"],+ "best_agent": "codex",+ "overall_score": score,+ "overall_lift": score - 0.4,+ }+ agent = {+ **coverage,+ "model": "gpt-codex",+ "baseline": 0.4,+ "with_skill": score,+ "lift": score - 0.4,+ "conditions": {+ condition: {**coverage, "expected_attempts": 1, "scored_attempts": 1}+ for condition in ("with_skill", "without_skill")+ },+ "dimensions": [+ {"id": dimension, "with_skill": score, "baseline": 0.4, "lift": score - 0.4}+ for dimension in ("security", "correctness", "discoverability", "effectiveness", "efficiency")+ ],+ }+ row = ValidationResult(validator_name="AGENT_EVAL")+ row.add_success("agent_eval", "Completed")+ row.metadata["agent_eval"] = {+ **summary,+ "summary": summary,+ "evaluated_at": "2026-08-25T12:00:00+00:00",+ "evaluator_version": "0.9.0",+ "agents": {"codex": agent},+ "dimensions": agent["dimensions"],+ "dataset_summary": {"total_tasks": 1},+ "dataset_digest": "sha256:" + "b" * 64,+ "dataset_digest_algorithm": "skill-evaluator-dataset-snapshot/1",+ "attempt_policy": {"max_attempts": 1, "pass_threshold": 0.5, "stop_on_pass": False},+ }+ rows = [row]+ for row in rows:+ row.metadata["publication_target"] = copy.deepcopy(target)+ row.metadata["gating"] = {"tier": tier, "blocking": tier == 1}+ return rows+++def retain(reports, *, names=("demo",), tiers=(1, 2, 3), verdict="pass"):+ manifest = {"tiers": []}+ for tier in tiers:+ record = {"tier": tier, "required": tier == 1, "status": "passed", "skills": []}+ for index, name in enumerate(names, 1):+ relative = f"tier{tier}/skill-{index:03}/skillevaluator-tier{tier}.json"+ destination = reports / relative+ destination.parent.mkdir(parents=True, exist_ok=True)+ destination.write_text(+ JSONReporter(include_timestamp=False).render_all(results(tier, name, verdict=verdict))+ )+ record["skills"].append(+ {+ "path": f"skills/{name}",+ "status": "failed" if tier == 3 and verdict == "fail" else "passed",+ "report_json": relative,+ }+ )+ manifest["tiers"].append(record)+ return manifest+++def read_combined(reports, row):+ assert row["combined_json"].startswith("benchmarks/skill-")+ assert row["benchmark_md"].endswith("/BENCHMARK.md")+ combined = json.loads((reports / row["combined_json"]).read_text())+ card = (reports / row["benchmark_md"]).read_text()+ assert row["publication_status"] == combined["publication_status"]+ assert row["eligible"] == combined["publication"]["eligible"]+ return combined, card+++def test_complete_retained_reports_preserve_run_owned_evidence(tmp_path):+ manifest = retain(tmp_path)+ original = json.loads((tmp_path / manifest["tiers"][2]["skills"][0]["report_json"]).read_text())+ rows = benchmark_reports.write_benchmark_reports(tmp_path, manifest)+ combined, card = read_combined(tmp_path, rows[0])+ assert rows[0]["path"] == "skills/demo"+ assert combined["publication_status"] == "pass"+ assert "Overall verdict: PASS" in card+ assert combined["tier3"] == original["tier3"]+ assert combined["results"][-1]["publication_target"] == original["results"][0]["publication_target"]+++def test_reordered_rows_compose_by_exact_skill_path(tmp_path):+ manifest = retain(tmp_path, names=("second", "demo"))+ manifest["tiers"][1]["skills"].reverse()+ rows = benchmark_reports.write_benchmark_reports(tmp_path, manifest)+ assert [row["path"] for row in rows] == ["skills/demo", "skills/second"]+ for row in rows:+ combined, _ = read_combined(tmp_path, row)+ assert combined["publication_status"] == "pass"+ assert {result["publication_target"]["skill_name"] for result in combined["results"]} == {+ Path(row["path"]).name+ }++[email protected]("tiers", [(1,), (2, 3), (1, 3)])+def test_missing_tiers_stay_publication_required(tmp_path, tiers):+ manifest = retain(tmp_path, tiers=tiers)+ combined, card = read_combined(tmp_path, benchmark_reports.write_benchmark_reports(tmp_path, manifest)[0])+ assert combined["publication_status"] == "incomplete"+ assert combined["benchmark_policy"] == {"tier2_required": True, "tier3_required": True}+ assert "Overall verdict: INCOMPLETE" in card++[email protected]("change", ["digest", "name", "case"])+def test_foreign_source_cannot_certify_card(tmp_path, change):+ manifest = retain(tmp_path)+ path = tmp_path / manifest["tiers"][1]["skills"][0]["report_json"]+ name = {"name": "foreign", "case": "Demo"}.get(change, "demo")+ path.write_text(+ JSONReporter(include_timestamp=False).render_all(results(2, name, digest="c" if change == "digest" else "a"))+ )+ combined, card = read_combined(tmp_path, benchmark_reports.write_benchmark_reports(tmp_path, manifest)[0])+ assert combined["publication_status"] == "incomplete"+ assert "Overall verdict: INCOMPLETE" in card+++def test_native_advisory_quality_failure_does_not_block_ci(tmp_path):+ manifest = retain(tmp_path, verdict="fail")+ combined, card = read_combined(tmp_path, benchmark_reports.write_benchmark_reports(tmp_path, manifest)[0])+ assert combined["overall_passed"] is True+ assert combined["publication_status"] == "fail"+ assert "Overall verdict: FAIL" in card+++def test_incomplete_manifest_cannot_reuse_pass_report(tmp_path):+ manifest = retain(tmp_path)+ manifest["tiers"][2]["skills"][0]["status"] = "incomplete"+ combined, card = read_combined(tmp_path, benchmark_reports.write_benchmark_reports(tmp_path, manifest)[0])+ assert combined["overall_passed"] is True+ assert combined["publication_status"] == "incomplete"+ assert "Overall verdict: INCOMPLETE" in card++[email protected]("unsafe", ["../outside.json", "/tmp/outside.json", "tier2/link/report.json"])+def test_report_paths_cannot_escape_retained_root(tmp_path, unsafe):+ manifest = retain(tmp_path)+ outside = tmp_path.parent / "benchmark-outside"+ outside.mkdir(exist_ok=True)+ (tmp_path / "tier2/link").symlink_to(outside, target_is_directory=True)+ manifest["tiers"][1]["skills"][0]["report_json"] = unsafe+ combined, _ = read_combined(tmp_path, benchmark_reports.write_benchmark_reports(tmp_path, manifest)[0])+ assert combined["publication_status"] == "incomplete"+++def test_failed_manifest_cannot_publish_a_passed_native_report(tmp_path):+ manifest = retain(tmp_path)+ manifest["tiers"][1]["skills"][0]["status"] = "failed"+ combined, _ = read_combined(tmp_path, benchmark_reports.write_benchmark_reports(tmp_path, manifest)[0])+ assert combined["publication_status"] != "pass"+++def test_explicit_optional_policy_survives_without_deriving_it_from_ci_gate(tmp_path):+ manifest = retain(tmp_path, tiers=(1,))+ path = tmp_path / manifest["tiers"][0]["skills"][0]["report_json"]+ native = results(1)+ for result in native:+ result.metadata["benchmark_policy"] = {"tier2_required": False, "tier3_required": False}+ path.write_text(JSONReporter(include_timestamp=False).render_all(native))+ combined, _ = read_combined(tmp_path, benchmark_reports.write_benchmark_reports(tmp_path, manifest)[0])+ assert combined["benchmark_policy"] == {"tier2_required": False, "tier3_required": False}+ assert combined["publication_status"] == "pass"+++def test_selected_missing_row_is_incomplete_despite_optional_policy(tmp_path):+ manifest = retain(tmp_path, tiers=(1,))+ path = tmp_path / manifest["tiers"][0]["skills"][0]["report_json"]+ native = results(1)+ for result in native:+ result.metadata["benchmark_policy"] = {"tier2_required": False, "tier3_required": False}+ path.write_text(JSONReporter(include_timestamp=False).render_all(native))+ manifest["tiers"].append(+ {"tier": 2, "status": "incomplete", "required": False, "skills": [], "selected": ["skills/demo"]}+ )+ combined, _ = read_combined(tmp_path, benchmark_reports.write_benchmark_reports(tmp_path, manifest)[0])+ assert combined["publication_status"] == "incomplete"+++def test_legacy_tier1_without_required_lineup_stays_incomplete(tmp_path):+ manifest = retain(tmp_path)+ path = tmp_path / manifest["tiers"][0]["skills"][0]["report_json"]+ payload = json.loads(path.read_text())+ for result in payload["results"]:+ result.pop("tier1_required_checks", None)+ path.write_text(json.dumps(payload))+ combined, _ = read_combined(tmp_path, benchmark_reports.write_benchmark_reports(tmp_path, manifest)[0])+ assert combined["publication_status"] == "incomplete"+ assert all("tier1_required_checks" not in row for row in combined["results"])+++def test_corrupted_skipped_report_does_not_create_optional_waiver(tmp_path):+ manifest = retain(tmp_path, tiers=(1, 2))+ path = tmp_path / manifest["tiers"][0]["skills"][0]["report_json"]+ native = results(1)+ for result in native:+ result.metadata["benchmark_policy"] = {"tier2_required": False, "tier3_required": False}+ path.write_text(JSONReporter(include_timestamp=False).render_all(native))+ row = manifest["tiers"][1]["skills"][0]+ row["status"] = "skipped"+ (tmp_path / row["report_json"]).write_text("{broken")+ combined, _ = read_combined(tmp_path, benchmark_reports.write_benchmark_reports(tmp_path, manifest)[0])+ assert combined["publication_status"] == "incomplete"+++def test_native_tier2_failure_is_advisory_in_combined_ci_gate(tmp_path):+ manifest = retain(tmp_path)+ path = tmp_path / manifest["tiers"][1]["skills"][0]["report_json"]+ native = results(2)+ native[0].add_error("Similarity threshold exceeded")+ native[0].metadata["gating"]["blocking"] = True+ path.write_text(JSONReporter(include_timestamp=False).render_all(native))+ manifest["tiers"][1]["skills"][0]["status"] = "failed"+ combined, _ = read_combined(tmp_path, benchmark_reports.write_benchmark_reports(tmp_path, manifest)[0])+ assert combined["overall_passed"] is True+ assert combined["publication_status"] == "fail"+ assert combined["benchmark_policy"]["tier2_required"] is True+++def in_memory_reports(reports, manifest):+ return {+ row["report_json"]: json.loads((reports / row["report_json"]).read_text())+ for tier in manifest["tiers"]+ for row in tier["skills"]+ if row.get("report_json")+ }+++def test_in_memory_documents_match_disk_composition_without_mutating_inputs(tmp_path):+ manifest = retain(tmp_path)+ manifest.update(repository="acme/skills", commit="c" * 40, runtime={"tools_ref": "d" * 40})+ native = in_memory_reports(tmp_path, manifest)+ original = copy.deepcopy(native)+ documents = benchmark_reports.benchmark_documents(manifest, native)+ assert native == original+ assert len(documents) == 1+ document = documents[0]+ combined = json.loads(document["combined_content"])+ assert combined["publication_status"] == "pass"+ assert combined["evaluated_source"] == {+ "repository": "acme/skills",+ "commit": "c" * 40,+ "evaluator_container_revision": "d" * 40,+ }+ assert "- Evaluated source: `acme/skills`" in document["benchmark_content"]+ assert "- Evaluated source revision: `" + "c" * 40 + "`" in document["benchmark_content"]+ assert "- Evaluator container revision: `" + "d" * 40 + "`" in document["benchmark_content"]+ rows = benchmark_reports.write_benchmark_reports(tmp_path, manifest)+ assert rows == [{key: value for key, value in document.items() if not key.endswith("_content")}]+ assert (tmp_path / rows[0]["combined_json"]).read_text() == document["combined_content"]+ assert (tmp_path / rows[0]["benchmark_md"]).read_text() == document["benchmark_content"]++[email protected]("tools_ref", [None, "main", "0123456"])+def test_missing_or_mutable_tools_ref_never_invents_evaluator_revision(tmp_path, tools_ref):+ manifest = retain(tmp_path)+ manifest.update(repository="acme/skills", commit="c" * 40, runtime={"tools_ref": tools_ref})+ document = benchmark_reports.benchmark_documents(manifest, in_memory_reports(tmp_path, manifest))[0]+ assert "- Evaluator container revision: not recorded" in document["benchmark_content"]+ assert json.loads(document["combined_content"])["evaluated_source"] == {+ "repository": "acme/skills",+ "commit": "c" * 40,+ }+++ "field,value",+ [+ ("repository", "foreign/skills"),+ ("commit", "e" * 40),+ ("commit", "malformed"),+ ("evaluator_container_revision", "f" * 40),+ ],+)+def test_conflicting_native_source_is_retained_and_marked_incomplete(tmp_path, field, value):+ manifest = retain(tmp_path)+ manifest.update(repository="acme/skills", commit="c" * 40, runtime={"tools_ref": "d" * 40})+ native = in_memory_reports(tmp_path, manifest)+ relative = manifest["tiers"][2]["skills"][0]["report_json"]+ foreign = {field: value}+ native[relative]["results"][0]["tier3"]["summary"]["evaluated_source"] = foreign+ original = copy.deepcopy(native)+ document = benchmark_reports.benchmark_documents(manifest, native)[0]+ combined = json.loads(document["combined_content"])+ assert native == original+ assert combined["publication_status"] == "incomplete"+ assert foreign in combined["evaluated_source_conflicts"]+ rehydrated = retained_results(combined)+ roundtrip = json.loads(JSONReporter(include_timestamp=False, expected_skill_name="demo").render_all(rehydrated))+ assert roundtrip["publication_status"] == "incomplete"+ assert roundtrip["publication"]["eligible"] is False+ assert "Overall verdict: INCOMPLETE" in document["benchmark_content"]+ assert "- Evaluated source: `acme/skills`" in document["benchmark_content"]++[email protected]("status", ["neutral", "skipped"])+def test_manifest_nonpass_status_cannot_publish_passed_native_evidence(tmp_path, status):+ manifest = retain(tmp_path)+ manifest["tiers"][2]["skills"][0]["status"] = status+ combined, card = read_combined(tmp_path, benchmark_reports.write_benchmark_reports(tmp_path, manifest)[0])+ assert combined["publication_status"] == "incomplete"+ assert "Overall verdict: INCOMPLETE" in card+++def test_consistent_native_neutral_status_is_not_replaced_by_incomplete(tmp_path):+ manifest = retain(tmp_path)+ native = in_memory_reports(tmp_path, manifest)+ row = manifest["tiers"][2]["skills"][0]+ row["status"] = "neutral"+ payload = native[row["report_json"]]+ payload["results"][0]["tier3"]["verdict"] = "neutral"+ payload["results"][0]["tier3"]["summary"]["verdict"] = "neutral"+ document = benchmark_reports.benchmark_documents(manifest, native)[0]+ combined = json.loads(document["combined_content"])+ assert combined["publication_status"] == "neutral"+ assert not any(result.get("incomplete_scans") for result in combined["results"])+++def test_consistent_optional_native_skip_stays_disclosed(tmp_path):+ manifest = retain(tmp_path, tiers=(1, 2))+ native = in_memory_reports(tmp_path, manifest)+ for result in native[manifest["tiers"][0]["skills"][0]["report_json"]]["results"]:+ result["benchmark_policy"] = {"tier2_required": False, "tier3_required": False}+ row = manifest["tiers"][1]["skills"][0]+ row["status"] = "skipped"+ skipped = results(2)[0]+ skipped.success_details.clear()+ skipped.summary.checks_performed = 0+ skipped.metadata.update(skipped=True, skip_reason="Comparison intentionally skipped by policy")+ native[row["report_json"]] = json.loads(JSONReporter(include_timestamp=False).render_all([skipped]))+ document = benchmark_reports.benchmark_documents(manifest, native)[0]+ combined = json.loads(document["combined_content"])+ assert combined["publication_status"] == "pass"+ assert "SKIPPED" in document["benchmark_content"]+ assert not any(result.get("incomplete_scans") for result in combined["results"])diff --git a/tests/ci/test_gateway_benchmark_workflows.py b/tests/ci/test_gateway_benchmark_workflows.pynew file mode 100644index 00000000..838065ac--- /dev/null+++ b/tests/ci/test_gateway_benchmark_workflows.py@@ -0,0 +1,213 @@+# SPDX-License-Identifier: Apache-2.0+"""Shared CI wiring for enriched security and independent live-agent models."""++import importlib.util+import subprocess+from pathlib import Path++import pytest+import yaml++ROOT = Path(__file__).parents[2]+++def workflow():+ return yaml.load((ROOT / ".github/workflows/evaluate-all-tiers.yml").read_text(), Loader=yaml.BaseLoader)+++def test_enriched_tier1_requires_admission_and_keeps_the_keyless_path():+ document = workflow()+ assert document["on"]["workflow_call"]["inputs"]["tier1-llm"]["default"] == "false"+ baseline = document["jobs"]["tier1"]+ assert baseline["with"]["llm"] == "false"+ assert "always()" in baseline["if"]+ assert "needs.eligibility.outputs.allowed" in baseline["with"]["artifact-name"]+ assert baseline["with"]["artifact-name"].endswith("|| 'skill-evaluator-tier1' }}")+ enriched = document["jobs"]["tier1-llm"]+ # A native local Tier 3 runner need not have Docker. Tier 1 keeps the+ # separate image-capable runner used by its keyless baseline.+ assert enriched["runs-on"] == "ubuntu-24.04"+ assert "inputs.tier1-llm" in enriched["if"]+ assert "needs.eligibility.outputs.allowed == 'true'" in enriched["if"]+ assert enriched["environment"] == "${{ inputs.environment }}"+ check = next(step for step in enriched["steps"] if step.get("id") == "current-head")+ evaluate = next(step for step in enriched["steps"] if "run_tier1_image.py" in step.get("run", ""))+ assert enriched["steps"].index(check) < enriched["steps"].index(evaluate)+ assert "steps.current-head.outputs.allowed == 'true'" in evaluate["if"]+ assert "secrets." not in str(check)+ assert "tier1-llm" in document["jobs"]["aggregate"]["needs"]+++def test_native_jobs_forward_gateway_settings_only_at_protected_execution_steps():+ document = workflow()+ inputs = document["on"]["workflow_call"]["inputs"]+ for name in ("base-url", "embedding-base-url", "tier3-provider", "tier3-model", "tier3-base-url", "agent-models"):+ assert inputs[name]["default"] == ""+ paid = document["jobs"]["paid-tiers"]+ assert paid["continue-on-error"] == "true"+ assert paid["env"]["SKILL_EVAL_TIER3_PROVIDER"] == "${{ inputs.tier3-provider }}"+ assert paid["env"]["SKILL_EVAL_AGENT_MODELS"] == "${{ inputs.agent-models }}"+ assert "secrets." not in str(paid["env"])+ for step in paid["steps"]:+ if "secrets.LLM_API_KEY" in str(step):+ assert "steps.current-head.outputs.allowed == 'true'" in step["if"]+ assert step["env"]["SKILL_EVAL_LLM_API_KEY"] == "${{ secrets.LLM_API_KEY }}"+++def test_gitlab_enrichment_is_protected_and_does_not_need_docker_in_docker():+ document = yaml.safe_load((ROOT / "ci/gitlab/all-tiers.yml").read_text())+ job = document["skill-evaluation-tier1-llm"]+ assert job["environment"]["name"] == "$SKILL_EVAL_ENVIRONMENT"+ assert job["services"] == []+ assert "tags" not in job # Use the existing untagged Tier 1 image runner.+ script = "\n".join(job["script"])+ assert script.index("eligible_gitlab.py") < script.index("run_tier1_image.py")+ assert "--in-image" in script+ rules = str(job["rules"])+ assert 'SKILL_EVAL_TIER1_LLM != "true"' in rules+ assert "CI_MERGE_REQUEST_SOURCE_PROJECT_ID != $CI_PROJECT_ID" in rules+ needs = document["skill-evaluation-aggregate"]["needs"]+ assert any(item["job"] == "skill-evaluation-tier1-llm" for item in needs)+++def _aggregate_selects_enriched(env):+ document = yaml.safe_load((ROOT / "ci/gitlab/all-tiers.yml").read_text())+ script = "\n".join(document["skill-evaluation-aggregate"]["script"])+ selection = script[script.index("enriched=false") : script.index('if [ "$enriched" = true ]')]+ result = subprocess.run(+ ["sh", "-c", "set -eu\n" + selection + 'printf %s "$enriched"'],+ env={"PATH": "/usr/bin:/bin", **env},+ capture_output=True,+ text=True,+ check=True,+ )+ return result.stdout == "true"+++ ("source", "admitted"),+ [("push", True), ("web", True), ("schedule", False), ("api", False), ("trigger", False), ("pipeline", False)],+)+def test_gitlab_enriched_tier1_matches_default_branch_admission(source, admitted):+ """Sources that admission rejects keep the keyless baseline instead of failing Tier 1."""+ env = {+ "SKILL_EVAL_TIER1_LLM": "true",+ "CI_PIPELINE_SOURCE": source,+ "CI_PROJECT_ID": "42",+ "CI_COMMIT_BRANCH": "main",+ "CI_DEFAULT_BRANCH": "main",+ "CI_COMMIT_REF_PROTECTED": "true",+ }+ assert _aggregate_selects_enriched(env) is admitted+ spec = importlib.util.spec_from_file_location("gate_sources", ROOT / "ci/eligible_gitlab.py")+ gate = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(gate)+ assert gate._default_branch_candidate({**env, "CI_COMMIT_SHA": "a" * 40}) is admitted+ document = yaml.safe_load((ROOT / "ci/gitlab/all-tiers.yml").read_text())+ default_rule = document["skill-evaluation-tier1-llm"]["rules"][-1]["if"]+ assert '$CI_PIPELINE_SOURCE == "push" || $CI_PIPELINE_SOURCE == "web"' in default_rule+++def test_gitlab_same_project_mr_still_selects_enriched_tier1():+ env = {+ "SKILL_EVAL_TIER1_LLM": "true",+ "CI_PIPELINE_SOURCE": "merge_request_event",+ "CI_PROJECT_ID": "42",+ "CI_MERGE_REQUEST_SOURCE_PROJECT_ID": "42",+ "CI_DEFAULT_BRANCH": "main",+ }+ assert _aggregate_selects_enriched(env)+ assert not _aggregate_selects_enriched({**env, "CI_MERGE_REQUEST_SOURCE_PROJECT_ID": "7"})+++def test_benchmark_publisher_is_separate_from_read_only_pr_feedback():+ document = yaml.load((ROOT / ".github/workflows/publish-benchmarks.yml").read_text(), Loader=yaml.BaseLoader)+ job = document["jobs"]["benchmarks"]+ assert document["permissions"]["contents"] == "write"+ assert "workflow_run" in job["if"] and "push" in job["if"] and "workflow_dispatch" in job["if"]+ assert "head_repository.full_name == github.repository" in job["if"]+ checkout = next(step for step in job["steps"] if step.get("uses", "").startswith("actions/checkout@"))+ assert checkout["with"]["ref"] == "${{ inputs.tools-ref }}"+ assert "pull_request.head" not in str(job)+ assert "secrets." not in str(job)+ feedback = yaml.load((ROOT / ".github/workflows/feedback-all-tiers.yml").read_text(), Loader=yaml.BaseLoader)+ assert feedback["permissions"]["contents"] == "read"+++def test_github_enriched_tier1_applies_the_keyless_scan_baselines():+ """The enriched gate evidence must honor security-baselines exactly like the keyless scan."""+ document = workflow()+ assert document["jobs"]["tier1"]["with"]["security-baselines"] == "${{ inputs.security-baselines }}"+ enriched = document["jobs"]["tier1-llm"]+ keyless = yaml.load((ROOT / ".github/workflows/evaluate-skills.yml").read_text(), Loader=yaml.BaseLoader)+ scan_env = next(+ step["env"] for step in keyless["jobs"]["tier1"]["steps"] if "POLICY_SOURCE_SHA" in step.get("env", {})+ )+ assert enriched["env"]["SECURITY_BASELINES"] == "${{ inputs.security-baselines }}"+ assert enriched["env"]["POLICY_SOURCE_SHA"] == scan_env["POLICY_SOURCE_SHA"]+ candidate = next(step for step in enriched["steps"] if step.get("with", {}).get("path") == "candidate")+ # The image cannot fetch, so baseline runs keep the policy commit's blobs.+ assert candidate["with"]["fetch-depth"] == "0"+ assert candidate["with"]["filter"] == "${{ !inputs.security-baselines && 'blob:none' || '' }}"+++def _run_gitlab_enriched(tmp_path, extra_env):+ import os++ document = yaml.safe_load((ROOT / "ci/gitlab/all-tiers.yml").read_text())+ script = "\n".join(document["skill-evaluation-tier1-llm"]["script"])+ workspace = tmp_path / "workspace"+ workspace.mkdir()+ bin_dir = tmp_path / "bin"+ bin_dir.mkdir()+ stub = bin_dir / "python"+ stub.write_text(+ "#!/bin/sh\n"+ 'case "$2" in\n'+ " */eligible_gitlab.py) exit 0 ;;\n"+ f" */prepare_security_baselines.py) printf '%s\\n' {'d' * 40}; exit 0 ;;\n"+ "esac\n"+ 'while [ "$#" -gt 0 ]; do\n'+ ' if [ "$1" = --reports ]; then shift; report_dir=$1; fi\n'+ " shift\n"+ "done\n"+ 'printf \'%s\\n%s\\n\' "$SECURITY_BASELINES" "${POLICY_SOURCE_SHA:-}" > "$report_dir/baselines.txt"\n'+ )+ stub.chmod(0o755)+ outer = {+ key: value+ for key, value in os.environ.items()+ if not key.startswith(("CI_", "GITLAB_", "SKILL_EVAL_"))+ and key not in {"SECURITY_BASELINES", "POLICY_SOURCE_SHA"}+ }+ env = {+ **outer,+ "PATH": str(bin_dir) + os.pathsep + os.environ["PATH"],+ "CI_PROJECT_DIR": str(workspace),+ "SKILL_EVAL_TOOLS_DIR": str(tmp_path / "tools"),+ "SKILL_EVAL_IMAGE": "ghcr.io/nvidia/skillevaluator-tier1@sha256:" + "a" * 64,+ **extra_env,+ }+ result = subprocess.run(["bash", "-c", script], env=env, capture_output=True, text=True, check=False)+ evidence = workspace / "skill-evaluator-enriched-tier1/baselines.txt"+ return result, evidence.read_text().splitlines() if evidence.exists() else None+++ ("extra", "expected"),+ [+ ({"SKILL_EVAL_SECURITY_BASELINES": "true"}, ["true", "d" * 40]),+ ({"SKILL_EVAL_SECURITY_BASELINES": "false", "POLICY_SOURCE_SHA": "a" * 40}, ["false", ""]),+ ({"POLICY_SOURCE_SHA": "a" * 40}, ["false", ""]),+ ],+)+def test_gitlab_enriched_tier1_applies_the_keyless_job_baselines(tmp_path, extra, expected):+ result, evidence = _run_gitlab_enriched(tmp_path, extra)+ assert result.returncode == 0, result.stderr+ assert evidence == expected+++def test_gitlab_enriched_tier1_rejects_noncanonical_baseline_opt_in(tmp_path):+ result, evidence = _run_gitlab_enriched(tmp_path, {"SKILL_EVAL_SECURITY_BASELINES": "TRUE"})+ assert result.returncode != 0+ assert evidence is Nonediff --git a/tests/ci/test_gitlab_admission_transport.py b/tests/ci/test_gitlab_admission_transport.pyindex b3078517..b0ec0aeb 100644--- a/tests/ci/test_gitlab_admission_transport.py+++ b/tests/ci/test_gitlab_admission_transport.py@@ -97,3 +97,33 @@ def test_admission_auth_failure_reports_only_numeric_status(mr_env, monkeypatch,assert module.main() == 2output = capsys.readouterr().outassert "HTTP 404" in output and "job-test-token" not in output++[email protected]("source", ["merge_request_event", "push"])[email protected]("read_token", [None, "read-only-test-token"])+def test_forbidden_current_head_check_explains_separate_read_token(mr_env, monkeypatch, capsys, source, read_token):+ module = gate()+ for key, value in {+ "CI_PIPELINE_SOURCE": source,+ "CI_COMMIT_BRANCH": "main",+ "CI_DEFAULT_BRANCH": "main",+ "CI_COMMIT_REF_PROTECTED": "true",+ }.items():+ monkeypatch.setenv(key, value)+ if read_token:+ monkeypatch.setenv("SKILLEVALUATOR_GITLAB_READ_TOKEN", read_token)++ class Opener:+ def open(self, request, *_args, **_kwargs):+ resource = "merge_requests/1" if source == "merge_request_event" else "repository/branches/main"+ assert request.full_url.endswith("/projects/42/" + resource)+ raise urllib.error.HTTPError(request.full_url, 403, "job-test-token read-only-test-token", {}, None)++ monkeypatch.setattr(module.urllib.request, "build_opener", lambda *_handlers: Opener())++ assert module.main() == 2+ output = capsys.readouterr().out+ assert "HTTP 403" in output+ assert "SKILLEVALUATOR_GITLAB_READ_TOKEN" in output+ assert "Reporter/read_api" in output+ assert "job-test-token" not in output and "read-only-test-token" not in outputdiff --git a/tests/ci/test_gitlab_default_head_admission.py b/tests/ci/test_gitlab_default_head_admission.pynew file mode 100644index 00000000..c0e80bd9--- /dev/null+++ b/tests/ci/test_gitlab_default_head_admission.py@@ -0,0 +1,183 @@+# SPDX-License-Identifier: Apache-2.0+"""Default-branch admission requires the live protected branch head."""++import importlib.util+import io+import json+import urllib.error+import urllib.request+from pathlib import Path++import pytest++ROOT = Path(__file__).parents[2]+SHA = "a" * 40+BRANCH = {"name": "main", "protected": True, "commit": {"id": SHA}}+++def gate(monkeypatch):+ spec = importlib.util.spec_from_file_location("default_gate", ROOT / "ci/eligible_gitlab.py")+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ env = {+ "CI_PIPELINE_SOURCE": "push",+ "CI_API_V4_URL": "https://gitlab.example.test/api/v4",+ "CI_PROJECT_ID": "42",+ "CI_COMMIT_SHA": SHA,+ "CI_COMMIT_BRANCH": "main",+ "CI_DEFAULT_BRANCH": "main",+ "CI_COMMIT_REF_PROTECTED": "true",+ "CI_JOB_TOKEN": "job-secret",+ "SKILLEVALUATOR_GITLAB_TOKEN": "publisher-secret",+ }+ monkeypatch.setattr(module.os, "environ", env)+ return module+++def fake_api(monkeypatch, gate, payload):+ real_builder = urllib.request.build_opener++ class HTTPS(urllib.request.HTTPSHandler):+ def https_open(self, request):+ assert request.full_url == (+ "https://gitlab.example.test/api/v4/projects/42/repository/branches/"+ + ("release%2Fstable%20%231" if gate.os.environ["CI_DEFAULT_BRANCH"] != "main" else "main")+ )+ assert request.timeout == 30+ headers = {+ key.lower(): value for key, value in request.header_items() if key.lower() not in {"host", "user-agent"}+ }+ read_token = gate.os.environ.get("SKILLEVALUATOR_GITLAB_READ_TOKEN")+ assert headers == ({"private-token": read_token} if read_token else {"job-token": "job-secret"})+ if isinstance(payload, Exception):+ raise payload+ response = io.BytesIO(payload)+ response.code = 200+ response.msg = "OK"+ response.info = dict+ return response++ def builder(*handlers):+ assert any(+ isinstance(handler, urllib.request.HTTPRedirectHandler)+ and handler.redirect_request(None, None, 302, "", {}, "https://elsewhere.test") is None+ for handler in handlers+ )+ return real_builder(*handlers, HTTPS())++ monkeypatch.setattr(gate.urllib.request, "build_opener", builder)++[email protected]("source", ["push", "web"])[email protected]("read_token", [None, "reader-secret"])+def test_current_protected_default_head_is_admitted(gate, monkeypatch, source, read_token):+ gate.os.environ["CI_PIPELINE_SOURCE"] = source+ if read_token:+ gate.os.environ["SKILLEVALUATOR_GITLAB_READ_TOKEN"] = read_token+ fake_api(monkeypatch, gate, json.dumps(BRANCH).encode())+ assert gate.main() == 0+++ "current",+ [+ None,+ {},+ {**BRANCH, "commit": {"id": "b" * 40}},+ {**BRANCH, "name": "other"},+ {**BRANCH, "protected": False},+ {**BRANCH, "protected": "true"},+ {**BRANCH, "commit": None},+ {**BRANCH, "commit": []},+ {**BRANCH, "commit": {}},+ ],+)+def test_unverified_stale_or_forged_branch_is_rejected(gate, current):+ assert not gate.eligible(gate.os.environ, current)+++ "payload",+ [+ {**BRANCH, "commit": {"id": "b" * 40}},+ {**BRANCH, "protected": False},+ [],+ None,+ ],+)+def test_live_branch_advance_or_unprotection_blocks_provider_admission(gate, monkeypatch, payload):+ fake_api(monkeypatch, gate, json.dumps(payload).encode())+ assert gate.main() == 2+++def test_branch_name_is_encoded_as_one_path_segment(gate, monkeypatch):+ gate.os.environ.update(CI_DEFAULT_BRANCH="release/stable #1", CI_COMMIT_BRANCH="release/stable #1")+ fake_api(monkeypatch, gate, json.dumps({**BRANCH, "name": "release/stable #1"}).encode())+ assert gate.main() == 0+++ "key,value",+ [+ ("CI_API_V4_URL", ""),+ ("CI_API_V4_URL", "http://gitlab.example.test/api/v4"),+ ("CI_API_V4_URL", "https://[email protected]/api/v4"),+ ("CI_API_V4_URL", "https://gitlab.example.test/api/v4?token=reader-secret"),+ ("CI_API_V4_URL", "https://[bad/api/v4"),+ ("CI_PROJECT_ID", ""),+ ("CI_DEFAULT_BRANCH", ""),+ ("CI_COMMIT_SHA", ""),+ ],+)+def test_invalid_or_missing_api_identity_fails_closed(gate, monkeypatch, key, value, capsys):+ gate.os.environ[key] = value+ monkeypatch.setattr(+ gate.urllib.request, "build_opener", lambda *_args: pytest.fail("invalid API must not be called")+ )+ assert gate.main() == 2+ assert "reader-secret" not in capsys.readouterr().out+++ "payload",+ [+ pytest.param(b"not json reader-secret", id="invalid-json"),+ pytest.param(b"x" * (1024 * 1024 + 1), id="oversized"),+ urllib.error.URLError("reader-secret publisher-secret job-secret"),+ urllib.error.HTTPError("https://reader-secret", 302, "publisher-secret", {}, None),+ ],+)+def test_transport_and_malformed_responses_fail_without_credential_leaks(gate, monkeypatch, capsys, payload):+ fake_api(monkeypatch, gate, payload)+ assert gate.main() == 2+ output = capsys.readouterr().out+ assert all(secret not in output for secret in ("reader-secret", "publisher-secret", "job-secret"))+++ "changes",+ [+ {"CI_COMMIT_BRANCH": "feature"},+ {"CI_COMMIT_REF_PROTECTED": "false"},+ {"CI_PIPELINE_SOURCE": "schedule"},+ {"CI_PIPELINE_SOURCE": "api"},+ {"CI_PIPELINE_SOURCE": "external_pull_request_event"},+ ],+)+def test_live_branch_cannot_override_pipeline_constraints(gate, monkeypatch, changes):+ gate.os.environ.update(changes)+ monkeypatch.setattr(+ gate.urllib.request, "build_opener", lambda *_args: pytest.fail("ineligible pipeline must not call API")+ )+ assert not gate.eligible(gate.os.environ, BRANCH)+ assert gate.main() == 2+++def test_refused_branch_read_names_the_read_token_remedy(gate, monkeypatch, capsys):+ fake_api(monkeypatch, gate, urllib.error.HTTPError("https://gitlab.example.test", 403, "Forbidden", {}, None))+ assert gate.main() == 2+ output = capsys.readouterr().out+ assert "default-branch head could not be verified (HTTP 403)" in output+ assert "SKILLEVALUATOR_GITLAB_READ_TOKEN" in output+ assert "job-secret" not in outputdiff --git a/tests/ci/test_gitlab_enriched_admission.py b/tests/ci/test_gitlab_enriched_admission.pynew file mode 100644index 00000000..b4dfbc05--- /dev/null+++ b/tests/ci/test_gitlab_enriched_admission.py@@ -0,0 +1,121 @@+# SPDX-License-Identifier: Apache-2.0+"""GitLab evidence selection must agree with provider-job admission."""++import os+import re+import subprocess+from pathlib import Path++import pytest+import yaml++ROOT = Path(__file__).parents[2]+++def config():+ return yaml.safe_load((ROOT / "ci/gitlab/all-tiers.yml").read_text())+++ params=[+ ("push", "42", "true", "true", True),+ ("web", "42", "true", "true", True),+ ("schedule", "42", "true", "true", False),+ ("api", "42", "true", "true", False),+ ("trigger", "42", "true", "true", False),+ ("pipeline", "42", "true", "true", False),+ ("merge_request_event", "42", "false", "true", True),+ ("merge_request_event", "99", "false", "true", False),+ ("push", "42", "false", "true", False),+ ("push", "42", "true", "false", False),+ ],+ ids=[+ "push",+ "web",+ "schedule",+ "api",+ "trigger",+ "pipeline",+ "same-project-mr",+ "fork-mr",+ "unprotected",+ "keyless",+ ],+)+def admission_case(request):+ source, project, protected, llm, enriched = request.param+ return {+ "PATH": os.environ["PATH"],+ "CI_PIPELINE_SOURCE": source,+ "CI_PROJECT_ID": "42",+ "CI_MERGE_REQUEST_SOURCE_PROJECT_ID": project,+ "CI_COMMIT_BRANCH": "" if source == "merge_request_event" else "main",+ "CI_DEFAULT_BRANCH": "main",+ "CI_COMMIT_REF_PROTECTED": protected,+ "SKILL_EVAL_TIER1_LLM": llm,+ }, enriched+++def job_enabled(job, env):+ # These rules use GitLab's string equality and boolean-expression subset,+ # which has the same semantics in bash's conditional expression syntax.+ conditions = []+ for rule in job["rules"]:+ expression = re.sub(r"\$([A-Z0-9_]+)", r'"${\1:-}"', rule["if"])+ status = 1 if rule.get("when") == "never" else 0+ conditions.append(f"if [[ {expression} ]]; then exit {status}; fi")+ result = subprocess.run(["bash", "-c", "\n".join([*conditions, "exit 1"])], env=env, check=False)+ assert result.returncode in {0, 1}+ return result.returncode == 0+++def route_evidence(config, env, workspace):+ script = "\n".join(config["skill-evaluation-aggregate"]["script"])+ routing = script[script.index("mkdir -p skill-evaluator-results/tier1") :]+ routing, separator, _ = routing.partition('python -I "$SKILL_EVAL_TOOLS_DIR/ci/run_tiers.py" aggregate')+ assert separator+ subprocess.run(["bash", "-euc", routing], cwd=workspace, env=env, check=True)+++def test_enriched_job_is_scheduled_only_for_supported_provider_admission(config, admission_case):+ env, enriched = admission_case++ assert job_enabled(config["skill-evaluation"], env)+ assert job_enabled(config["skill-evaluation-tier1-llm"], env) is enriched+++def test_aggregate_uses_keyless_evidence_when_provider_job_is_not_eligible(config, admission_case, tmp_path):+ env, enriched = admission_case+ baseline = tmp_path / "skill-evaluator-report"+ baseline.mkdir()+ (baseline / "evidence.txt").write_text("keyless")+ if enriched:+ authenticated = tmp_path / "skill-evaluator-enriched-tier1"+ authenticated.mkdir()+ (authenticated / "evidence.txt").write_text("enriched")++ route_evidence(config, env, tmp_path)++ assert (tmp_path / "skill-evaluator-results/tier1/evidence.txt").read_text() == (+ "enriched" if enriched else "keyless"+ )+++def test_eligible_enriched_run_never_substitutes_keyless_evidence(config, tmp_path):+ env = {+ "PATH": os.environ["PATH"],+ "CI_PIPELINE_SOURCE": "push",+ "CI_PROJECT_ID": "42",+ "CI_COMMIT_BRANCH": "main",+ "CI_DEFAULT_BRANCH": "main",+ "CI_COMMIT_REF_PROTECTED": "true",+ "SKILL_EVAL_TIER1_LLM": "true",+ }+ baseline = tmp_path / "skill-evaluator-report"+ baseline.mkdir()+ (baseline / "evidence.txt").write_text("keyless")++ route_evidence(config, env, tmp_path)++ assert list((tmp_path / "skill-evaluator-results/tier1").iterdir()) == []diff --git a/tests/ci/test_image_build.py b/tests/ci/test_image_build.pyindex 26f609a1..a84ada08 100644--- a/tests/ci/test_image_build.py+++ b/tests/ci/test_image_build.py@@ -166,19 +166,31 @@ def test_pull_requests_read_but_never_write_the_layer_cache():assert caller["permissions"] == {"contents": "read", "pull-requests": "read", "statuses": "read"}assert caller["secrets"] == {"NVSKILLS_CI_DISPATCH_TOKEN": "${{ secrets.NVSKILLS_CI_DISPATCH_TOKEN }}"}if "workflow_run" in triggers:- # The consumer listener calls only the immutable trusted publisher;+ # The consumer listener calls only the immutable trusted publishers;# it has no local steps, candidate checkout or image build/cache job.assert path.name == "skill-feedback-all-tiers.yml"assert set(triggers) == {"workflow_run"}- assert set(document["jobs"]) == {"feedback"}- caller = document["jobs"]["feedback"]- assert set(caller) == {"uses", "with"}- assert re.fullmatch(- r"NVIDIA/SkillEvaluator/\.github/workflows/feedback-all-tiers\.yml@[0-9a-f]{40}", caller["uses"]- )- source = caller["uses"].rsplit("@", 1)[1]- assert caller["with"]["tools-repository"] == "NVIDIA/SkillEvaluator"- assert caller["with"]["tools-ref"] == source+ publishers = {"feedback": "feedback-all-tiers.yml", "benchmarks": "publish-benchmarks.yml"}+ assert set(document["jobs"]) == set(publishers)+ feedback = document["jobs"]["feedback"]+ source = feedback["uses"].rsplit("@", 1)[1]+ for name, publisher in publishers.items():+ caller = document["jobs"][name]+ expected_keys = {"uses", "with", "permissions"} if name == "benchmarks" else {"uses", "with"}+ assert set(caller) == expected_keys+ assert re.fullmatch(+ rf"NVIDIA/SkillEvaluator/\.github/workflows/{re.escape(publisher)}@[0-9a-f]{{40}}",+ caller["uses"],+ )+ assert caller["uses"].rsplit("@", 1)[1] == source+ assert caller["with"]["tools-repository"] == "NVIDIA/SkillEvaluator"+ assert caller["with"]["tools-ref"] == source+ assert caller["with"] == feedback["with"]+ assert document["jobs"]["benchmarks"]["permissions"] == {+ "contents": "write",+ "actions": "read",+ "pull-requests": "write",+ }def test_release_builds_reuse_no_cached_layers():diff --git a/tests/ci/test_model_config.py b/tests/ci/test_model_config.pynew file mode 100644index 00000000..a35ffefc--- /dev/null+++ b/tests/ci/test_model_config.py@@ -0,0 +1,252 @@+# SPDX-License-Identifier: Apache-2.0+"""CI model routing keeps native models and provider credentials isolated."""++import pytest++from ci import run_tiers+++def test_gateway_chat_and_build_embeddings_use_only_selected_credentials():+ child = run_tiers.child_environment(+ {+ "PATH": "/bin",+ "SKILL_EVAL_PROVIDER": "nv_build",+ "SKILL_EVAL_MODEL": "nvidia/build-model",+ "SKILL_EVAL_TIER3_PROVIDER": "openai-compatible",+ "SKILL_EVAL_TIER3_MODEL": "gateway/judge",+ "SKILL_EVAL_TIER3_BASE_URL": "https://gateway.example/api/v1/",+ "SKILL_EVAL_LLM_API_KEY": "gateway-secret",+ "NVIDIA_API_KEY": "embedding-secret",+ "OPENAI_API_KEY": "ambient-secret",+ "ANTHROPIC_API_KEY": "ambient-secret",+ "OPENAI_BASE_URL": "https://ambient.example/v1",+ "GITHUB_TOKEN": "feedback-secret",+ "CI_JOB_TOKEN": "job-secret",+ },+ tier=3,+ )+ assert child["SKILL_EVAL_LLM_PROVIDER"] == "openai-compatible"+ assert child["SKILL_EVAL_LLM_MODEL"] == "gateway/judge"+ assert child["LLM_JUDGE_MODEL"] == "gateway/judge"+ assert child["SKILL_EVAL_LLM_BASE_URL"] == "https://gateway.example/api/v1"+ assert child["SKILL_EVAL_LLM_API_KEY"] == "gateway-secret"+ assert not any(key.startswith("SKILL_EVAL_EMBEDDING_") for key in child)+ assert "NVIDIA_API_KEY" not in child+ assert not set(child) & {"OPENAI_API_KEY", "ANTHROPIC_API_KEY", "OPENAI_BASE_URL", "GITHUB_TOKEN", "CI_JOB_TOKEN"}+++def test_changed_tier3_provider_does_not_inherit_build_model_or_api_root():+ from ci.model_config import model_environment++ child = model_environment(+ {+ "SKILL_EVAL_PROVIDER": "nv_build",+ "SKILL_EVAL_MODEL": "nvidia/build-model",+ "SKILL_EVAL_BASE_URL": "https://build.example/v1",+ "SKILL_EVAL_TIER3_PROVIDER": "openai",+ "SKILL_EVAL_TIER3_MODEL": "",+ "SKILL_EVAL_TIER3_BASE_URL": "",+ },+ 3,+ )+ assert child["SKILL_EVAL_LLM_PROVIDER"] == "openai"+ assert "SKILL_EVAL_LLM_MODEL" not in child+ assert "LLM_JUDGE_MODEL" not in child+ assert "SKILL_EVAL_LLM_BASE_URL" not in child+ assert "OPENAI_BASE_URL" not in child++[email protected]("tier", [1, 2, 3])+def test_empty_overrides_inherit_same_provider_and_models(tier):+ from ci.model_config import model_environment++ child = model_environment(+ {+ "SKILL_EVAL_PROVIDER": "openai-compatible",+ "SKILL_EVAL_MODEL": "catalog/exact-model",+ "SKILL_EVAL_BASE_URL": "https://gateway.example/v1",+ "SKILL_EVAL_TIER3_PROVIDER": "",+ "SKILL_EVAL_TIER3_MODEL": "",+ "SKILL_EVAL_TIER3_BASE_URL": "",+ "SKILL_EVAL_EMBEDDING_PROVIDER": "openai-compatible",+ "SKILL_EVAL_EMBEDDING_BASE_URL": "https://embedding.example/v1",+ "SKILL_EVAL_EMBEDDING_API_KEY": "embedding-secret",+ },+ tier,+ )+ assert child["SKILL_EVAL_LLM_MODEL"] == "catalog/exact-model"+ assert child["SKILL_EVAL_LLM_BASE_URL"] == "https://gateway.example/v1"+ if tier == 2:+ assert child["SKILL_EVAL_EMBEDDING_BASE_URL"] == "https://embedding.example/v1"+ assert child["SKILL_EVAL_EMBEDDING_API_KEY"] == "embedding-secret"+ else:+ assert not any(key.startswith("SKILL_EVAL_EMBEDDING_") for key in child)+ assert "SKILL_EVAL_LLM_API_KEY" not in child+++ "url",+ [+ "relative/v1",+ "https://user:[email protected]/v1",+ "https://example.com/v1?key=secret",+ "https://example.com/#secret",+ "https://example.com/\nsecret",+ "file:///secret",+ ],+)+def test_malformed_api_roots_have_fixed_secret_free_errors(url):+ from ci.model_config import model_environment++ with pytest.raises(ValueError) as error:+ model_environment({"SKILL_EVAL_PROVIDER": "openai-compatible", "SKILL_EVAL_BASE_URL": url}, 2)+ assert "secret" not in str(error.value)+ assert url not in str(error.value)+++def test_unselected_gateway_credentials_and_settings_are_removed():+ from ci.model_config import model_environment++ child = model_environment(+ {+ "SKILL_EVAL_PROVIDER": "nv_build",+ "NVIDIA_API_KEY": "selected",+ "SKILL_EVAL_LLM_API_KEY": "ambient",+ "SKILL_EVAL_EMBEDDING_API_KEY": "ambient",+ "SKILL_EVAL_EMBEDDING_BASE_URL": "invalid-ignored",+ "ANTHROPIC_BASE_URL": "invalid-ignored",+ },+ 2,+ )+ assert child["NVIDIA_API_KEY"] == "selected"+ assert not set(child) & {+ "SKILL_EVAL_LLM_API_KEY",+ "SKILL_EVAL_EMBEDDING_API_KEY",+ "SKILL_EVAL_EMBEDDING_BASE_URL",+ "ANTHROPIC_BASE_URL",+ }+++def test_agent_models_preserve_native_catalog_ids():+ from ci.model_config import agent_model_overrides++ assert agent_model_overrides(+ {+ "SKILL_EVAL_AGENT_MODELS": "claude-code=aws/anthropic/bedrock-claude-opus-5-5\ncodex=openai/openai/gpt-6.1-sol"+ }+ ) == (+ "claude-code=aws/anthropic/bedrock-claude-opus-5-5",+ "codex=openai/openai/gpt-6.1-sol",+ )+ assert agent_model_overrides({"SKILL_EVAL_AGENT_MODELS": "codex=Exact-ID,opencode=vendor/model"}) == (+ "codex=Exact-ID",+ "opencode=vendor/model",+ )+++ "value", ["unknown=foo", "codex=foo,codex=bar", "codex=", "codex=foo\x1b[31m", "codex=" + "x" * 257, "x" * 4097]+)+def test_invalid_agent_models_are_rejected_without_echo(value):+ from ci.model_config import agent_model_overrides++ with pytest.raises(ValueError) as error:+ agent_model_overrides({"SKILL_EVAL_AGENT_MODELS": value})+ assert value not in str(error.value)+++def test_tier1_specific_provider_uses_its_default_model():+ from ci.model_config import model_environment++ child = model_environment(+ {+ "SKILL_EVAL_PROVIDER": "nv_build",+ "SKILL_EVAL_MODEL": "tier2-model",+ "SKILL_EVAL_TIER1_PROVIDER": "openai",+ "SKILL_EVAL_TIER1_MODEL": "",+ },+ 1,+ )+ assert child["SKILL_EVAL_LLM_PROVIDER"] == "openai"+ assert "SKILL_EVAL_LLM_MODEL" not in child++[email protected]("tier", [1, 3])+ "embedding_settings",+ [+ {},+ {"SKILL_EVAL_EMBEDDING_PROVIDER": "unsupported"},+ {+ "SKILL_EVAL_EMBEDDING_PROVIDER": "openai-compatible",+ "SKILL_EVAL_EMBEDDING_BASE_URL": "invalid-unused-url",+ "SKILL_EVAL_EMBEDDING_MODEL": "invalid unused model",+ "SKILL_EVAL_EMBEDDING_API_KEY": "embedding-only-secret",+ },+ ],+)+def test_chat_only_tiers_do_not_require_or_forward_unused_embedding_routes(tier, embedding_settings):+ from ci.model_config import model_environment++ child = model_environment(+ {+ "SKILL_EVAL_PROVIDER": "openai-compatible",+ f"SKILL_EVAL_TIER{tier}_PROVIDER": "openai",+ f"SKILL_EVAL_TIER{tier}_MODEL": "",+ "OPENAI_API_KEY": "selected-chat-secret",+ **embedding_settings,+ },+ tier,+ )+ assert child["SKILL_EVAL_LLM_PROVIDER"] == "openai"+ assert child["OPENAI_API_KEY"] == "selected-chat-secret"+ assert not any(key.startswith("SKILL_EVAL_EMBEDDING_") for key in child)+ assert "SKILL_EVAL_LLM_API_KEY" not in child+++def test_tier2_still_requires_a_valid_selected_embedding_route():+ from ci.model_config import model_environment++ with pytest.raises(ValueError, match="Selected provider configuration is incomplete or invalid"):+ model_environment({"SKILL_EVAL_PROVIDER": "openai", "SKILL_EVAL_EMBEDDING_PROVIDER": "openai-compatible"}, 2)++[email protected]("tier", [1, 3])+def test_chat_only_tiers_keep_shared_chat_key_but_exclude_embedding_only_key(tier):+ from ci.model_config import model_environment++ child = model_environment(+ {+ "SKILL_EVAL_PROVIDER": "nv_build",+ "SKILL_EVAL_EMBEDDING_PROVIDER": "openai",+ "NVIDIA_API_KEY": "chat-key",+ "OPENAI_API_KEY": "embedding-only-key",+ },+ tier,+ )+ assert child["NVIDIA_API_KEY"] == "chat-key"+ assert "OPENAI_API_KEY" not in child++[email protected]("tier", [1, 3])+def test_chat_only_tiers_do_not_validate_an_unused_embedding_route(tier):+ """The Tier 1 image job receives no embedding settings and must not fail on them."""+ from ci.model_config import model_environment++ gateway = {+ "SKILL_EVAL_PROVIDER": "openai-compatible",+ f"SKILL_EVAL_TIER{tier}_PROVIDER": "openai",+ f"SKILL_EVAL_TIER{tier}_MODEL": "",+ "OPENAI_API_KEY": "chat-key",+ }+ child = model_environment(gateway, tier)+ assert child["SKILL_EVAL_LLM_PROVIDER"] == "openai"+ assert child["OPENAI_API_KEY"] == "chat-key"+ incomplete_embedding = {+ "SKILL_EVAL_PROVIDER": "nv_build",+ "SKILL_EVAL_EMBEDDING_PROVIDER": "openai-compatible",+ "NVIDIA_API_KEY": "chat-key",+ }+ assert model_environment(incomplete_embedding, tier)["SKILL_EVAL_LLM_PROVIDER"] == "nv_build"+ with pytest.raises(ValueError):+ model_environment(incomplete_embedding, 2)diff --git a/tests/ci/test_repository_skill_ci.py b/tests/ci/test_repository_skill_ci.pyindex 4f89cb10..a09108c0 100644--- a/tests/ci/test_repository_skill_ci.py+++ b/tests/ci/test_repository_skill_ci.py@@ -45,32 +45,50 @@ def test_repository_skill_checks_use_reviewed_full_three_tier_configuration():assert inputs["scan-mode"] == "auto"assert inputs["env-mode"] == "docker"assert inputs["min-score"] == "70"+ assert inputs["tier1-llm"] == "true"+ assert inputs["tier1-provider"] == "nv_build"+ assert inputs["tier1-model"] == "nvidia/nemotron-3.5-super-vl-120b-a12b"assert inputs["provider"] == inputs["embedding-provider"] == "nv_build"+ assert inputs["model"] == "nvidia/nemotron-3.5-lightning-30b-a3b"+ assert inputs["tier3-provider"] == "openai-compatible"+ assert inputs["tier3-base-url"] == "${{ vars.SKILL_EVAL_TIER3_BASE_URL }}"+ assert inputs["tier3-model"] == "us/aws/anthropic/eccn-claude-opus-4-8"+ assert inputs["agents"] == "codex,claude-code"+ assert inputs["agent-models"].splitlines() == [+ "codex=openai/openai/eccn-gpt-6.1-sol",+ "claude-code=aws/anthropic/eccn-claude-opus-5-5",+ ]assert inputs["environment"] == "skillevaluator"assert inputs["n-attempts"] == inputs["n-concurrent"] == "1"assert "tier3-required" not in inputs- assert job["secrets"] == {- key: "${{ secrets." + key + " }}" for key in ("OPENAI_API_KEY", "ANTHROPIC_API_KEY", "NVIDIA_API_KEY")- }+ secrets = {key: "${{ secrets." + key + " }}" for key in ("OPENAI_API_KEY", "ANTHROPIC_API_KEY", "NVIDIA_API_KEY")}+ secrets["LLM_API_KEY"] = "${{ secrets[vars.SKILL_EVAL_GATEWAY_SECRET] }}"+ assert job["secrets"] == secretsassert "steps" not in job-def test_repository_feedback_approves_exact_caller_and_preserves_public_publisher():+def test_repository_feedback_and_benchmarks_approve_exact_caller_and_preserve_public_publisher():feedback = workflow(FEEDBACK)assert feedback["on"] == {"workflow_run": {"workflows": [workflow(SCAN)["name"]], "types": ["completed"]}}assert feedback["permissions"] == {"contents": "read", "actions": "read", "pull-requests": "write"}+ assert set(feedback["jobs"]) == {"feedback", "benchmarks"}job = feedback["jobs"]["feedback"]# A consumer keeps its reviewed runtime when a later release descriptor changes.runtime = workflow(SCAN)["jobs"]["skills"]["with"]["tools-ref"]assert job["uses"] == ("NVIDIA/SkillEvaluator/.github/workflows/feedback-all-tiers.yml@" + runtime)- assert "steps" not in job- assert "secrets" not in job+ assert set(job) == {"uses", "with"}inputs = job["with"]+ assert inputs["tools-repository"] == "NVIDIA/SkillEvaluator"assert inputs["tools-ref"] == runtimeassert inputs["trusted-workflow-ref"] == workflow(SCAN)["jobs"]["skills"]["uses"]# Apply the checkout's clean filters exactly as committing the caller does.blob = subprocess.check_output(["git", "hash-object", "--path", SCAN, SCAN], cwd=ROOT, text=True).strip()assert inputs["trusted-caller-blobs"] == blob+ benchmarks = feedback["jobs"]["benchmarks"]+ assert set(benchmarks) == {"uses", "with", "permissions"}+ assert benchmarks["uses"] == ("NVIDIA/SkillEvaluator/.github/workflows/publish-benchmarks.yml@" + runtime)+ assert benchmarks["permissions"] == {"contents": "write", "actions": "read", "pull-requests": "write"}+ assert benchmarks["with"] == inputspublic = workflow(".github/workflows/feedback-all-tiers.yml")assert set(public["on"]) == {"workflow_call"}assert public["jobs"]["feedback"]["steps"]diff --git a/tests/ci/test_run_tier1_image.py b/tests/ci/test_run_tier1_image.pynew file mode 100644index 00000000..a416a019--- /dev/null+++ b/tests/ci/test_run_tier1_image.py@@ -0,0 +1,302 @@+# SPDX-License-Identifier: Apache-2.0+"""Exercise the trusted image boundary without Docker or paid model calls."""++import importlib+import os+import subprocess+import sys+from pathlib import Path++import pytest++IMAGE = "ghcr.io/nvidia/skillevaluator-tier1@sha256:" + "a" * 64+++def test_isolated_cli_help_uses_trusted_helpers_and_ignores_consumer_imports(tmp_path):+ consumer = tmp_path / "consumer"+ consumer.mkdir()+ marker = tmp_path / "consumer-code-ran"+ trap = f"from pathlib import Path\nPath({str(marker)!r}).write_text('executed')\nraise RuntimeError('consumer import trap')\n"+ for filename in ("model_config.py", "select_changed_skills.py", "sitecustomize.py"):+ (consumer / filename).write_text(trap)+ (consumer / "skillevaluator").mkdir()+ (consumer / "skillevaluator" / "__init__.py").write_text(trap)+ launcher = Path(__file__).resolve().parents[2] / "ci" / "run_tier1_image.py"+ completed = subprocess.run(+ [sys.executable, "-I", str(launcher), "--help"],+ cwd=consumer,+ env={**os.environ, "PYTHONPATH": str(consumer)},+ capture_output=True,+ text=True,+ timeout=30,+ check=False,+ )+ assert completed.returncode == 0, completed.stderr+ assert "--workspace" in completed.stdout+ assert "--in-image" in completed.stdout+ assert not marker.exists()+++def launch(tmp_path, monkeypatch):+ runner = importlib.import_module("ci.run_tier1_image")+ workspace = tmp_path / "candidate"+ workspace.mkdir()+ native_run = subprocess.run++ def git(*args):+ return native_run(+ ["git", "-C", str(workspace), *args], text=True, capture_output=True, check=True+ ).stdout.strip()++ git("init", "-q")+ git("config", "user.name", "Fixture")+ git("config", "user.email", "[email protected]")+ (workspace / "skills").mkdir()+ (workspace / "skills" / "SKILL.md").write_text("fixture")+ git("add", ".")+ git("commit", "-qm", "fixture")+ head = git("rev-parse", "HEAD")+ env = {+ "PATH": os.environ["PATH"],+ "REPORT_COMMIT": head,+ "DIFF_HEAD_SHA": head,+ "SKILL_EVAL_TIER1_PROVIDER": "anthropic",+ "ANTHROPIC_API_KEY": "selected-secret",+ "OPENAI_API_KEY": "unselected-secret",+ "GH_TOKEN": "publisher-secret",+ "CI_JOB_TOKEN": "gitlab-secret",+ "SKILL_EVAL_TIER1_MODEL": "claude-fixture",+ "PYTHONPATH": str(workspace),+ "LD_PRELOAD": "candidate.so",+ }+ monkeypatch.setattr(os, "environ", env)+ calls = []++ def execute(argv, **kwargs):+ calls.append((argv, kwargs))+ return subprocess.CompletedProcess(argv, 0)++ monkeypatch.setattr(runner.subprocess, "run", execute)+ reports = tmp_path / "reports"+ args = ["--workspace", str(workspace), "--reports", str(reports), "--image", IMAGE]+ return runner, args, calls, env, workspace, reports, git+++def test_docker_launch_is_hardened_and_maps_only_selected_key(launch):+ runner, args, calls, env, workspace, reports, _ = launch+ env.update(SKILL_EVAL_PATHS="skills", SKILL_EVAL_MIN_SCORE="81", SKILL_EVAL_SCAN_WORKERS="2")+ assert runner.main(args) == 0+ pull, run = calls+ assert pull[0][-2:] == ["pull", IMAGE]+ config = Path(pull[0][pull[0].index("--config") + 1])+ assert config != Path.home() / ".docker"+ assert not config.exists()+ assert "selected-secret" not in str(run[0])+ command, kwargs = run+ for flag in ("--read-only", "--cap-drop", "--security-opt", "--user"):+ assert flag in command+ assert "ALL" in command and "no-new-privileges" in command+ assert "/tmp:rw,nosuid,noexec,size=1g" in command+ assert "/audit-tmp:rw,nosuid,noexec,mode=1777,size=1g" in command+ assert f"type=bind,src={workspace},dst=/workspace,readonly" in command+ assert f"type=bind,src={reports},dst=/reports" in command+ assert command[-1] == IMAGE+ child = kwargs["env"]+ assert child["LLM_API_KEY"] == "selected-secret"+ assert child["LLM_PROVIDER"] == "anthropic"+ assert child["LLM_MODEL"] == "claude-fixture"+ assert child["LLM_ENABLED"] == "true"+ assert child["SCAN_MODE"] == "all"+ assert child["MIN_SCORE"] == "81" and child["SCAN_WORKERS"] == "2"+ assert (+ not {"GH_TOKEN", "CI_JOB_TOKEN", "OPENAI_API_KEY", "ANTHROPIC_API_KEY", "PYTHONPATH", "LD_PRELOAD"}+ & child.keys()+ )+ assert "LLM_API_KEY" not in pull[1]["env"]++[email protected]("mutation", ["missing-key", "wrong-head", "conflicting-head", "gateway", "base-url", "static"])+def test_invalid_llm_request_never_launches_or_exposes_keys(launch, mutation, capsys):+ runner, args, calls, env, *_ = launch+ if mutation == "missing-key":+ del env["ANTHROPIC_API_KEY"]+ elif mutation == "wrong-head":+ env["REPORT_COMMIT"] = env["DIFF_HEAD_SHA"] = "b" * 40+ elif mutation == "conflicting-head":+ env["DIFF_HEAD_SHA"] = "b" * 40+ elif mutation == "gateway":+ env.update(+ SKILL_EVAL_TIER1_PROVIDER="openai-compatible",+ SKILL_EVAL_TIER1_BASE_URL="https://example.invalid/v1",+ SKILL_EVAL_LLM_API_KEY="gateway-secret",+ )+ elif mutation == "base-url":+ env["SKILL_EVAL_TIER1_BASE_URL"] = "https://example.invalid/v1"+ else:+ env["SKILL_EVAL_TIER1_PROVIDER"] = "static"+ assert runner.main(args) == 1+ assert not calls+ output = capsys.readouterr()+ assert "secret" not in output.err + output.out++[email protected]("unsafe", ["inside", "parent", "symlink", "comma", "workspace-link"])+def test_unsafe_mount_paths_fail_before_launch(launch, unsafe):+ runner, args, calls, _, workspace, reports, _ = launch+ if unsafe == "inside":+ args[3] = str(workspace / "reports")+ elif unsafe == "parent":+ args[3] = str(workspace.parent)+ elif unsafe == "symlink":+ reports.symlink_to(workspace.parent, target_is_directory=True)+ elif unsafe == "comma":+ args[3] = str(reports.with_name("report,unsafe"))+ else:+ link = workspace.with_name("linked")+ link.symlink_to(workspace, target_is_directory=True)+ args[1] = str(link)+ assert runner.main(args) == 1+ assert not calls+++def test_in_image_invokes_installed_runner_outside_candidate(launch):+ runner, args, calls, env, workspace, reports, _ = launch+ env["PATH"] = str(workspace) + os.pathsep + env["PATH"]+ assert runner.main([*args, "--in-image"]) == 0+ assert len(calls) == 1+ argv, kwargs = calls[0]+ assert argv == [+ "/opt/skillevaluator/.venv/bin/python",+ "-E",+ "-s",+ "/opt/skillevaluator/ci/run_tier1.py",+ "--workspace",+ str(workspace),+ "--reports",+ str(reports),+ ]+ assert kwargs["cwd"] == "/opt/skillevaluator"+ assert kwargs["env"]["LLM_API_KEY"] == "selected-secret"+ assert "PYTHONPATH" not in kwargs["env"]+ assert str(workspace) not in kwargs["env"]["PATH"]+++def test_gateway_rejection_explains_immutable_image_limitation_without_endpoint(launch, capsys):+ runner, args, calls, env, *_ = launch+ env["SKILL_EVAL_TIER1_PROVIDER"] = "openai-compatible"+ assert runner.main(args) == 1+ assert not calls+ assert "default endpoints only" in capsys.readouterr().out++[email protected]("provider,key", [("openai", "OPENAI_API_KEY"), ("nv_build", "NVIDIA_API_KEY")])+def test_supported_provider_selects_its_own_credential(launch, provider, key):+ runner, args, calls, env, *_ = launch+ env.update(SKILL_EVAL_TIER1_PROVIDER=provider)+ env[key] = "provider-credential"+ assert runner.main(args) == 0+ assert calls[-1][1]["env"]["LLM_PROVIDER"] == provider+ assert calls[-1][1]["env"]["LLM_API_KEY"] == "provider-credential"+++def test_native_tier1_launch_does_not_require_the_tier2_gateway_route(launch):+ runner, args, calls, env, *_ = launch+ # The GitHub Tier 1 job intentionally does not receive Tier 2's gateway URL.+ env.update(+ SKILL_EVAL_PROVIDER="openai-compatible",+ SKILL_EVAL_TIER1_PROVIDER="openai",+ SKILL_EVAL_TIER1_MODEL="",+ OPENAI_API_KEY="selected-tier1-secret",+ )+ assert runner.main(args) == 0+ child = calls[-1][1]["env"]+ assert child["LLM_PROVIDER"] == "openai"+ assert child["LLM_API_KEY"] == "selected-tier1-secret"++[email protected]("mutation", ["dirty", "missing-base", "untrusted-image"])+def test_unverified_inputs_fail_before_credential_launch(launch, mutation):+ runner, args, calls, env, workspace, *_ = launch+ if mutation == "dirty":+ (workspace / "skills" / "SKILL.md").write_text("modified")+ elif mutation == "missing-base":+ env["GITHUB_EVENT_NAME"] = "pull_request"+ else:+ args[-1] = "ghcr.io/attacker/skillevaluator-tier1@sha256:" + "a" * 64+ assert runner.main(args) == 1+ assert not calls+++ "event", [{"GITHUB_EVENT_NAME": "pull_request"}, {"CI_PIPELINE_SOURCE": "merge_request_event"}]+)+def test_auto_changes_on_pr_and_mr_but_setup_changes_force_all(launch, event):+ runner, args, calls, env, workspace, _, git = launch+ base = env["REPORT_COMMIT"]+ (workspace / "skills" / "SKILL.md").write_text("changed")+ git("commit", "-qam", "skill")+ env.update(+ event, DIFF_BASE_SHA=base, REPORT_COMMIT=git("rev-parse", "HEAD"), DIFF_HEAD_SHA=git("rev-parse", "HEAD")+ )+ assert runner.main(args) == 0+ assert calls[-1][1]["env"]["SCAN_MODE"] == "changed"+ (workspace / ".github").mkdir()+ (workspace / ".github" / "config.yml").write_text("changed")+ git("add", ".")+ git("commit", "-qm", "setup")+ env.update(REPORT_COMMIT=git("rev-parse", "HEAD"), DIFF_HEAD_SHA=git("rev-parse", "HEAD"))+ assert runner.main(args) == 0+ assert calls[-1][1]["env"]["SCAN_MODE"] == "all"+++def test_runtime_exceptions_are_fixed_diagnostics(launch, monkeypatch, capsys):+ runner, args, *_ = launch++ def fail(*args, **kwargs):+ raise RuntimeError("selected-secret and consumer-controlled text")++ monkeypatch.setattr(runner.subprocess, "run", fail)+ assert runner.main(args) == 1+ assert "selected-secret" not in str(capsys.readouterr())+++def test_reviewed_baselines_reach_the_enriched_scan_only_when_opted_in(launch):+ """The enriched evidence replaces the keyless gate, so it applies the same baselines."""+ runner, args, calls, env, *_ = launch+ env.update(SECURITY_BASELINES="true", POLICY_SOURCE_SHA="c" * 40)+ assert runner.main(args) == 0+ command, kwargs = calls[-1]+ assert kwargs["env"]["SECURITY_BASELINES"] == "true"+ assert kwargs["env"]["POLICY_SOURCE_SHA"] == "c" * 40+ assert {"SECURITY_BASELINES", "POLICY_SOURCE_SHA"} <= {+ command[index + 1] for index, arg in enumerate(command) if arg == "--env"+ }+ calls.clear()+ env.update(SECURITY_BASELINES="false")+ assert runner.main(args) == 0+ child = calls[-1][1]["env"]+ assert child["SECURITY_BASELINES"] == "false"+ assert "POLICY_SOURCE_SHA" not in child # An inherited policy commit is never forwarded.+ calls.clear()+ del env["SECURITY_BASELINES"]+ assert runner.main(args) == 0+ assert calls[-1][1]["env"]["SECURITY_BASELINES"] == "false"+++ "baselines",+ [+ {"SECURITY_BASELINES": "TRUE"},+ {"SECURITY_BASELINES": "true"},+ {"SECURITY_BASELINES": "true", "POLICY_SOURCE_SHA": "main"},+ ],+)+def test_invalid_baseline_opt_in_fails_before_credential_launch(launch, baselines, capsys):+ runner, args, calls, env, *_ = launch+ env.pop("POLICY_SOURCE_SHA", None)+ env.update(baselines)+ assert runner.main(args) == 1+ assert not calls+ output = capsys.readouterr()+ assert "secret" not in output.err + output.outdiff --git a/tests/ci/test_run_tiers.py b/tests/ci/test_run_tiers.pyindex f0c5a14c..e83c9384 100644--- a/tests/ci/test_run_tiers.py+++ b/tests/ci/test_run_tiers.py@@ -107,6 +107,38 @@ def test_ci_chat_model_uses_native_agent_provider_resolution(consumer, tmp_path)assert options.model is None+def test_native_agent_models_survive_the_serialized_execution_boundary(consumer, tmp_path, monkeypatch):+ requested = "codex=openai/example-gpt\nclaude-code=anthropic/example-claude"+ observed = []+ doctors = []+ monkeypatch.setattr(run_tiers, "dataset_preflight", lambda _skill: {})++ def execute(args, **_kwargs):+ if "doctor" in args:+ doctors.append(args)+ return 0+ config_path = Path(args[args.index("--config") + 1])+ saved = json.loads(config_path.read_text())+ options = run_tiers.tier3_options(consumer / "skills/alpha", config_path.parent, saved)+ observed.append(options.agent_model)+ return 1 # No model calls; missing evidence must remain advisory.++ monkeypatch.setattr(run_tiers, "run_command", execute)+ environment = env_for(+ consumer,+ NVIDIA_API_KEY="fixture-build-key",+ SKILL_EVAL_AGENTS="codex,claude-code",+ SKILL_EVAL_AGENT_MODELS=requested,+ )+ assert run_tiers.evaluate(3, consumer, tmp_path / "reports", environment) == 0+ expected = tuple(requested.splitlines())+ assert observed == [expected, expected]+ checked = tuple(+ args[index + 1] for args in doctors for index, value in enumerate(args[:-1]) if value == "--agent-model"+ )+ assert checked == expected++def test_native_tier3_engine_failure_still_emits_incomplete_evidence(consumer, tmp_path, monkeypatch):from skillevaluator.evaluation.service import EvaluationServicediff --git a/tests/golden/cli_surface.json b/tests/golden/cli_surface.jsonindex ac8098fb..5864a331 100644--- a/tests/golden/cli_surface.json+++ b/tests/golden/cli_surface.json@@ -85,7 +85,8 @@"choices": ["openai","anthropic",- "nv_build"+ "nv_build",+ "openai-compatible"],"default": "openai","name": "provider",@@ -97,7 +98,8 @@{"choices": ["openai",- "nv_build"+ "nv_build",+ "openai-compatible"],"name": "embedding_provider","opts": [@@ -121,6 +123,114 @@"param_type": "option","type": "text"},+ {+ "default": "False",+ "is_flag": true,+ "name": "tier1_llm",+ "opts": [+ "--tier1-llm"+ ],+ "param_type": "option",+ "type": "boolean"+ },+ {+ "choices": [+ "openai",+ "anthropic",+ "nv_build"+ ],+ "name": "tier1_provider",+ "opts": [+ "--tier1-provider"+ ],+ "param_type": "option"+ },+ {+ "default": "",+ "name": "tier1_model",+ "opts": [+ "--tier1-model"+ ],+ "param_type": "option",+ "type": "text"+ },+ {+ "default": "",+ "name": "base_url",+ "opts": [+ "--base-url"+ ],+ "param_type": "option",+ "type": "text"+ },+ {+ "default": "",+ "name": "embedding_base_url",+ "opts": [+ "--embedding-base-url"+ ],+ "param_type": "option",+ "type": "text"+ },+ {+ "choices": [+ "openai",+ "anthropic",+ "nv_build",+ "openai-compatible"+ ],+ "name": "tier3_provider",+ "opts": [+ "--tier3-provider"+ ],+ "param_type": "option"+ },+ {+ "default": "",+ "name": "tier3_model",+ "opts": [+ "--tier3-model"+ ],+ "param_type": "option",+ "type": "text"+ },+ {+ "default": "",+ "name": "tier3_base_url",+ "opts": [+ "--tier3-base-url"+ ],+ "param_type": "option",+ "type": "text"+ },+ {+ "multiple": true,+ "name": "agent_model",+ "opts": [+ "--agent-model"+ ],+ "param_type": "option",+ "type": "text"+ },+ {+ "default": "SKILL_EVAL_LLM_API_KEY",+ "name": "gateway_secret",+ "opts": [+ "--gateway-secret"+ ],+ "param_type": "option",+ "type": "text"+ },+ {+ "default": "False",+ "is_flag": true,+ "name": "benchmark_pr",+ "opts": [+ "--benchmark-pr"+ ],+ "param_type": "option",+ "type": "boolean"+ },{"name": "agents","opts": [diff --git a/tests/reporting/test_retained_publication_scope.py b/tests/reporting/test_retained_publication_scope.pynew file mode 100644index 00000000..b9a3ff4e--- /dev/null+++ b/tests/reporting/test_retained_publication_scope.py@@ -0,0 +1,109 @@+# SPDX-License-Identifier: Apache-2.0+"""Retained Tier 1 scope cannot turn incomplete publication evidence into PASS."""++import json++import pytest++from skillevaluator.models import ValidationResult+from skillevaluator.publication_evidence import stamp_publication_evidence, tier1_required_checks+from skillevaluator.reporting.base import assess_publication+from skillevaluator.reporting.json_reporter import JSONReporter+from skillevaluator.reporting.retained import RetainedReportError, retained_results+++def _results(*, skill_like=True, omitted=None, unscanned=None):+ required = tier1_required_checks(skill_like=skill_like)+ results = []+ for check in required:+ if check == omitted:+ continue+ result = ValidationResult(validator_name=check.upper())+ result.add_success(check, "Validation completed")+ stamp_publication_evidence([result], tier=1, check_id=check)+ result.metadata.update(+ publication_target={+ "skill_name": "demo",+ "skill_digest": "sha256:" + "a" * 64,+ "skill_digest_algorithm": "skill-evaluator-source-tree/2",+ },+ benchmark_policy={"tier2_required": False, "tier3_required": False},+ tier1_required_checks=list(required),+ tier1_unscanned_paths=list(unscanned or []),+ )+ results.append(result)+ return results+++def _emit(results):+ return json.loads(JSONReporter(include_timestamp=False, expected_skill_name="demo").render_all(results))+++ ("options", "status"),+ [+ ({}, "pass"),+ ({"skill_like": False}, "pass"),+ ({"omitted": "security"}, "incomplete"),+ ({"unscanned": ["references/results"]}, "incomplete"),+ ],+ ids=["complete-skill", "complete-core", "omitted-required-check", "unscanned-content"],+)+def test_scope_roundtrip_preserves_publication_verdict(options, status):+ results = _results(**options)+ assessment = assess_publication(results, expected_skill_name="demo")+ assert assessment.status == status++ payload = _emit(results)+ restored = retained_results(payload)++ assert assess_publication(restored, expected_skill_name="demo") == assessment+ assert payload["publication_status"] == status+ assert _emit(restored)["publication"] == payload["publication"]+ for original, row, retained in zip(results, payload["results"], restored, strict=True):+ for key in ("tier1_required_checks", "tier1_unscanned_paths"):+ assert row[key] == original.metadata[key]+ assert retained.metadata[key] == original.metadata[key]+ assert retained.metadata[key] is not row[key]+++def test_contradictory_required_lineups_remain_incomplete_after_roundtrip():+ results = _results(skill_like=False)+ results[0].metadata["tier1_required_checks"] = tier1_required_checks(skill_like=True)+ assessment = assess_publication(results, expected_skill_name="demo")+ assert assessment.status == "incomplete"+ assert "Tier 1 did not run every required check: lint, quality, version." in assessment.reasons+ assert assess_publication(retained_results(_emit(results)), expected_skill_name="demo") == assessment++[email protected]("key", ["tier1_required_checks", "tier1_unscanned_paths"])+ "value",+ [None, "schema", {"schema": True}, [True], [1], [None], [""], ["x" * 4097], ["x"] * 20_001],+ ids=["null", "string", "object", "boolean-item", "number-item", "null-item", "empty-item", "long-item", "many"],+)+def test_retained_scope_rejects_malformed_or_unbounded_lists(key, value):+ payload = _emit(_results())+ payload["results"][0][key] = value+ with pytest.raises(RetainedReportError, match=f"{key}|Metadata list too large"):+ retained_results(payload)++[email protected]("key", ["tier1_required_checks", "tier1_unscanned_paths"])[email protected]("value", [None, "schema", [1], [""], ["x" * 4097], ["x"] * 20_001])+def test_json_scope_rejects_malformed_declarations_instead_of_dropping_them(key, value):+ results = _results()+ results[0].metadata[key] = value+ with pytest.raises(ValueError, match=key):+ _emit(results)+++def test_legacy_reports_without_scope_fields_remain_readable():+ results = _results()+ for result in results:+ result.metadata.pop("tier1_required_checks")+ result.metadata.pop("tier1_unscanned_paths")+ payload = _emit(results)+ restored = retained_results(payload)+ assert assess_publication(restored, expected_skill_name="demo").status == "pass"+ assert _emit(restored)["results"] == payload["results"]diff --git a/tests/test_ci_onboarding_all_tiers.py b/tests/test_ci_onboarding_all_tiers.pyindex 01e41159..5d879ae7 100644--- a/tests/test_ci_onboarding_all_tiers.py+++ b/tests/test_ci_onboarding_all_tiers.py@@ -272,8 +272,9 @@ def test_invalid_tier_selection_fails_before_writes(repository, all_release, tie@pytest.mark.parametrize("has_reusable_feedback", [False, True])[email protected]("benchmark_pr", [False, True])def test_github_setup_pr_is_api_only_and_preserves_checkout(- repository, all_release, monkeypatch, request, has_reusable_feedback+ repository, all_release, monkeypatch, request, has_reusable_feedback, benchmark_pr):import base64@@ -316,7 +317,13 @@ def test_github_setup_pr_is_api_only_and_preserves_checkout(monkeypatch.setattr(wizard, "github_api", api)# API commits upload raw bytes; local Git clean filters do not apply.monkeypatch.setattr(wizard, "committed_blob", lambda *_args: "0" * 40)- result = invoke(repository, all_release, "--mode", "pr", "--paths", "skills")+ if benchmark_pr:+ release = json.loads(all_release.read_text())+ release["capabilities"].append("ci-benchmark-pr-v1")+ all_release.write_text(json.dumps(release))+ result = invoke(+ repository, all_release, "--mode", "pr", "--paths", "skills", *(["--benchmark-pr"] if benchmark_pr else [])+ )assert result.exit_code == 0, result.outputassert "https://github.com/example-org/consumer/pull/1" in result.outputtree = next(payload for endpoint, payload in mutations if endpoint.endswith("/git/trees"))@@ -329,9 +336,11 @@ def test_github_setup_pr_is_api_only_and_preserves_checkout(setup = next(payload for endpoint, payload in mutations if endpoint.endswith("/pulls"))assert "Tier 1 required" in setup["body"]assert "Tier 2 and Tier 3 advisory" in setup["body"]- assert feedback["jobs"]["feedback"]["with"]["trusted-caller-blobs"] == wizard.blob_id(- texts[".github/workflows/skill-checks-all-tiers.yml"]- )+ assert set(feedback["jobs"]) == ({"feedback", "benchmarks"} if benchmark_pr else {"feedback"})+ for job in feedback["jobs"].values():+ assert job["with"]["trusted-caller-blobs"] == wizard.blob_id(+ texts[".github/workflows/skill-checks-all-tiers.yml"]+ )assert subprocess.check_output(["git", "-C", str(repository), "status", "--porcelain"]) == beforediff --git a/tests/test_ci_onboarding_model_routing.py b/tests/test_ci_onboarding_model_routing.pynew file mode 100644index 00000000..777d6d9a--- /dev/null+++ b/tests/test_ci_onboarding_model_routing.py@@ -0,0 +1,280 @@+"""Offline caller rendering and capability boundaries for CI model routing."""++import json+import subprocess++import pytest+import yaml+from click.testing import CliRunner++from skillevaluator import _ci_onboarding_all_tiers as all_tiers+from skillevaluator import ci_onboarding as wizard+from skillevaluator.cli import cli+from test_ci_onboarding import repository as _repository+from test_ci_onboarding_all_tiers import ALL_RELEASE, invoke++repository = _repository+++def routing_release(tmp_path, monkeypatch):+ path = tmp_path / "routing.json"+ path.write_text(json.dumps({**ALL_RELEASE, "capabilities": [*ALL_RELEASE["capabilities"], "ci-model-routing-v1"]}))+ monkeypatch.setattr(wizard, "github_api", lambda *_a, **_k: pytest.fail("offline setup contacted GitHub"))+ monkeypatch.setattr(all_tiers, "gitlab_api", lambda *_a, **_k: pytest.fail("offline setup contacted GitLab"))+ return path+++ROUTING = (+ "--provider",+ "openai-compatible",+ "--base-url",+ "https://gateway.example/v1",+ "--embedding-provider",+ "openai-compatible",+ "--embedding-base-url",+ "https://embed.example/v1",+ "--tier1-llm",+ "--tier1-provider",+ "anthropic",+ "--tier1-model",+ "claude-tier1",+ "--tier3-provider",+ "openai-compatible",+ "--tier3-model",+ "judge-tier3",+ "--tier3-base-url",+ "https://judge.example/v1",+ "--agent-model",+ "codex=gpt-agent",+ "--agent-model",+ "claude-code=claude-agent",+ "--gateway-secret",+ "TEAM_GATEWAY_KEY",+)+++def test_github_routing_preview_and_save_are_offline_and_thin(repository, routing_release):+ before = subprocess.check_output(["git", "-C", str(repository), "status", "--porcelain"])+ preview = invoke(repository, routing_release, "--mode", "preview", "--show-files", *ROUTING)+ assert preview.exit_code == 0, preview.output+ assert subprocess.check_output(["git", "-C", str(repository), "status", "--porcelain"]) == before+ saved = invoke(repository, routing_release, "--mode", "save", *ROUTING)+ assert saved.exit_code == 0, saved.output+ scan = yaml.safe_load((repository / all_tiers.SCAN).read_text())["jobs"]["skills"]+ assert scan["with"]["tier1-llm"] is True+ assert scan["with"]["tier1-provider"] == "anthropic"+ assert scan["with"]["tier1-model"] == "claude-tier1"+ assert scan["with"]["base-url"] == "https://gateway.example/v1"+ assert scan["with"]["embedding-base-url"] == "https://embed.example/v1"+ assert scan["with"]["tier3-provider"] == "openai-compatible"+ assert scan["with"]["tier3-model"] == "judge-tier3"+ assert scan["with"]["tier3-base-url"] == "https://judge.example/v1"+ assert scan["with"]["agent-models"] == "codex=gpt-agent\nclaude-code=claude-agent"+ assert scan["secrets"]["LLM_API_KEY"] == "${{ secrets.TEAM_GATEWAY_KEY }}"+ assert scan["secrets"]["EMBEDDING_API_KEY"] == "${{ secrets.SKILL_EVAL_EMBEDDING_API_KEY }}"+ assert scan["secrets"]["OPENAI_API_KEY"] == "${{ secrets.OPENAI_API_KEY }}"+ changed = subprocess.check_output(+ ["git", "-C", str(repository), "ls-files", "--others", "--exclude-standard"], text=True+ )+ assert sorted(changed.splitlines()) == sorted([all_tiers.SCAN, all_tiers.FEEDBACK])+ assert "steps" not in scan+++def test_gitlab_routing_uses_variables_and_custom_secret_alias(repository, routing_release):+ subprocess.run(+ ["git", "-C", str(repository), "remote", "set-url", "origin", "https://gitlab.example/group/consumer.git"],+ check=True,+ )+ result = invoke(repository, routing_release, "--mode", "save", *ROUTING)+ assert result.exit_code == 0, result.output+ variables = yaml.safe_load((repository / all_tiers.GL_SCAN).read_text())["variables"]+ assert variables["SKILL_EVAL_TIER1_LLM"] == "true"+ assert variables["SKILL_EVAL_TIER1_PROVIDER"] == "anthropic"+ assert variables["SKILL_EVAL_TIER1_MODEL"] == "claude-tier1"+ assert variables["SKILL_EVAL_BASE_URL"] == "https://gateway.example/v1"+ assert variables["SKILL_EVAL_EMBEDDING_BASE_URL"] == "https://embed.example/v1"+ assert variables["SKILL_EVAL_TIER3_PROVIDER"] == "openai-compatible"+ assert variables["SKILL_EVAL_TIER3_MODEL"] == "judge-tier3"+ assert variables["SKILL_EVAL_TIER3_BASE_URL"] == "https://judge.example/v1"+ assert variables["SKILL_EVAL_AGENT_MODELS"] == "codex=gpt-agent\nclaude-code=claude-agent"+ assert variables["SKILL_EVAL_LLM_API_KEY"] == "$TEAM_GATEWAY_KEY"+++ "args",+ [+ ("--tier1-llm",),+ ("--tier3-model", "judge"),+ ("--base-url", "https://gateway.example/v1"),+ ("--agent-model", "codex=gpt"),+ ("--provider", "openai-compatible"),+ ],+)+def test_old_pins_refuse_new_routing_before_writes(repository, tmp_path, args):+ release = tmp_path / "old.json"+ release.write_text(json.dumps(ALL_RELEASE))+ result = invoke(repository, release, "--mode", "save", *args)+ assert result.exit_code != 0+ assert "ci-model-routing-v1" in result.output+ assert not (repository / all_tiers.SCAN).exists()++[email protected]("secret", ["KEY }}\nX: injected", "bad-name", "1KEY", "secrets.KEY", "GITHUB_TOKEN"])+def test_secret_names_cannot_inject_caller_expressions(repository, routing_release, secret):+ result = invoke(repository, routing_release, "--mode", "save", "--gateway-secret", secret)+ assert result.exit_code != 0+ assert "secret" in result.output.lower()+ assert not (repository / all_tiers.SCAN).exists()++[email protected]("value", ["missing-equals", "codex=", "unknown=model", "codex=model\nother=bad"])+def test_invalid_agent_models_fail_before_files(repository, routing_release, value):+ result = invoke(repository, routing_release, "--mode", "save", "--agent-model", value)+ assert result.exit_code != 0+ assert not (repository / all_tiers.SCAN).exists()+++def test_new_settings_require_all_tier_opt_in(repository, routing_release):+ result = CliRunner().invoke(+ cli,+ [+ "ci",+ "init",+ "--repo",+ str(repository),+ "--release",+ str(routing_release),+ "--no-input",+ "--mode",+ "save",+ "--tier1-llm",+ ],+ )+ assert result.exit_code != 0+ assert "--tier1-llm" in result.output and "--tiers 1,2,3" in result.output+++ "args, expected",+ [+ ((), {}),+ (("--tier1-llm",), {}),+ (+ ("--tier3-provider", "openai-compatible", "--tier3-base-url", "https://gateway.example/v1"),+ {"LLM_API_KEY": "${{ secrets.SKILL_EVAL_LLM_API_KEY }}"},+ ),+ (+ ("--embedding-provider", "openai-compatible", "--embedding-base-url", "https://embed.example/v1"),+ {"EMBEDDING_API_KEY": "${{ secrets.SKILL_EVAL_EMBEDDING_API_KEY }}"},+ ),+ ],+)+def test_generic_secrets_are_only_exposed_to_selected_routes(repository, routing_release, args, expected):+ result = invoke(repository, routing_release, "--mode", "save", *args)+ assert result.exit_code == 0, result.output+ job = yaml.safe_load((repository / all_tiers.SCAN).read_text())["jobs"]["skills"]+ assert {+ key: value for key, value in job["secrets"].items() if key in {"LLM_API_KEY", "EMBEDDING_API_KEY"}+ } == expected+ if not args:+ assert not set(job["with"]) & {"tier1-llm", "base-url", "tier3-model", "agent-models"}+++def test_duplicate_agent_model_is_rejected_locally(repository, routing_release):+ result = invoke(+ repository, routing_release, "--mode", "save", "--agent-model", "codex=one", "--agent-model", "codex=two"+ )+ assert result.exit_code != 0+ assert "only one model" in result.output+ assert not (repository / all_tiers.SCAN).exists()+++def test_native_routing_does_not_alias_an_unused_gateway_secret(repository, routing_release):+ subprocess.run(+ ["git", "-C", str(repository), "remote", "set-url", "origin", "https://gitlab.example/group/consumer.git"],+ check=True,+ )+ result = invoke(repository, routing_release, "--mode", "save", "--gateway-secret", "UNUSED_GATEWAY")+ assert result.exit_code == 0, result.output+ variables = yaml.safe_load((repository / all_tiers.GL_SCAN).read_text())["variables"]+ assert "SKILL_EVAL_LLM_API_KEY" not in variables+++def test_default_gateway_key_needs_no_gitlab_self_alias(repository, routing_release):+ subprocess.run(+ ["git", "-C", str(repository), "remote", "set-url", "origin", "https://gitlab.example/group/consumer.git"],+ check=True,+ )+ result = invoke(+ repository,+ routing_release,+ "--mode",+ "save",+ "--provider",+ "openai-compatible",+ "--base-url",+ "https://gateway.example/v1",+ )+ assert result.exit_code == 0, result.output+ variables = yaml.safe_load((repository / all_tiers.GL_SCAN).read_text())["variables"]+ assert "SKILL_EVAL_LLM_API_KEY" not in variables+++def test_tier1_llm_job_override_is_recognized_as_an_evaluator_job():+ assert all_tiers.gitlab_unguarded_jobs("skill-evaluation-tier1-llm:\n tags: [cpu]\n") == []+++def benchmark_release(tmp_path):+ path = tmp_path / "benchmark.json"+ path.write_text(json.dumps({**ALL_RELEASE, "capabilities": [*ALL_RELEASE["capabilities"], "ci-benchmark-pr-v1"]}))+ return path+++def test_benchmark_pr_adds_only_a_pinned_job_to_existing_feedback_file(repository, benchmark_release, monkeypatch):+ monkeypatch.setattr(wizard, "github_api", lambda *_a, **_k: pytest.fail("offline setup contacted GitHub"))+ result = invoke(repository, benchmark_release, "--mode", "save", "--benchmark-pr")+ assert result.exit_code == 0, result.output+ feedback = yaml.safe_load((repository / all_tiers.FEEDBACK).read_text())+ assert feedback["permissions"] == {"actions": "read", "contents": "read", "pull-requests": "write"}+ assert set(feedback["jobs"]) == {"feedback", "benchmarks"}+ benchmarks = feedback["jobs"]["benchmarks"]+ assert benchmarks["uses"] == "NVIDIA/SkillEvaluator/.github/workflows/publish-benchmarks.yml@" + "d" * 40+ assert benchmarks["permissions"] == {"actions": "read", "contents": "write", "pull-requests": "write"}+ assert benchmarks["with"] == feedback["jobs"]["feedback"]["with"]+ assert benchmarks["with"]["tools-ref"] == "f" * 40+ assert benchmarks["with"]["trusted-workflow-ref"].endswith("@" + ALL_RELEASE["workflow_ref"])+ changed = subprocess.check_output(+ ["git", "-C", str(repository), "ls-files", "--others", "--exclude-standard"], text=True+ )+ assert sorted(changed.splitlines()) == sorted([all_tiers.SCAN, all_tiers.FEEDBACK])+ assert "benchmark-pr" not in yaml.safe_load((repository / all_tiers.SCAN).read_text())["jobs"]["skills"]["with"]+++def test_benchmark_pr_requires_its_own_capability(repository, routing_release):+ result = invoke(repository, routing_release, "--mode", "save", "--benchmark-pr")+ assert result.exit_code != 0+ assert "ci-benchmark-pr-v1" in result.output+ assert not (repository / all_tiers.SCAN).exists()+++def test_benchmark_pr_refuses_gitlab_without_writing(repository, benchmark_release):+ subprocess.run(+ ["git", "-C", str(repository), "remote", "set-url", "origin", "https://gitlab.example/group/consumer.git"],+ check=True,+ )+ result = invoke(repository, benchmark_release, "--mode", "save", "--benchmark-pr")+ assert result.exit_code != 0+ assert "benchmark-update PR publication currently requires GitHub" in result.output+ assert "GitLab cards retained in reports" in result.output+ assert not (repository / all_tiers.GL_SCAN).exists()+++def test_benchmark_capability_alone_keeps_default_output_byte_identical(repository, benchmark_release, tmp_path):+ old_release = tmp_path / "old-default.json"+ old_release.write_text(json.dumps(ALL_RELEASE))+ before = invoke(repository, old_release, "--mode", "preview", "--show-files")+ after = invoke(repository, benchmark_release, "--mode", "preview", "--show-files")+ assert before.exit_code == after.exit_code == 0+ assert before.output == after.outputdiff --git a/tests/test_harbor_runner_status.py b/tests/test_harbor_runner_status.pyindex c64b2890..9ca3e2ae 100644--- a/tests/test_harbor_runner_status.py+++ b/tests/test_harbor_runner_status.py@@ -220,9 +220,40 @@ def test_bounded_harbor_process_contains_tree_after_stdin_delivery_error() -> Noassert time.monotonic() - started < 3-def test_bounded_harbor_process_timeout_preserves_redacted_diagnostic_tail() -> None:+def test_bounded_harbor_process_timeout_preserves_redacted_diagnostic_tail(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:secret = "synthetic-timeout-secret"- script = f"import os,time;os.write(2,{f'useful timeout diagnostic {secret}'.encode()!r});time.sleep(30)"+ ready_path = tmp_path / "diagnostic-ready"+ script = (+ "import os,pathlib,time;"+ f"os.write(2,{f'useful timeout diagnostic {secret}'.encode()!r});"+ f"pathlib.Path({str(ready_path)!r}).touch();"+ "time.sleep(30)"+ )+ real_popen = runner.subprocess.Popen++ def ready_popen(*args: object, **kwargs: object) -> object:+ process = real_popen(*args, **kwargs)+ # This test needs emitted output, not a guarantee that Python starts+ # within 100 ms on a loaded runner. Leave the real output pipe unread.+ deadline = time.monotonic() + 10+ try:+ while not ready_path.exists():+ if process.poll() is not None or time.monotonic() >= deadline:+ raise RuntimeError("diagnostic fixture did not become ready")+ time.sleep(0.01)+ except BaseException:+ if process.poll() is None:+ process.kill()+ process.wait(timeout=5)+ if process.stdout is not None:+ process.stdout.close()+ raise+ return process++ monkeypatch.setattr(runner.subprocess, "Popen", ready_popen)with pytest.raises(RuntimeError, match="timed out") as raised:runner._run_bounded_harbor_process(