Skip to content

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.

feat(ci): add three-tier onboarding and private report feedback (#349)

Narendran Raghavan86f1a1f05bc5
diff --git a/.github/workflows/evaluate-all-tiers.yml b/.github/workflows/evaluate-all-tiers.yml
new file mode 100644
index 00000000..138081c4
--- /dev/null
+++ b/.github/workflows/evaluate-all-tiers.yml
@@ -0,0 +1,401 @@
+# SPDX-License-Identifier: Apache-2.0
+name: Reusable three-tier skill evaluation
+on:
+ workflow_call:
+ inputs:
+ image:
+ description: Immutable legacy Tier 1 GHCR image
+ type: string
+ required: true
+ tools-repository:
+ type: string
+ default: NVIDIA/SkillEvaluator
+ tools-ref:
+ description: Reviewed 40-character evaluator commit
+ type: string
+ required: true
+ tiers:
+ type: string
+ default: '1,2,3'
+ paths:
+ type: string
+ default: skills
+ scan-mode:
+ type: string
+ default: auto
+ min-score:
+ type: number
+ default: 70
+ env-mode:
+ description: docker or local; cloud backends are not supported here
+ type: string
+ default: docker
+ provider:
+ type: string
+ default: openai
+ model:
+ type: string
+ default: ''
+ embedding-provider:
+ type: string
+ default: ''
+ embedding-model:
+ type: string
+ default: ''
+ agents:
+ type: string
+ default: ''
+ runner:
+ type: string
+ default: ubuntu-24.04
+ environment:
+ description: Execution environment with optional repository-configured reviewers
+ type: string
+ default: skillevaluator
+ tier3-required:
+ description: Deprecated and ignored; Tier 2 and Tier 3 are always advisory
+ type: boolean
+ default: false
+ n-attempts:
+ type: number
+ default: 1
+ n-concurrent:
+ type: number
+ default: 1
+ timeout-minutes:
+ type: number
+ default: 300
+ secrets:
+ OPENAI_API_KEY:
+ required: false
+ ANTHROPIC_API_KEY:
+ required: false
+ NVIDIA_API_KEY:
+ required: false
+permissions:
+ contents: read
+ id-token: write
+jobs:
+ tier1:
+ needs: eligibility
+ if: ${{ always() && contains(format(',{0},', inputs.tiers), ',1,') }}
+ uses: ./.github/workflows/evaluate-skills.yml
+ with:
+ image: ${{ inputs.image }}
+ paths: ${{ inputs.paths }}
+ min-score: ${{ inputs.min-score }}
+ scan-mode: ${{ needs.eligibility.outputs.scan-mode || inputs.scan-mode }}
+ artifact-name: skill-evaluator-tier1
+ llm: false
+ eligibility:
+ runs-on: ubuntu-24.04
+ permissions:
+ contents: read
+ pull-requests: read
+ outputs:
+ allowed: ${{ steps.check.outputs.allowed }}
+ scan-mode: ${{ steps.check.outputs.scan-mode }}
+ steps:
+ - name: Check immutable configuration and current same-repository PR head
+ id: check
+ env:
+ GH_TOKEN: ${{ github.token }}
+ API_URL: ${{ github.api_url }}
+ TOOLS_REF: ${{ inputs.tools-ref }}
+ ENV_MODE: ${{ inputs.env-mode }}
+ TIERS: ${{ inputs.tiers }}
+ SCAN_MODE: ${{ inputs.scan-mode }}
+ run: |
+ python3 -I - <<'PY'
+ import json, os, re, urllib.parse, urllib.request
+ if not re.fullmatch(r'[0-9a-f]{40}', os.environ['TOOLS_REF']):
+ raise SystemExit('tools-ref must be a reviewed immutable 40-character commit')
+ if os.environ['ENV_MODE'] not in ('docker', 'local'):
+ raise SystemExit('CI supports env-mode docker or local only')
+ tiers = os.environ['TIERS'].split(',')
+ if not tiers or len(set(tiers)) != len(tiers) or any(t not in ('1','2','3') for t in tiers):
+ raise SystemExit('tiers must be a comma-separated selection of 1,2,3')
+ event = json.load(open(os.environ['GITHUB_EVENT_PATH']))
+ repo = os.environ['GITHUB_REPOSITORY']
+ pr = event.get('pull_request')
+ def read_api(suffix):
+ request = urllib.request.Request(os.environ['API_URL'] + '/repos/' + repo + suffix, headers={'Authorization':'Bearer '+os.environ['GH_TOKEN'], 'Accept':'application/vnd.github+json'})
+ try:
+ with urllib.request.urlopen(request, timeout=30) as response:
+ return json.load(response)
+ except (OSError, ValueError):
+ return {}
+ actor = urllib.parse.quote(os.environ['GITHUB_ACTOR'], safe='')
+ permission = read_api('/collaborators/' + actor + '/permission')
+ actor_allowed = permission.get('permission') in ('write', 'maintain', 'admin')
+ allowed = False
+ scan_mode = os.environ['SCAN_MODE']
+ if pr and pr['head']['repo'] and pr['head']['repo']['full_name'] == repo:
+ url = os.environ['API_URL'] + '/repos/' + repo + '/pulls/' + str(pr['number'])
+ request = urllib.request.Request(url, headers={'Authorization':'Bearer '+os.environ['GH_TOKEN'], 'Accept':'application/vnd.github+json'})
+ with urllib.request.urlopen(request, timeout=30) as response:
+ current = json.load(response)
+ allowed = actor_allowed and current['state'] == 'open' and current['head']['sha'] == pr['head']['sha'] and current['head']['repo'] and current['head']['repo']['full_name'] == repo
+ # A setup/configuration PR must exercise every selected skill. This
+ # predicate equals select_changed_skills.setup_changed (tests check it).
+ for page in range(1, 31):
+ files_url = url + '/files?per_page=100&page=' + str(page)
+ request = urllib.request.Request(files_url, headers={'Authorization':'Bearer '+os.environ['GH_TOKEN'], 'Accept':'application/vnd.github+json'})
+ with urllib.request.urlopen(request, timeout=30) as response:
+ files = json.load(response)
+ if any(path.startswith(('.github/', '.gitlab/', '.skillevaluator/ci')) or path == '.gitlab-ci.yml' for item in files for path in (item['filename'], item.get('previous_filename', ''))):
+ scan_mode = 'all'
+ break
+ if len(files) < 100:
+ break
+ else:
+ scan_mode = 'all' # Bounded discovery cannot certify a partial list.
+ elif not pr and os.environ['GITHUB_EVENT_NAME'] in ('push', 'workflow_dispatch'):
+ repository = read_api('')
+ default = repository.get('default_branch')
+ if isinstance(default, str) and default and os.environ.get('GITHUB_REF') == 'refs/heads/' + default:
+ branch = read_api('/branches/' + urllib.parse.quote(default, safe=''))
+ allowed = actor_allowed and branch.get('commit', {}).get('sha') == os.environ['GITHUB_SHA']
+ with open(os.environ['GITHUB_OUTPUT'], 'a') as output:
+ output.write('allowed=' + str(allowed).lower() + '\n')
+ output.write('scan-mode=' + scan_mode + '\n')
+ print('Provider jobs eligible' if allowed else 'Provider jobs withheld; Tier 1 remains available')
+ PY
+ paid-tiers:
+ needs: eligibility
+ if: ${{ needs.eligibility.outputs.allowed == 'true' }}
+ runs-on: ${{ inputs.runner }}
+ environment: ${{ inputs.environment }}
+ permissions:
+ contents: read
+ pull-requests: read
+ timeout-minutes: ${{ inputs.timeout-minutes }}
+ continue-on-error: true
+ strategy:
+ fail-fast: false
+ matrix:
+ tier: [2, 3]
+ env:
+ SKILLEVALUATOR_TOOLS_REF: ${{ inputs.tools-ref }}
+ SKILL_EVAL_PATHS: ${{ inputs.paths }}
+ # Tier 1's decision, including the full scan for a PR too large to list.
+ SKILL_EVAL_SCAN_MODE: ${{ needs.eligibility.outputs.scan-mode || inputs.scan-mode }}
+ SKILL_EVAL_MIN_SCORE: ${{ inputs.min-score }}
+ SKILL_EVAL_ENV_MODE: ${{ inputs.env-mode }}
+ SKILL_EVAL_PROVIDER: ${{ inputs.provider }}
+ SKILL_EVAL_MODEL: ${{ inputs.model }}
+ # 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_AGENTS: ${{ inputs.agents }}
+ SKILL_EVAL_TIER3_REQUIRED: 'false'
+ SKILL_EVAL_N_ATTEMPTS: ${{ inputs.n-attempts }}
+ SKILL_EVAL_N_CONCURRENT: ${{ inputs.n-concurrent }}
+ SKILL_EVAL_TIMEOUT_MINUTES: ${{ inputs.timeout-minutes }}
+ DIFF_BASE_SHA: ${{ github.event.pull_request.base.sha }}
+ DIFF_HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }}
+ REPORT_COMMIT: ${{ github.event.pull_request.head.sha || github.sha }}
+ REPORT_REPOSITORY: ${{ github.repository }}
+ REPORT_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
+ SKILLEVALUATOR_RUNTIME_DIR: ${{ github.workspace }}/.skillevaluator-ci-runtimes
+ PYTHON_DOTENV_DISABLED: '1'
+ 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
+ filter: blob:none
+ persist-credentials: false
+ - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1
+ with:
+ python-version: '3.12'
+ - name: Install only the selected tier's runtime from pinned tools
+ if: ${{ contains(format(',{0},', inputs.tiers), format(',{0},', matrix.tier)) }}
+ env:
+ TIER: ${{ matrix.tier }}
+ 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 "tier${TIER}" --project "$GITHUB_WORKSPACE/evaluator" --python 3.12 --default-index https://pypi.org/simple
+ echo "$GITHUB_WORKSPACE/evaluator/.venv/bin" >> "$GITHUB_PATH"
+ - name: Recheck current head after environment approval
+ id: current-head
+ env:
+ GH_TOKEN: ${{ github.token }}
+ API_URL: ${{ github.api_url }}
+ run: |
+ python3 -I - <<'PYTHON'
+ import json, os, urllib.parse, urllib.request
+ event = json.load(open(os.environ['GITHUB_EVENT_PATH']))
+ repo = os.environ['GITHUB_REPOSITORY']
+ def read_api(suffix):
+ request = urllib.request.Request(os.environ['API_URL'] + '/repos/' + repo + suffix, headers={'Authorization':'Bearer '+os.environ['GH_TOKEN'], 'Accept':'application/vnd.github+json'})
+ try:
+ with urllib.request.urlopen(request, timeout=30) as response:
+ return json.load(response)
+ except (OSError, ValueError):
+ return {}
+ actor = urllib.parse.quote(os.environ['GITHUB_ACTOR'], safe='')
+ permission = read_api('/collaborators/' + actor + '/permission')
+ if permission.get('permission') not in ('write', 'maintain', 'admin'):
+ raise SystemExit('Provider jobs require current write, maintain, or admin permission for the initiating actor')
+ pr = event.get('pull_request')
+ if pr:
+ current = read_api('/pulls/' + str(pr['number']))
+ if not pr['head']['repo'] or pr['head']['repo']['full_name'] != repo or current.get('state') != 'open' or current.get('head', {}).get('sha') != pr['head']['sha'] or not current.get('head', {}).get('repo') or current['head']['repo']['full_name'] != repo:
+ raise SystemExit('PR head changed or is no longer eligible; rerun the current head')
+ else:
+ repository = read_api('')
+ default = repository.get('default_branch')
+ if os.environ['GITHUB_EVENT_NAME'] not in ('push', 'workflow_dispatch') or not isinstance(default, str) or not default or os.environ.get('GITHUB_REF') != 'refs/heads/' + default:
+ raise SystemExit('Provider jobs require the current default branch for push or manual runs')
+ branch = read_api('/branches/' + urllib.parse.quote(default, safe=''))
+ if branch.get('commit', {}).get('sha') != os.environ['GITHUB_SHA']:
+ raise SystemExit('Default branch advanced; rerun the current commit')
+ with open(os.environ['GITHUB_OUTPUT'], 'a') as output:
+ output.write('allowed=true\n')
+ PYTHON
+ - name: Bootstrap native local agents and check selected environment
+ if: ${{ steps.current-head.outputs.allowed == 'true' && matrix.tier == 3 && contains(format(',{0},', inputs.tiers), ',3,') }}
+ continue-on-error: true
+ env:
+ 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/bootstrap_tiers.py
+ - name: Evaluate selected tier and retain native evidence
+ if: ${{ !cancelled() && steps.current-head.outputs.allowed == 'true' && contains(format(',{0},', inputs.tiers), format(',{0},', matrix.tier)) }}
+ env:
+ TIER: ${{ matrix.tier }}
+ OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
+ ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
+ NVIDIA_API_KEY: ${{ secrets.NVIDIA_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 ))
+ export SKILL_EVAL_TIMEOUT_SECONDS="$(( (SKILL_EVAL_TIMEOUT_MINUTES - reserve) * 60 ))"
+ python -I evaluator/ci/run_tiers.py evaluate --tier "$TIER" --workspace "$GITHUB_WORKSPACE/candidate" --reports "$RUNNER_TEMP/skill-reports"
+ - name: Retain native reports after failure
+ if: ${{ always() && contains(format(',{0},', inputs.tiers), format(',{0},', matrix.tier)) }}
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9
+ with:
+ name: skill-evaluator-tier${{ matrix.tier }}-attempt-${{ github.run_attempt }}
+ path: ${{ runner.temp }}/skill-reports/
+ if-no-files-found: warn
+ retention-days: 14
+ aggregate:
+ needs: [tier1, paid-tiers]
+ if: ${{ always() }}
+ runs-on: ubuntu-24.04
+ permissions:
+ contents: read
+ actions: read
+ id-token: write
+ env:
+ SKILLEVALUATOR_TOOLS_REF: ${{ inputs.tools-ref }}
+ DIFF_BASE_SHA: ${{ github.event.pull_request.base.sha }}
+ REPORT_COMMIT: ${{ github.event.pull_request.head.sha || github.sha }}
+ REPORT_REPOSITORY: ${{ github.repository }}
+ REPORT_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
+ SKILL_EVAL_ENV_MODE: ${{ inputs.env-mode }}
+ SKILL_EVAL_TIER3_REQUIRED: 'false'
+ steps:
+ - name: Capture signed aggregate execution receipt
+ id: provenance
+ continue-on-error: true
+ run: |
+ python3 -I - <<'PY'
+ import json, os, re, tempfile, urllib.parse, urllib.request
+
+ url = os.environ.get("ACTIONS_ID_TOKEN_REQUEST_URL")
+ credential = os.environ.get("ACTIONS_ID_TOKEN_REQUEST_TOKEN")
+ if not url or not credential:
+ print("Hosted-report receipt is disabled; scan artifacts remain available.")
+ raise SystemExit(0)
+
+ class NoRedirect(urllib.request.HTTPRedirectHandler):
+ def redirect_request(self, *args, **kwargs):
+ return None
+
+ try:
+ parsed = urllib.parse.urlsplit(url)
+ if (parsed.scheme != "https" or not parsed.hostname
+ or not parsed.hostname.endswith(".actions.githubusercontent.com")
+ or parsed.port not in (None, 443) or parsed.username or parsed.password
+ or parsed.fragment):
+ raise ValueError("Unexpected GitHub identity endpoint")
+ audience = "urn:skillevaluator:report-provenance:v1"
+ url += ("&" if parsed.query else "?") + "audience=" + urllib.parse.quote(audience, safe="")
+ request = urllib.request.Request(url, headers={"Authorization": "Bearer " + credential})
+ with urllib.request.build_opener(NoRedirect()).open(request, timeout=30) as response:
+ payload = response.read(65537)
+ if len(payload) > 65536:
+ raise ValueError("Oversized identity response")
+ token = json.loads(payload)["value"]
+ if (not isinstance(token, str) or len(token) > 32768
+ or not re.fullmatch(r"[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+", token)):
+ raise ValueError("Invalid identity response")
+ directory = tempfile.mkdtemp(prefix="skill-provenance-", dir=os.environ["RUNNER_TEMP"])
+ descriptor = os.open(os.path.join(directory, "execution.jwt"), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
+ with os.fdopen(descriptor, "w") as handle:
+ handle.write(token)
+ with open(os.environ["GITHUB_OUTPUT"], "a") as handle:
+ handle.write("directory=" + directory + "\n")
+ print("Captured the signed execution receipt for hosted reports.")
+ except (OSError, ValueError, KeyError, TypeError):
+ raise SystemExit("Could not capture the hosted-report receipt. Scan artifacts remain available; hosting will be skipped.") from None
+ PY
+ - 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 aggregate 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 --project "$GITHUB_WORKSPACE" --python 3.12 --default-index https://pypi.org/simple
+ echo "$GITHUB_WORKSPACE/.venv/bin" >> "$GITHUB_PATH"
+ # "Re-run failed jobs" keeps earlier-attempt artifacts from tier jobs that were not rerun.
+ - name: Download every attempt's tier reports into separate directories
+ continue-on-error: true
+ uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093
+ with:
+ pattern: skill-evaluator-tier[123]-attempt-*
+ path: ${{ runner.temp }}/skill-artifacts
+ - name: Select each tier's latest retained attempt
+ run: python -I ci/run_tiers.py select-attempts --artifacts "$RUNNER_TEMP/skill-artifacts" --reports "$RUNNER_TEMP/skill-reports"
+ - name: Aggregate required Tier 1 and advisory Tier 2 and Tier 3 evidence
+ env:
+ TIERS: ${{ inputs.tiers }}
+ run: python -I ci/run_tiers.py aggregate --reports "$RUNNER_TEMP/skill-reports" --tiers "$TIERS"
+ - name: Upload complete reports even when required gates fail
+ if: ${{ always() }}
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9
+ with:
+ name: skill-evaluator-results-attempt-${{ github.run_attempt }}
+ path: ${{ runner.temp }}/skill-reports/
+ if-no-files-found: warn
+ retention-days: 14
+ - name: Add aggregate summary
+ if: ${{ always() }}
+ run: |
+ if [ -f "$RUNNER_TEMP/skill-reports/summary.md" ]; then
+ cat "$RUNNER_TEMP/skill-reports/summary.md" >> "$GITHUB_STEP_SUMMARY"
+ fi
+ - name: Retain signed receipt separately from native evidence
+ if: ${{ always() && steps.provenance.outputs.directory != '' }}
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9
+ with:
+ name: skill-evaluator-results-provenance-attempt-${{ github.run_attempt }}
+ path: ${{ steps.provenance.outputs.directory }}/execution.jwt
+ if-no-files-found: error
+ retention-days: 14
diff --git a/.github/workflows/feedback-all-tiers.yml b/.github/workflows/feedback-all-tiers.yml
new file mode 100644
index 00000000..0d94ede1
--- /dev/null
+++ b/.github/workflows/feedback-all-tiers.yml
@@ -0,0 +1,60 @@
+# SPDX-License-Identifier: Apache-2.0
+name: Trusted three-tier skill feedback
+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: read
+ actions: read
+ pull-requests: write
+jobs:
+ feedback:
+ # Serialize updates to one PR's comment; queue instead of cancelling pending runs.
+ concurrency:
+ group: skillevaluator-feedback-${{ github.repository }}-${{ github.event.workflow_run.head_repository.full_name }}-${{ github.event.workflow_run.head_branch }}
+ cancel-in-progress: false
+ queue: max
+ # Fork PR runs have no producer receipt; skip them instead of failing.
+ if: ${{ github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.head_repository.full_name == github.repository }}
+ runs-on: ubuntu-24.04
+ permissions:
+ contents: read
+ actions: read
+ pull-requests: write
+ steps:
+ # No producer repository ref, artifacts, or PR code is executed here.
+ - 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 feedback 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 current head and producer before updating one comment
+ 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: '"$GITHUB_WORKSPACE/.venv/bin/python" -I ci/feedback.py --platform github --repository "$GITHUB_REPOSITORY" --run-id "$SOURCE_RUN_ID" --run-attempt "$SOURCE_RUN_ATTEMPT"'
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b23abe54..06698f9f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,23 @@ All notable changes to SkillEvaluator are documented in this file.
Your Agent" docs page shows how to install it in Codex, Claude Code, OpenCode,
OpenClaw, and other skill-aware agents.
+- Opt-in three-tier GitHub and GitLab CI entrypoints with required Tier 1,
+ advisory Tier 2 and paired Tier 3, Docker and native local execution, pinned
+ local agent bootstrap, retained aggregate/native reports, and trusted default-branch
+ feedback. Candidate templates require a capability-bearing release descriptor;
+ released Tier 1 bundles and workflows remain unchanged. Incomplete runs retain
+ redacted startup diagnostics. Interrupted Tier 1 selections cannot pass on
+ partial results; advisory tiers preserve their failed or incomplete status.
+ GitLab callers quote variable values, use literal job timeouts
+ compatible with GitLab 17.8, and safely select changes in runner-owned checkouts.
+ GitLab before 18.4 uses a separate read-only admission credential; feedback
+ initiation is advisory so first-install reporting does not change the tier gate.
+ Same-project feedback uses the short-lived job-token trigger API and verifies
+ the server-bound upstream pipeline and source job, preserving protected-branch
+ and deployment permissions. Its persisted GraphQL MR association supports
+ GitLab 17.x without requiring the newer pipeline/MR REST endpoint. Publisher
+ failures include a trusted check location and finite diagnostic category.
+
- Private plugin helpers recognize native OpenClaw manifests
(`openclaw.plugin.json`) after the existing manifest formats. `id` is the
plugin identity and `configSchema` must be an object. Only the `skills` roots
@@ -71,6 +88,22 @@ All notable changes to SkillEvaluator are documented in this file.
required and advisory summary reasons distinct within mixed tiers and focus
direct agent links on their named panels.
+- Compact all-tier CI PR and MR feedback into one summary table with a row per
+ skill, one-line tier statuses and issue counts, and one combined **Report**
+ link per skill. Incomplete or missing evidence keeps issue counts unknown;
+ detailed aggregate and native reports remain in the authenticated artifact.
+
+- Make Tier 1 the only gate in opt-in all-tier GitHub and GitLab CI. Tier 2 and
+ Tier 3 retain failed and incomplete advisory outcomes and native reports.
+ Deprecate and ignore onboarding's `--tier3-required`, GitHub's
+ `tier3-required` input and GitLab's `SKILL_EVAL_TIER3_REQUIRED` variable;
+ none can make Tier 3 block CI. Standalone validation and benchmark
+ publication policies are unchanged.
+
+- Give staged Tier 3 main images a fixed liveness healthcheck so Docker Compose
+ 2 can wait for readiness while authored image healthchecks remain suppressed.
+ Keep custom service healthchecks and their readiness dependencies intact.
+
### Documentation
- The 0.8.0 entry for refused `claude-code` attempts said the arm reports its
@@ -98,6 +131,12 @@ All notable changes to SkillEvaluator are documented in this file.
### Fixed
+- All-tier CI retains Tier 2's native reports as advisory while preserving
+ failed and incomplete evaluation outcomes. GitHub `ci status` validates the
+ pinned evaluation and feedback configuration before reporting readiness,
+ including malformed YAML and missing approval inputs. Candidate onboarding
+ pins include the reviewed CI fixes and matching runtime metadata.
+
- Private native Claude Code staging keeps the source client's skill
declarations: Codex paths that Codex ignores are no longer copied into the
staged `plugin.json` (where Claude Code rejected or loaded them), and
diff --git a/ci/bootstrap_tiers.py b/ci/bootstrap_tiers.py
new file mode 100644
index 00000000..05dca424
--- /dev/null
+++ b/ci/bootstrap_tiers.py
@@ -0,0 +1,69 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: Apache-2.0
+# ruff: noqa: T201 — command-line helper diagnostics
+"""Prepare only native agent runtimes, then doctor the CI-selected environment."""
+
+from __future__ import annotations
+
+import os
+import subprocess
+import sys
+
+from skillevaluator.tier3.commands import resolve_agents
+from skillevaluator.tier3.harbor.local_runtime import managed_install_argv, managed_runtime_prefix
+
+
+def install_agent(agent: str) -> None:
+ argv = managed_install_argv(agent)
+ if agent == "opencode":
+ # Unlike interactive local setup, CI never resolves an unpinned npm package.
+ # Docker runs install the same release through Harbor's agent kwargs.
+ from skillevaluator.tier3.harbor.runner import OPENCODE_VERSION
+
+ argv[-1] = f"opencode-ai@{OPENCODE_VERSION}"
+ subprocess.run(argv, check=True, timeout=600)
+ print(f"Installed {agent} in {managed_runtime_prefix(agent)}")
+
+
+def main() -> int:
+ mode = os.environ.get("SKILL_EVAL_ENV_MODE", "docker")
+ if mode not in {"docker", "local"}:
+ print("Three-tier CI supports docker and local environments only.")
+ return 2
+ try:
+ agents = resolve_agents(
+ os.environ.get("SKILL_EVAL_AGENTS") or None, provider=os.environ.get("SKILL_EVAL_PROVIDER", "openai")
+ )
+ 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
+ result = subprocess.run(
+ [
+ sys.executable,
+ "-I",
+ "-m",
+ "skillevaluator.cli",
+ "doctor",
+ "--env-mode",
+ mode,
+ "--agents",
+ ",".join(agents),
+ ],
+ check=False,
+ env=doctor_env,
+ timeout=180,
+ )
+ return result.returncode
+ except (OSError, ValueError, subprocess.SubprocessError) as exc:
+ # Do not print subprocess output or provider credentials.
+ print(f"Native CI preflight needs action: {type(exc).__name__}")
+ return 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/ci/comment_summary.py b/ci/comment_summary.py
new file mode 100644
index 00000000..df729760
--- /dev/null
+++ b/ci/comment_summary.py
@@ -0,0 +1,164 @@
+# SPDX-License-Identifier: Apache-2.0
+# ruff: noqa: INP001 -- platform-neutral CI comment renderer.
+"""Render a bounded, skill-scoped comment from validated retained CI evidence."""
+
+from __future__ import annotations
+
+import html
+import unicodedata
+from urllib.parse import quote, urlsplit
+
+try:
+ from tier_manifest import validate_manifest
+except ModuleNotFoundError:
+ from ci.tier_manifest import validate_manifest
+
+_CELL_CHARACTERS = 140
+_COMMENT_BYTES = 52_000
+
+
+def _text(value: str, limit: int = _CELL_CHARACTERS) -> str:
+ """Keep each cell on one bounded line, without executable Markdown or mentions."""
+ value = " ".join("".join(" " if unicodedata.category(c).startswith("C") else c for c in value).split())
+ if len(value) > limit:
+ value = value[: limit - 1].rstrip() + "…"
+ # Markdown decodes "&#64;" back to "@" before mention filters run; a zero-width
+ # space after "@" keeps the text readable without notifying users or teams.
+ return "".join(
+ html.escape(c, quote=False)
+ if c in "&<>"
+ else "@\u200b"
+ if c == "@"
+ else "&#124;"
+ if c == "|"
+ else "\\" + c
+ if c in "\\`*_{}[]()#!"
+ else c
+ for c in value
+ )
+
+
+def _report_link(artifact_url: str) -> str:
+ """A downloadable archive is one artifact, never a member URL directory."""
+ if (
+ not isinstance(artifact_url, str)
+ or not artifact_url
+ or len(artifact_url) > 8192
+ or any(c.isspace() or unicodedata.category(c).startswith("C") or c == "\\" for c in artifact_url)
+ ):
+ raise ValueError("Invalid artifact URL")
+ parsed = urlsplit(artifact_url)
+ if parsed.scheme != "https" or not parsed.hostname or parsed.username or parsed.password:
+ raise ValueError("Invalid artifact URL")
+ safe_url = quote(artifact_url, safe=":/?#[]@!$&'*+,;=%-._~")
+ return f"[Report]({safe_url})"
+
+
+def _reason(record: dict) -> str:
+ return next((record[key] for key in ("error", "reason") if isinstance(record.get(key), str) and record[key]), "")
+
+
+def _cell_text(status: str, issues: str, reason: str = "") -> str:
+ prefix = f"{status.upper()} · {issues}"
+ if not reason:
+ return prefix
+ return prefix + " · " + _text(reason, max(1, _CELL_CHARACTERS - len(prefix) - 3))
+
+
+def _cell(record: dict | None, skill: dict | None, *, expected: bool, path: str | None = None) -> str:
+ if record is None:
+ reason = "No retained result" if expected else "Not requested"
+ return _cell_text("not_run", "issues unknown", reason)
+ if skill is None:
+ if record["skills"]:
+ # Tiers can select different skills; a skill this tier never selected is not missing evidence.
+ selected = record.get("selected")
+ if isinstance(selected, list) and path not in selected:
+ return _cell_text("skipped", "issues unknown", "Not selected for this tier")
+ return _cell_text("incomplete", "issues unknown", "No retained result for this skill")
+ reason = _reason(record) or "No retained skill evidence"
+ return _cell_text(record["status"], "issues unknown", reason)
+
+ metrics = skill.get("metrics", {})
+ count, critical, high = (metrics.get(key) for key in ("issue_count", "critical_count", "high_count"))
+ counts_valid = all(type(value) is int and value >= 0 for value in (count, critical, high))
+ known = metrics.get("issue_count_known") is True and counts_valid
+ if known or (counts_valid and count > 0):
+ prefix = "" if known else "at least "
+ issues = f"{prefix}{count} issues"
+ severity = ", ".join(f"{value} {name}" for value, name in ((critical, "critical"), (high, "high")) if value > 0)
+ if severity:
+ issues += f" ({severity})"
+ else:
+ issues = "issues unknown"
+ top_issue = metrics.get("top_issue")
+ reason = (top_issue if isinstance(top_issue, str) else "") or _reason(skill)
+ if not reason and not known:
+ reason = _reason(record) or ("Incomplete native evidence" if counts_valid else "Native evidence unavailable")
+ return _cell_text(skill["status"], issues, reason)
+
+
+def _policy(records: dict[int, dict], expected: list[int]) -> tuple[str, str]:
+ required = [tier for tier in (1, 2, 3) if records.get(tier, {}).get("required", tier == 1 and tier in expected)]
+ if required == [1]:
+ policy = "Only Tier 1 blocks CI; Tier 2 and Tier 3 are advisory."
+ else:
+ required_label = ", ".join(f"Tier {tier}" for tier in required) or "none"
+ advisory_label = ", ".join(f"Tier {tier}" for tier in (1, 2, 3) if tier not in required) or "none"
+ policy = f"Required tiers: {required_label}. Advisory tiers: {advisory_label}."
+ return policy, "Advisory only" if not required else ""
+
+
+def render_comment_summary(manifest: dict, artifact_url: str) -> str:
+ """Return one compact Markdown table; never read paths or mutate evidence.
+
+ Callers derive each skill's ``metrics`` from verified retained JSON using
+ ``summary_metrics.summarize_results``. Missing metrics remain unknown. The
+ report link points unchanged to the combined artifact covering all tiers.
+ Commit, producer receipt, and run link are supplied by the feedback adapter.
+ """
+ manifest = validate_manifest(manifest)
+ report = _report_link(artifact_url)
+ records = {record["tier"]: record for record in manifest["tiers"]}
+ by_skill = {tier: {skill["path"]: skill for skill in record["skills"]} for tier, record in records.items()}
+ paths = sorted({path for skills in by_skill.values() for path in skills})
+ policy, gate = _policy(records, manifest["expected_tiers"])
+ if not gate:
+ gate = (
+ "Skipped"
+ if manifest["overall_passed"] and manifest["overall_status"] == "skipped"
+ else "Passed"
+ if manifest["overall_passed"]
+ else "Not passed"
+ )
+ lines = [
+ "## SkillEvaluator CI results",
+ "",
+ f"Required gate: **{gate}**",
+ "",
+ policy,
+ "",
+ "| Skill | Tier 1: Static and Security Validation | Tier 2: Deduplication | Tier 3: Live Agent Evaluation | Report |",
+ "| --- | --- | --- | --- | --- |",
+ ]
+ size = len("\n".join(lines).encode("utf-8"))
+ for index, path in enumerate(paths or [None]):
+ cells = [
+ _cell(
+ records.get(tier),
+ by_skill.get(tier, {}).get(path),
+ expected=tier in manifest["expected_tiers"],
+ path=path,
+ )
+ for tier in (1, 2, 3)
+ ]
+ label = _text(path) if path is not None else "No skills evaluated"
+ row = "| " + " | ".join([label, *cells, report]) + " |"
+ row_bytes = len(row.encode("utf-8")) + 1
+ # Reserve room for a truthful omission notice and the adapter's footer.
+ if size + row_bytes > _COMMENT_BYTES - 200:
+ lines.extend(["", f"{len(paths) - index} additional skills omitted; open a Report for complete evidence."])
+ break
+ lines.append(row)
+ size += row_bytes
+ return "\n".join([*lines, ""])
diff --git a/ci/diagnostics.py b/ci/diagnostics.py
new file mode 100644
index 00000000..908db88f
--- /dev/null
+++ b/ci/diagnostics.py
@@ -0,0 +1,396 @@
+# SPDX-License-Identifier: Apache-2.0
+# ruff: noqa: INP001 -- standalone CI artifact helper.
+"""Bounded, redacted native-worker startup diagnostics; never agent trajectories."""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+import stat
+import tempfile
+from pathlib import Path
+
+from skillevaluator.utils.secret_redaction import REDACTED, Redactor
+from skillevaluator.utils.secure_fs import SecureRoot, _validate_opened_file, read_bounded
+
+MAX_FILE_BYTES = 1024 * 1024
+MAX_TOTAL_BYTES = 8 * 1024 * 1024
+MAX_FILES = 100
+MAX_ENTRIES = 10_000
+MAX_RECORDS = 200
+MAX_DEPTH = 64
+# Harbor writes one directory per trial (its trial.log, and exception.txt when it
+# failed). Startup problems repeat across trials, so keep the first failing trial
+# of each job (one arm of one agent) and a few per skill, failing jobs first.
+MAX_TRIALS_PER_JOB = 1
+MAX_TRIALS = 4
+# Every skill of one tier shares this budget (index.json files excluded), which
+# keeps a tier's diagnostics far below what the feedback reader accepts.
+MAX_TIER_FILES = 1000
+MAX_TIER_BYTES = 16 * 1024 * 1024
+_NAMES = frozenset({"failure.json", "exception.txt", "traceback.txt", "trial.log", "stderr.log", "stdout.log"})
+_EXCLUDED = frozenset(
+ {
+ "agent",
+ "agents",
+ "user-agent",
+ "verifier",
+ "artifacts",
+ "trajectories",
+ "payloads",
+ "credentials",
+ "config",
+ "configs",
+ "workspace",
+ "consumer",
+ "task",
+ "tasks",
+ ".git",
+ ".env",
+ ".ssh",
+ ".aws",
+ ".config",
+ "node_modules",
+ "__pycache__",
+ }
+)
+_KEY = re.compile(
+ r"(?i)(?:[a-z][a-z0-9]*[_-])*(?:api[_-]?key|apikey|access[_-]?token|auth[_-]?token|token|secret|password|passwd|pwd|authorization)"
+)
+_NVIDIA = re.compile(r"\bnvapi-[A-Za-z0-9_-]{8,}")
+_BEARER = re.compile(r"(?i)\bbearer\s+[^\s\"'`<>;,]+")
+_AUTHORIZATION = re.compile(r"(?i)(\b(?:proxy[-_])?authorization[\"']?[ \t]*[:=][ \t]*)[^\r\n]+")
+_ASSIGNMENT = re.compile(
+ r"(?i)((?<![a-z0-9_-])(?:[a-z][a-z0-9]*[_-])*(?:api[_-]?key|apikey|access[_-]?token|auth[_-]?token|token|secret|password|passwd|pwd)[\"']?[ \t]*[:=][ \t]*)"
+ r"""(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s"'`;,}{]+)"""
+)
+_ANSI = re.compile(r"\x1b\[[0-?]*[ -/]*[@-~]")
+_MARKER = b"\n[diagnostic truncated]\n"
+
+
+def _mask_text(value: str, redactor: Redactor) -> str:
+ value = redactor.text(value)
+ value = _NVIDIA.sub(REDACTED, value)
+ value = _AUTHORIZATION.sub(lambda match: match.group(1) + REDACTED, value)
+ value = _BEARER.sub("Bearer " + REDACTED, value)
+ return _ASSIGNMENT.sub(lambda match: match.group(1) + REDACTED, value)
+
+
+def _mask_object(value, redactor: Redactor):
+ if isinstance(value, str):
+ return _mask_text(value, redactor)
+ if isinstance(value, list):
+ return [_mask_object(item, redactor) for item in value]
+ if isinstance(value, dict):
+ return {key: REDACTED if _KEY.fullmatch(key) else _mask_object(item, redactor) for key, item in value.items()}
+ return value
+
+
+class TierBudget:
+ """Diagnostic files and bytes that remain for the rest of one tier's skills."""
+
+ def __init__(self) -> None:
+ self.files = MAX_TIER_FILES
+ self.bytes = MAX_TIER_BYTES
+
+
+def _trial(directory: Path) -> tuple[bool, bool]:
+ """Return whether a directory is a Harbor trial and whether that trial failed."""
+
+ def regular(name: str) -> bool:
+ try:
+ return stat.S_ISREG((directory / name).lstat().st_mode)
+ except OSError:
+ return False
+
+ failed = regular("exception.txt")
+ return failed or regular("trial.log"), failed
+
+
+def _excluded(name: str, relative: Path) -> bool:
+ return name.casefold() in _EXCLUDED or len(relative.parts) > MAX_DEPTH
+
+
+def _select_trials(raw: Path) -> set[Path]:
+ """Choose the trials to keep across all Harbor jobs before any file is read.
+
+ Each job keeps its own first trials, failing ones first. Across jobs, failing
+ trials come before passing ones, so passing jobs that sort first cannot push
+ a later job's failure past ``MAX_TRIALS``.
+ """
+ jobs: dict[Path, list[tuple[bool, str]]] = {}
+ seen = 0
+ for directory, directories, names in os.walk(raw, followlinks=False):
+ seen += len(directories) + len(names)
+ if seen > MAX_ENTRIES:
+ break
+ directories.sort()
+ for name in list(directories):
+ path = Path(directory) / name
+ if path.is_symlink() or _excluded(name, path.relative_to(raw)):
+ directories.remove(name)
+ continue
+ is_trial, failed = _trial(path)
+ if is_trial:
+ jobs.setdefault(Path(directory).relative_to(raw), []).append((not failed, name))
+ kept = [
+ (passing, job, name) for job, trials in jobs.items() for passing, name in sorted(trials)[:MAX_TRIALS_PER_JOB]
+ ]
+ return {job / name for _, job, name in sorted(kept)[:MAX_TRIALS]}
+
+
+def _regular_root(path: Path) -> Path:
+ path = Path(path).absolute()
+ if any(parent.is_symlink() for parent in (path, *path.parents)):
+ raise ValueError("Diagnostic roots must not contain symlinks")
+ return path
+
+
+def _write(root: Path, relative: Path, payload: bytes) -> None:
+ target = root / relative
+ for parent in (target.parent, *target.parent.parents):
+ if parent.is_symlink():
+ raise ValueError("Diagnostic output must not contain symlinks")
+ if parent == root:
+ break
+ target.parent.mkdir(parents=True, exist_ok=True)
+ if target.is_symlink() or (target.exists() and not target.is_file()):
+ raise ValueError("Diagnostic output must be regular")
+ descriptor, temporary = tempfile.mkstemp(prefix=".diagnostic-", dir=target.parent)
+ try:
+ with os.fdopen(descriptor, "wb") as stream:
+ stream.write(payload)
+ Path(temporary).replace(target)
+ finally:
+ Path(temporary).unlink(missing_ok=True)
+
+
+def _read(root: SecureRoot, relative: Path, metadata: os.stat_result) -> tuple[bytes, bool]:
+ if metadata.st_size <= MAX_FILE_BYTES:
+ return root.read_bytes(relative, MAX_FILE_BYTES, expected=metadata)[0], False
+ if relative.suffix == ".json" or os.name != "posix":
+ raise ValueError("oversized_json_or_platform")
+ # The secure reader pins every directory and rejects redirects/hard links.
+ descriptor = root._open_posix(relative, metadata, allow_hardlinks=False)
+ try:
+ budget = max(0, (MAX_FILE_BYTES - len(_MARKER)) // 2)
+ head = read_bounded(descriptor, budget, truncate=True)
+ os.lseek(descriptor, max(0, metadata.st_size - budget), os.SEEK_SET)
+ tail = read_bounded(descriptor, budget, truncate=True)
+ _validate_opened_file(os.fstat(descriptor), relative, metadata)
+ finally:
+ os.close(descriptor)
+ # Drop split edge lines so truncation cannot expose an unknown credential's
+ # suffix after its NVIDIA/Bearer/assignment prefix has been cut away.
+ head = head[: head.rfind(b"\n") + 1] if b"\n" in head else b""
+ tail = tail[tail.find(b"\n") + 1 :] if b"\n" in tail else b""
+ return head + _MARKER + tail, True
+
+
+def retain_diagnostics(
+ raw: Path,
+ destination: Path,
+ tokens: set[str],
+ *,
+ command_log: Path | None = None,
+ budget: TierBudget | None = None,
+) -> dict:
+ """Retain whitelisted worker diagnostics below ``destination/diagnostics``.
+
+ The caller supplies an evaluator-owned output root. The optional command log
+ is an explicit separate input, retained first as ``command.log``. Each unsafe
+ or unsupported child is omitted with a fixed reason; input content and
+ absolute paths never appear in index errors. No HTML or agent/state/config
+ files are copied, and no diagnostic changes the evaluation verdict. Files
+ from at most ``MAX_TRIALS`` Harbor trials are kept, failing trials first, and
+ an optional ``budget`` bounds what all skills of one tier retain together.
+ """
+ raw, destination = _regular_root(raw), _regular_root(destination)
+ if not raw.is_dir() or destination.is_relative_to(raw) or raw.is_relative_to(destination):
+ raise ValueError("Separate regular worker and artifact roots are required")
+ output = destination / "diagnostics"
+ if output.exists() or output.is_symlink():
+ raise ValueError("Diagnostics require a fresh output directory")
+ output.mkdir(parents=True)
+ redactor = Redactor(tokens)
+ result = {
+ "schema_version": 1,
+ "index": "diagnostics/index.json",
+ "retained": [],
+ "omitted": [],
+ "truncated": [],
+ "errors": [],
+ "omitted_count": 0,
+ "total_bytes": 0,
+ }
+ reads = visited = 0
+
+ def label(relative: Path) -> str:
+ text = relative.as_posix()
+ if len(text) > 1024 or any(ord(c) < 32 or ord(c) == 127 for c in text) or _mask_text(text, redactor) != text:
+ return "[REDACTED PATH]"
+ return text
+
+ def record(bucket: str, relative: Path, reason: str) -> None:
+ if bucket == "omitted":
+ result["omitted_count"] += 1
+ if len(result[bucket]) < MAX_RECORDS:
+ result[bucket].append({"path": label(relative), "reason": reason})
+
+ def collect(source: SecureRoot, relative: Path, target: Path, metadata: os.stat_result) -> None:
+ nonlocal reads
+ if not stat.S_ISREG(metadata.st_mode) or metadata.st_nlink != 1:
+ record("errors", target, "special_file")
+ return
+ if reads >= MAX_FILES or len(result["retained"]) >= MAX_FILES:
+ record("omitted", target, "file_limit")
+ return
+ if result["total_bytes"] >= MAX_TOTAL_BYTES:
+ record("omitted", target, "total_limit")
+ return
+ if budget is not None and (budget.files <= 0 or budget.bytes <= 0):
+ record("omitted", target, "tier_limit")
+ return
+ if label(target) == "[REDACTED PATH]":
+ record("omitted", target, "unsafe_or_sensitive_path")
+ return
+ reads += 1
+ try:
+ content, truncated = _read(source, relative, metadata)
+ if b"\x00" in content:
+ record("omitted", target, "binary_or_encoding")
+ return
+ text = _ANSI.sub("", content.decode("utf-8-sig"))
+ if target.suffix == ".json":
+ value = json.loads(text, parse_constant=lambda _value: (_ for _ in ()).throw(ValueError("nonfinite")))
+ value = _mask_object(redactor.object(value), redactor)
+ payload = (json.dumps(value, ensure_ascii=True, allow_nan=False, indent=2) + "\n").encode()
+ if len(payload) > MAX_FILE_BYTES:
+ record("omitted", target, "redacted_json_limit")
+ result["truncated"].append(target.as_posix())
+ return
+ else:
+ payload = _mask_text(text, redactor).encode("utf-8")
+ if len(payload) > MAX_FILE_BYTES:
+ # Redaction may grow short literals. Trim complete lines of
+ # already-redacted text, preserving the terminal error.
+ payload = payload[-MAX_FILE_BYTES:]
+ payload = payload[payload.find(b"\n") + 1 :] if b"\n" in payload else b""
+ truncated = True
+ if result["total_bytes"] + len(payload) > MAX_TOTAL_BYTES:
+ record("omitted", target, "total_limit")
+ return
+ if budget is not None and len(payload) > budget.bytes:
+ record("omitted", target, "tier_limit")
+ return
+ _write(output, target, payload)
+ result["retained"].append(
+ {"path": target.as_posix(), "bytes": len(payload), "source_bytes": metadata.st_size}
+ )
+ result["total_bytes"] += len(payload)
+ if budget is not None:
+ budget.files -= 1
+ budget.bytes -= len(payload)
+ if truncated:
+ result["truncated"].append(target.as_posix())
+ except UnicodeError:
+ record("omitted", target, "binary_or_encoding")
+ except (ValueError, RecursionError):
+ record("omitted", target, "invalid_or_oversized_diagnostic")
+ if metadata.st_size > MAX_FILE_BYTES:
+ result["truncated"].append(target.as_posix())
+ except OSError:
+ record("errors", target, "read_or_write_error")
+
+ def collect_setup(source: SecureRoot, agent: Path) -> None:
+ nonlocal visited
+ setup = agent / "setup"
+ if visited >= MAX_ENTRIES:
+ record("omitted", setup.relative_to(raw), "discovery_limit")
+ return
+ visited += 1
+ if setup.is_symlink():
+ record("errors", setup.relative_to(raw), "unsafe_link")
+ return
+ if not setup.is_dir():
+ return
+ try:
+ with os.scandir(setup) as entries:
+ for entry in entries:
+ relative = Path(entry.path).relative_to(raw)
+ if visited >= MAX_ENTRIES:
+ record("omitted", relative, "discovery_limit")
+ break
+ visited += 1
+ metadata = entry.stat(follow_symlinks=False)
+ if stat.S_ISLNK(metadata.st_mode):
+ record("errors", relative, "unsafe_link")
+ elif re.fullmatch(
+ r"install-(?:root-prereqs|agent-runtime)(?:\.attempt-[0-9]+)?(?:\.(?:failed|timeout))?\.log",
+ entry.name,
+ ):
+ collect(source, relative, relative, metadata)
+ else:
+ record("omitted", relative, "not_allowed")
+ except OSError:
+ record("errors", setup.relative_to(raw), "read_or_write_error")
+
+ # The evaluator's own output explains most failures; keep it before trial logs.
+ if command_log is not None:
+ command_log = _regular_root(command_log)
+ try:
+ with SecureRoot(command_log.parent) as source:
+ collect(source, Path(command_log.name), Path("command.log"), command_log.lstat())
+ except OSError:
+ record("errors", Path("command.log"), "read_or_write_error")
+ trials = _select_trials(raw)
+ with SecureRoot(raw) as source:
+ for directory, directories, names in os.walk(raw, followlinks=False):
+ directories.sort()
+ names.sort()
+ for name in list(directories):
+ visited += 1
+ if visited > MAX_ENTRIES:
+ record("omitted", Path(directory).relative_to(raw), "discovery_limit")
+ directories.clear()
+ break
+ path = Path(directory) / name
+ relative = path.relative_to(raw)
+ if path.is_symlink():
+ directories.remove(name)
+ record("errors", relative, "unsafe_link")
+ elif _excluded(name, relative):
+ directories.remove(name)
+ if name == "agent":
+ collect_setup(source, path)
+ record("omitted", relative, "not_allowed")
+ for name in list(directories):
+ relative = (Path(directory) / name).relative_to(raw)
+ if relative not in trials and _trial(raw / relative)[0]:
+ directories.remove(name)
+ record("omitted", relative, "trial_limit")
+ for name in names:
+ visited += 1
+ relative = (Path(directory) / name).relative_to(raw)
+ if visited > MAX_ENTRIES:
+ record("omitted", relative, "discovery_limit")
+ directories.clear()
+ break
+ try:
+ metadata = (raw / relative).lstat()
+ except OSError:
+ record("errors", relative, "read_or_write_error")
+ continue
+ if stat.S_ISLNK(metadata.st_mode):
+ record("errors", relative, "unsafe_link")
+ elif not stat.S_ISREG(metadata.st_mode):
+ record("errors", relative, "special_file")
+ elif name not in _NAMES and re.fullmatch(r"(?:docker|environment)[A-Za-z0-9_.-]*\.log", name) is None:
+ record("omitted", relative, "not_allowed")
+ else:
+ collect(source, relative, relative, metadata)
+ if visited > MAX_ENTRIES:
+ break
+ _write(output, Path("index.json"), (json.dumps(result, ensure_ascii=True, indent=2) + "\n").encode())
+ return result
diff --git a/ci/eligible_gitlab.py b/ci/eligible_gitlab.py
new file mode 100644
index 00000000..17e7dd4b
--- /dev/null
+++ b/ci/eligible_gitlab.py
@@ -0,0 +1,95 @@
+#!/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."""
+
+from __future__ import annotations
+
+import json
+import os
+import urllib.error
+import urllib.parse
+import urllib.request
+from collections.abc import Mapping
+
+
+class _NoRedirect(urllib.request.HTTPRedirectHandler):
+ def redirect_request(self, *_args, **_kwargs):
+ return None
+
+
+def eligible(env: Mapping[str, str], current: dict | None) -> bool:
+ if env.get("CI_PIPELINE_SOURCE") == "merge_request_event":
+ if current is None:
+ return False
+ project = env.get("CI_PROJECT_ID")
+ return (
+ env.get("CI_MERGE_REQUEST_SOURCE_PROJECT_ID") == project
+ and str(current.get("source_project_id")) == project
+ and str(current.get("target_project_id")) == project
+ and current.get("state") == "opened"
+ and current.get("sha") == env.get("CI_COMMIT_SHA")
+ )
+ return (
+ 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"}
+ )
+
+
+def main() -> int:
+ env = os.environ
+ current = None
+ if env.get("CI_PIPELINE_SOURCE") == "merge_request_event":
+ base = env.get("CI_API_V4_URL", "")
+ parsed = urllib.parse.urlsplit(base)
+ if (
+ parsed.scheme != "https"
+ or not parsed.hostname
+ or parsed.username
+ or parsed.password
+ or parsed.query
+ or parsed.fragment
+ or not parsed.path.rstrip("/").endswith("/api/v4")
+ ):
+ print("GitLab admission requires an HTTPS API endpoint.")
+ return 2
+ project = env.get("CI_PROJECT_ID", "")
+ iid = env.get("CI_MERGE_REQUEST_IID", "")
+ if not project.isdigit() or not iid.isdigit():
+ return 2
+ # GitLab added job-token authentication for this 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)
+ try:
+ with urllib.request.build_opener(_NoRedirect()).open(request, timeout=30) as response:
+ payload = response.read(1024 * 1024 + 1)
+ if len(payload) > 1024 * 1024:
+ raise ValueError("Oversized admission response")
+ current = json.loads(payload)
+ 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."
+ )
+ return 2
+ except urllib.error.URLError as error:
+ print(f"Current merge-request head could not be verified (transport {type(error.reason).__name__}).")
+ return 2
+ except (OSError, ValueError) as error:
+ print(f"Current merge-request head could not be verified ({type(error).__name__}).")
+ return 2
+ if not eligible(env, current):
+ print("Provider jobs require the current same-project MR head or a protected default branch.")
+ return 2
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/ci/feedback.py b/ci/feedback.py
new file mode 100644
index 00000000..3b1d6eec
--- /dev/null
+++ b/ci/feedback.py
@@ -0,0 +1,1160 @@
+# SPDX-License-Identifier: Apache-2.0
+# ruff: noqa: INP001, T201 -- trusted CI entrypoint with fixed diagnostics.
+"""Comment on current PR/MR evidence without executing artifacts or source code.
+
+GitHub authenticates the producer through its signed reusable-job receipt.
+GitLab authenticates this protected downstream job through its own ID token,
+then binds its source job, producer configuration and exact aggregate job.
+All artifact processing is bounded in memory; HTML is never interpreted.
+"""
+
+from __future__ import annotations
+
+import argparse
+import base64
+import binascii
+import http.client
+import io
+import json
+import os
+import re
+import stat
+import sys
+import urllib.error
+import urllib.parse
+import urllib.request
+import zipfile
+from datetime import datetime
+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__:
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
+
+try:
+ import github_api
+ import 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
+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_reports
+
+MARKER = "<!-- skillevaluator-all-tiers-report -->"
+RUN_MARKER = re.compile(r"<!-- skillevaluator-all-tiers-run:([1-9][0-9]*):([1-9][0-9]*) -->")
+CALLER_PATH = ".github/workflows/skill-checks-all-tiers.yml"
+MAX_BYTES = 64 * 1024 * 1024
+MAX_FILE_BYTES = 32 * 1024 * 1024
+MAX_BODY_BYTES = 60000
+# Size the report member bound from the documented per-run skill limit
+# (run_tier1.MAX_SKILLS). Each skill retains six Tier 1 files (JSON, HTML,
+# 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
+MAX_AGGREGATE_MEMBERS = 64 # manifests, summaries, indexes and tier directories
+MAX_FILES = MAX_SKILLS * MEMBERS_PER_SKILL + MAX_AGGREGATE_MEMBERS
+# A Tier 2/3 skill whose execution failed or is incomplete, or whose worker exited
+# abnormally, and a failed Tier 2 catalog also retain worker diagnostics
+# (ci/diagnostics.py), which this job never opens. The producer keeps at most
+# diagnostics.MAX_TRIALS trials per skill and shares a per-tier budget of
+# diagnostics.MAX_TIER_FILES logs and diagnostics.MAX_TIER_BYTES. This bound
+# does not rely on those caps: every root may hold index.json plus
+# diagnostics.MAX_FILES logs (command.log included) and
+# diagnostics.MAX_TOTAL_BYTES. It is separate from the report member and
+# expansion limits, allowing each retained file up to seven nested directory
+# entries (Harbor job/trial/agent/setup paths on GitLab).
+DIAGNOSTIC_ROOTS = 2 * MAX_SKILLS + 1
+DIAGNOSTIC_FILES = 100 + 1 # diagnostics.MAX_FILES logs plus index.json
+MAX_DIAGNOSTIC_MEMBERS = DIAGNOSTIC_ROOTS * DIAGNOSTIC_FILES * 8
+MAX_DIAGNOSTIC_BYTES = DIAGNOSTIC_ROOTS * (8 + 1) * 1024 * 1024 # logs plus one index.json
+DIAGNOSTIC_PATH = r"(?:tier[23]/skill-[0-9]{3}|tier2/catalog)/diagnostics/.*"
+MAX_PAGES = 10
+MAX_MARKER_RUNS = 20
+MAX_REDIRECTS = 5
+REDIRECT_CODES = frozenset({301, 302, 303, 307, 308})
+GL_AUDIENCE = "urn:skillevaluator:feedback:v1"
+
+
+class FeedbackError(ValueError):
+ """Fixed diagnostic containing no credentials or untrusted response text."""
+
+
+def _require(condition, message):
+ if not condition:
+ raise FeedbackError(message)
+
+
+def _positive(value):
+ _require(type(value) is int and value > 0, "A positive API identity is required.")
+ return value
+
+
+def _json(raw):
+ return github_api.strict_json(raw, FeedbackError, "Feedback evidence is invalid JSON.")
+
+
+def _time(value):
+ try:
+ parsed = datetime.fromisoformat(value)
+ _require(parsed.tzinfo is not None, "An API timestamp lacks its timezone.")
+ return parsed
+ except (ValueError, TypeError, AttributeError) as exc:
+ raise FeedbackError("An API timestamp is invalid.") from exc
+
+
+def _safe_path(value):
+ return (
+ isinstance(value, str)
+ and bool(value)
+ and len(value) <= 4096
+ and not any(c in value for c in "\\:%?#")
+ and not value.startswith("/")
+ and not any(ord(c) < 32 or ord(c) == 127 for c in value)
+ and all(p not in {"", ".", ".."} for p in value.split("/"))
+ )
+
+
+def read_results(raw: bytes, *, prefix: str = "") -> dict:
+ """Validate exact retained native JSON; never extract or interpret HTML."""
+ _require(len(raw) <= MAX_BYTES, "The aggregate archive exceeds its size limit.")
+ try:
+ with zipfile.ZipFile(io.BytesIO(raw)) as archive:
+ members = {}
+ reports = total = diagnostic_members = diagnostic_total = 0
+ diagnostic = re.compile(re.escape(prefix) + DIAGNOSTIC_PATH)
+ for entry in archive.infolist():
+ name = entry.filename
+ kind = stat.S_IFMT(entry.external_attr >> 16)
+ _require(
+ not entry.flag_bits & 1 and kind in {0, stat.S_IFREG, stat.S_IFDIR},
+ "The aggregate archive contains a linked or encrypted member.",
+ )
+ _require(
+ _safe_path(name.rstrip("/") if entry.is_dir() else name),
+ "The aggregate archive contains an unsafe member path.",
+ )
+ _require(name not in members, "The aggregate archive contains duplicate members.")
+ members[name] = entry
+ if diagnostic.fullmatch(name):
+ diagnostic_members += 1
+ diagnostic_total += entry.file_size
+ else:
+ reports += 1
+ total += entry.file_size
+ _require(
+ reports <= MAX_FILES
+ and diagnostic_members <= MAX_DIAGNOSTIC_MEMBERS
+ and 0 <= entry.file_size <= MAX_FILE_BYTES
+ and total <= MAX_BYTES
+ and diagnostic_total <= MAX_DIAGNOSTIC_BYTES,
+ "The aggregate archive exceeds its member or expansion limits.",
+ )
+
+ def read(name):
+ _require(name in members and not members[name].is_dir(), "Required retained evidence is missing.")
+ with archive.open(members[name]) as source:
+ result = source.read(MAX_FILE_BYTES + 1)
+ _require(len(result) <= MAX_FILE_BYTES, "Retained evidence exceeds its size limit.")
+ return result
+
+ result = validate_manifest(_json(read(prefix + "ci-results.json")))
+ from skillevaluator.reporting.retained import retained_results
+ from skillevaluator.reporting.run_status import resolve_run_status
+
+ seen = set()
+ for tier in result["tiers"]:
+ # Comment counters come from validated native findings, never
+ # from arbitrary producer-supplied manifest metrics.
+ tier.pop("metrics", None)
+ for skill in tier["skills"]:
+ skill.pop("metrics", None)
+ json_path, html_path = skill["report_json"], skill["report_html"]
+ if json_path is None:
+ _require(skill["status"] not in {"passed", "failed"}, "A verdict lacks its retained evidence.")
+ _require(html_path is None, "An HTML report lacks its retained JSON.")
+ continue
+ pattern = rf"tier{tier['tier']}/skill-[0-9]{{3}}/skillevaluator-tier{tier['tier']}\.json"
+ _require(
+ re.fullmatch(pattern, json_path) is not None and json_path not in seen,
+ "Native evidence does not have a unique canonical tier path.",
+ )
+ seen.add(json_path)
+ _require(
+ html_path == json_path.removesuffix(".json") + ".html",
+ "Native HTML and JSON evidence paths disagree.",
+ )
+ _require(
+ prefix + html_path in members and not members[prefix + html_path].is_dir(),
+ "The retained native HTML report is missing.",
+ )
+ native = _json(read(prefix + json_path))
+ retained = retained_results(native, copy_metadata=False, allowed_tiers={tier["tier"]})
+ native_status = resolve_run_status(retained).tiers[tier["tier"]].status.value
+ status = native_status
+ if tier["tier"] == 3 and status == "passed" and native.get("tier3", {}).get("verdict") == "neutral":
+ status = "neutral"
+ # A producer may downgrade a clean result after an execution
+ # error, before any neutral mapping; it may never promote
+ # failed/incomplete evidence.
+ _require(
+ skill["status"] == status
+ or (skill["status"] == "incomplete" and native_status in {"passed", "not_run"}),
+ "The aggregate verdict contradicts retained native evidence.",
+ )
+ if tier["tier"] == 3 and skill["status"] in {"passed", "neutral"}:
+ _require(
+ tier3_execution_complete(native),
+ "Tier 3 passing or neutral evidence lacks complete paired execution.",
+ )
+ skill["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
+ if tier["tier"] == 3 and not tier3_execution_complete(native):
+ skill["metrics"]["issue_count_known"] = False
+ skill["metrics"].pop("score", None)
+ skill["metrics"].pop("skill_lift", None)
+ return result
+ except FeedbackError:
+ raise
+ except (ValueError, TypeError, KeyError, AttributeError, OSError, RuntimeError, zipfile.BadZipFile) as exc:
+ raise FeedbackError("The aggregate archive or retained evidence is invalid.") from exc
+
+
+def _body(manifest, run_url, artifact_url, receipt):
+ # Every skill links once to the combined report archive. Its members are
+ # navigated through index.html after download, never as fabricated web URLs.
+ rendered = render_comment_summary(manifest, artifact_url)
+ body = (
+ f"{MARKER}\n<!-- skillevaluator-all-tiers-run:{receipt[0]}:{receipt[1]} -->\n"
+ f"[Evaluation run]({run_url})\n\n{rendered}\n\n"
+ f"Commit: `{manifest['commit']}` · Environment: {manifest['environment']}\n"
+ )
+ _require(len(body.encode("utf-8")) <= MAX_BODY_BYTES, "The feedback comment exceeds its size limit.")
+ return body
+
+
+def _identity(comment):
+ matches = RUN_MARKER.findall(comment["body"])
+ _require(len(matches) == 1, "An owned comment lacks a unique producer receipt.")
+ return tuple(int(n) for n in matches[0])
+
+
+def _listing(api, path, *, key=None):
+ rows = []
+ for page in range(1, MAX_PAGES + 1):
+ value = api.get(f"{path}{'&' if '?' in path else '?'}per_page=100&page={page}")
+ items = value.get(key) if key and isinstance(value, dict) else value
+ _require(
+ isinstance(items, list) and len(items) <= 100 and all(isinstance(i, dict) for i in items),
+ "An API listing has an unsupported shape.",
+ )
+ rows.extend(items)
+ if len(items) < 100:
+ return rows
+ raise FeedbackError("An API listing exceeds its pagination limit.")
+
+
+def _upsert(api, *, collection, member, owned, body, receipt, current, method="patch", verified=None):
+ comments = [c for c in _listing(api, collection) if owned(c)]
+ stale = []
+ if verified is not None:
+ # A shared bot identity can be used by other workflows. Defer only to
+ # markers bound to a genuine producer run; overwrite unverifiable ones.
+ stale = [c for c in comments if not verified(c)]
+ comments = [c for c in comments if c not in stale]
+ _require(len(comments) <= 1, "Multiple owned report comments require manual reconciliation.")
+ if any(_identity(c) > receipt for c in comments):
+ return {"comment_action": "skipped", "comment_reason": "A newer report comment already exists."}
+ if not current():
+ return {"comment_action": "skipped", "comment_reason": "The source head or producer attempt changed."}
+ canonical = comments[0] if comments else (stale[0] if stale else None)
+ if canonical:
+ identifier = _positive(canonical.get("id"))
+ # Re-read ownership immediately before updating an existing note.
+ check = api.get(member.format(id=identifier))
+ _require(
+ owned(check) and check.get("id") == identifier and check.get("body") == canonical["body"],
+ "The report comment changed ownership or content before update.",
+ )
+ if canonical in comments and _identity(check) > receipt:
+ return {"comment_action": "skipped", "comment_reason": "A newer report comment already exists."}
+ if canonical["body"] == body:
+ action = "unchanged"
+ else:
+ response = getattr(api, method)(member.format(id=identifier), {"body": body})
+ _require(response.get("id") == identifier, "The API did not acknowledge the expected comment update.")
+ action = "updated"
+ else:
+ response = api.post(collection, {"body": body})
+ identifier = _positive(response.get("id"))
+ action = "created"
+ check = api.get(member.format(id=identifier))
+ _require(
+ isinstance(check, dict) and check.get("id") == identifier and owned(check) and check.get("body") == body,
+ "The comment readback does not match the expected bot-owned content.",
+ )
+ return {"comment_action": action, "comment_id": str(identifier)}
+
+
+def _github_run(run, repository, run_id, attempt):
+ _require(
+ isinstance(run, dict)
+ and run.get("id") == run_id
+ and run.get("run_attempt") == attempt
+ and run.get("repository", {}).get("full_name") == repository,
+ "The run identity or latest attempt does not match the selected producer.",
+ )
+ _require(
+ run.get("event") == "pull_request"
+ and run.get("status") == "completed"
+ and run.get("path") == CALLER_PATH
+ and isinstance(run.get("head_sha"), str)
+ and github_api.COMMIT_SHA.fullmatch(run["head_sha"]),
+ "Only completed approved pull-request workflow runs can receive feedback.",
+ )
+
+
+def _github_artifacts(api, root, run):
+ listing = api.get(f"{root}/actions/runs/{run['id']}/artifacts?per_page=100")
+ _require(
+ isinstance(listing, dict)
+ and isinstance(listing.get("artifacts"), list)
+ and type(listing.get("total_count")) is int
+ and listing["total_count"] <= 100,
+ "The aggregate artifact listing exceeds its limit.",
+ )
+ started, finished = _time(run.get("run_started_at")), _time(run.get("updated_at"))
+ _require(started <= finished, "The producer attempt has an invalid time interval.")
+ selected = []
+ for prefix in ("skill-evaluator-results", "skill-evaluator-results-provenance"):
+ matches = [
+ a
+ for a in listing["artifacts"]
+ if isinstance(a, dict)
+ and a.get("name") == f"{prefix}-attempt-{run['run_attempt']}"
+ and a.get("expired") is False
+ ]
+ _require(len(matches) == 1, "The exact aggregate or provenance artifact is missing or ambiguous.")
+ artifact = matches[0]
+ _positive(artifact.get("id"))
+ _require(
+ artifact.get("workflow_run", {}).get("id") == run["id"]
+ and artifact["workflow_run"].get("head_sha") == run["head_sha"]
+ and started <= _time(artifact.get("created_at")) <= finished,
+ "An artifact does not belong to the selected producer attempt and revision.",
+ )
+ _require(
+ type(artifact.get("size_in_bytes")) is int
+ and 0 < artifact["size_in_bytes"] <= (64 * 1024 if prefix.endswith("provenance") else MAX_BYTES),
+ "An artifact exceeds its size limit.",
+ )
+ selected.append(artifact)
+ 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."""
+ _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)
+ 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
+ )
+ _require(match is not None, "An immutable trusted reusable workflow reference is required.")
+ workflow, sha = match.groups()
+ references = run.get("referenced_workflows")
+ _require(
+ isinstance(references, list)
+ and len(references) <= 32
+ and sum(r.get("path") == reference and r.get("sha") == sha for r in references if isinstance(r, dict)) == 1,
+ "The run did not use exactly the approved immutable reusable workflow.",
+ )
+ raw_pins = os.environ.get("SKILL_EVAL_TRUSTED_CALLER_BLOBS", "")
+ pins = [s.strip() for s in re.split(r"[,\n]", raw_pins)]
+ _require(
+ 0 < len(pins) <= 32 and all(github_api.COMMIT_SHA.fullmatch(p) for p in pins),
+ "Reviewed caller Git blob identities are required.",
+ )
+ artifact, provenance = _github_artifacts(api, root, run)
+ try:
+ identity = verify_receipt(
+ api.download_artifact(provenance["id"]),
+ repository=repository,
+ run=run,
+ evaluator_workflow=workflow,
+ evaluator_sha=sha,
+ caller_workflow_path=CALLER_PATH,
+ )
+ except ProvenanceError as exc:
+ raise FeedbackError("The producer execution receipt is invalid.") from exc
+ caller = api.get(f"{root}/contents/{CALLER_PATH}?ref={identity['workflow_sha']}")
+ _require(
+ isinstance(caller, dict)
+ and caller.get("type") == "file"
+ and caller.get("path") == CALLER_PATH
+ and caller.get("sha") in pins,
+ "The executed caller workflow blob is not approved.",
+ )
+ manifest = read_results(api.download_artifact(artifact["id"]))
+ _require(
+ all(
+ manifest[k] == v
+ for k, v in {
+ "repository": repository,
+ "platform": "github",
+ "commit": run["head_sha"],
+ "run_id": str(run_id),
+ "run_attempt": str(attempt),
+ }.items()
+ ),
+ "The report manifest does not match the exact producer attempt and revision.",
+ )
+ 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),
+ "The producer must identify exactly one pull request.",
+ )
+ number = _positive(candidates[0].get("number"))
+
+ def current():
+ pr = api.get(f"{root}/pulls/{number}")
+ latest = api.get(f"{root}/actions/runs/{run_id}")
+ return (
+ pr.get("state") == "open"
+ and pr.get("head", {}).get("sha") == run["head_sha"]
+ and all(pr.get(part, {}).get("repo", {}).get("full_name") == repository for part in ("head", "base"))
+ and latest.get("run_attempt") == attempt
+ and latest.get("head_sha") == run["head_sha"]
+ )
+
+ if not current():
+ return {"comment_action": "skipped", "comment_reason": "The pull request head or producer attempt changed."}
+ run_url = f"https://github.com/{repository}/actions/runs/{run_id}"
+ body = _body(manifest, run_url, f"{run_url}/artifacts/{artifact['id']}", (run_id, attempt))
+ bot = os.environ.get("SKILL_EVAL_BOT_LOGIN", "github-actions[bot]")
+ _require(re.fullmatch(r"[A-Za-z0-9_-]+\[bot\]", bot), "The configured comment owner is not a bot login.")
+
+ def owned(comment):
+ return (
+ isinstance(comment, dict)
+ and comment.get("user", {}).get("login") == bot
+ and comment["user"].get("type") == "Bot"
+ and isinstance(comment.get("body"), str)
+ and comment["body"].startswith(MARKER + "\n")
+ )
+
+ producers = {run_id: run}
+
+ def verified(comment):
+ # Same-repository workflows can post as github-actions[bot]; bind the
+ # marker to an existing same-repository producer run of this caller for
+ # this PR head. Runs with recorded pull requests must include this PR.
+ markers = RUN_MARKER.findall(comment["body"])
+ if len(markers) != 1:
+ return False
+ marker_run, marker_attempt = (int(n) for n in markers[0])
+ if marker_run not in producers:
+ if len(producers) > MAX_MARKER_RUNS:
+ return False
+ try:
+ producers[marker_run] = api.get(f"{root}/actions/runs/{marker_run}")
+ except urllib.error.HTTPError as exc:
+ if exc.code != 404:
+ raise
+ producers[marker_run] = None
+ marked = producers[marker_run]
+ if not isinstance(marked, dict):
+ return False
+ pulls = marked.get("pull_requests")
+ return (
+ marked.get("id") == marker_run
+ and marked.get("path") == CALLER_PATH
+ and marked.get("event") == "pull_request"
+ and isinstance(marked.get("repository"), dict)
+ and marked["repository"].get("full_name") == repository
+ and isinstance(marked.get("head_repository"), dict)
+ and marked["head_repository"].get("full_name") == repository
+ and (
+ not pulls
+ or (isinstance(pulls, list) and any(isinstance(p, dict) and p.get("number") == number for p in pulls))
+ )
+ and marked.get("head_sha") == run["head_sha"]
+ and type(marked.get("run_attempt")) is int
+ and marked["run_attempt"] >= marker_attempt
+ )
+
+ result = _upsert(
+ api,
+ collection=f"{root}/issues/{number}/comments",
+ member=f"{root}/issues/comments/{{id}}",
+ owned=owned,
+ body=body,
+ receipt=(run_id, attempt),
+ current=current,
+ verified=verified,
+ )
+ if "comment_id" in result:
+ result["comment_url"] = f"https://github.com/{repository}/pull/{number}#issuecomment-{result['comment_id']}"
+ return result
+
+
+def _gitlab_origin(api_url):
+ try:
+ parsed = urllib.parse.urlsplit(api_url)
+ _require(
+ parsed.scheme == "https"
+ and bool(parsed.hostname)
+ and not parsed.username
+ and not parsed.password
+ and re.fullmatch(r"(?:/[A-Za-z0-9._~-]+)*/api/v4", parsed.path)
+ and all(part not in {".", ".."} for part in parsed.path.split("/"))
+ and not parsed.query
+ and not parsed.fragment
+ and "\\" not in api_url
+ and not any(ord(c) < 33 for c in api_url),
+ "GitLab requires an exact HTTPS API origin ending in /api/v4.",
+ )
+ _require(parsed.port is None or 1 <= parsed.port <= 65535, "Invalid GitLab API port.")
+ return f"https://{parsed.netloc}" + parsed.path.removesuffix("/api/v4")
+ except (ValueError, TypeError) as exc:
+ raise FeedbackError("The GitLab API URL is invalid.") from exc
+
+
+def _artifact_redirect(base, location):
+ """Resolve one object-storage redirect to an HTTPS URL without credentials."""
+ try:
+ url = urllib.parse.urljoin(base, location) if isinstance(location, str) and location else ""
+ parsed = urllib.parse.urlsplit(url)
+ valid = (
+ parsed.scheme == "https"
+ and bool(parsed.hostname)
+ and not parsed.username
+ and not parsed.password
+ and (parsed.port is None or 1 <= parsed.port <= 65535)
+ and "\\" not in url
+ and not any(ord(c) < 33 or ord(c) == 127 for c in url)
+ )
+ except (ValueError, TypeError):
+ valid = False
+ _require(valid, "The GitLab artifact download redirected to an unsupported location.")
+ return url
+
+
+class GitLabAPI:
+ """Bounded private-token API client; artifact redirects never receive credentials."""
+
+ def __init__(self, api_url: str, project: str, token: str):
+ self.origin = _gitlab_origin(api_url)
+ self.api_url, self.project, self.token = api_url, project, token
+ self.opener = urllib.request.build_opener(github_api._NoRedirect())
+
+ def _call(self, method, path, payload=None, *, binary=False):
+ # Resolve a human namespace once. All later operations use its numeric ID.
+ allowed = path == "/user" or re.fullmatch(r"/projects/[A-Za-z0-9_.%/-]+(?:\?[^\s]*)?", path)
+ _require(
+ allowed
+ and ".." not in path
+ and "\\" not in path
+ and not path.startswith("//")
+ and not any(ord(c) < 33 for c in path),
+ "Only relative GitLab project API paths are supported.",
+ )
+ headers = {
+ "PRIVATE-TOKEN": self.token,
+ "User-Agent": "SkillEvaluator-trusted-feedback",
+ "Accept": "application/octet-stream" if binary else "application/json",
+ }
+ data = None
+ if payload is not None:
+ data = json.dumps(payload, allow_nan=False).encode("utf-8")
+ headers["Content-Type"] = "application/json"
+ request = urllib.request.Request(self.api_url + path, headers=headers, data=data, method=method)
+ with self.opener.open(request, timeout=github_api.TIMEOUT_SECONDS) as response:
+ raw = github_api.bounded_read(
+ response,
+ MAX_BYTES if binary else github_api.MAX_API_BYTES,
+ FeedbackError,
+ "The GitLab API response exceeds its size limit.",
+ )
+ return raw if binary else _json(raw)
+
+ def get(self, path):
+ return self._call("GET", path)
+
+ def post(self, path, payload):
+ return self._call("POST", path, payload)
+
+ def put(self, path, payload):
+ return self._call("PUT", path, payload)
+
+ def graphql(self, query: str, variables: dict) -> dict:
+ """Read server-owned relationships at this instance's fixed GraphQL endpoint."""
+ _require(
+ isinstance(query, str) and 0 < len(query) <= 16384 and isinstance(variables, dict),
+ "The GitLab relationship request is invalid.",
+ )
+ try:
+ data = json.dumps({"query": query, "variables": variables}, allow_nan=False).encode("utf-8")
+ _require(len(data) <= 64 * 1024, "The GitLab relationship request exceeds its size limit.")
+ request = urllib.request.Request(
+ self.origin + "/api/graphql",
+ method="POST",
+ data=data,
+ headers={
+ "PRIVATE-TOKEN": self.token,
+ "Content-Type": "application/json",
+ "Accept": "application/json",
+ "User-Agent": "SkillEvaluator-trusted-feedback",
+ },
+ )
+ with self.opener.open(request, timeout=github_api.TIMEOUT_SECONDS) as response:
+ _require(response.getcode() == 200, "The GitLab relationship response has an invalid HTTP status.")
+ raw = github_api.bounded_read(
+ response,
+ github_api.MAX_API_BYTES,
+ FeedbackError,
+ "The GitLab relationship response exceeds its size limit.",
+ )
+ payload = _json(raw)
+ except FeedbackError:
+ raise
+ except (http.client.HTTPException, OSError, TypeError, ValueError, RecursionError):
+ raise FeedbackError("The GitLab relationship request could not be verified.") from None
+ _require(
+ isinstance(payload, dict)
+ and ("errors" not in payload or payload["errors"] == [])
+ and isinstance(payload.get("data"), dict),
+ "The GitLab relationship response is incomplete or invalid.",
+ )
+ return payload["data"]
+
+ def download_artifact(self, job_id):
+ _positive(job_id)
+ path = f"/projects/{self.project}/jobs/{job_id}/artifacts"
+ try:
+ return self._call("GET", path, binary=True)
+ except urllib.error.HTTPError as exc:
+ if exc.code not in REDIRECT_CODES:
+ raise
+ url, location = self.api_url + path, exc.headers.get("Location")
+ # Object storage serves a signed URL; never forward PRIVATE-TOKEN to it.
+ for _ in range(MAX_REDIRECTS):
+ url = _artifact_redirect(url, location)
+ request = urllib.request.Request(url, headers={"User-Agent": "SkillEvaluator-trusted-feedback"})
+ try:
+ with self.opener.open(request, timeout=github_api.TIMEOUT_SECONDS) as response:
+ return github_api.bounded_read(
+ response, MAX_BYTES, FeedbackError, "The GitLab artifact exceeds its size limit."
+ )
+ except urllib.error.HTTPError as exc:
+ if exc.code not in REDIRECT_CODES:
+ raise
+ location = exc.headers.get("Location")
+ raise FeedbackError("The GitLab artifact download exceeded its redirect limit.")
+
+
+def _gitlab_signing_keys(origin):
+ # GitLab's documented fixed JWKS endpoint; never follow provider-controlled
+ # discovery URLs or attach the private API token to a key fetch.
+ request = urllib.request.Request(
+ origin + "/oauth/discovery/keys",
+ headers={"Accept": "application/json", "User-Agent": "SkillEvaluator-trusted-feedback"},
+ )
+ with urllib.request.build_opener(github_api._NoRedirect()).open(request, timeout=30) as response:
+ keys = _json(github_api.bounded_read(response, 256 * 1024, FeedbackError))
+ _require(
+ isinstance(keys, dict) and isinstance(keys.get("keys"), list) and 1 <= len(keys["keys"]) <= 32,
+ "GitLab returned an invalid signing key set.",
+ )
+ return keys["keys"]
+
+
+def verify_gitlab_job(api_url: str, token: str) -> dict:
+ """Authenticate the actual protected job independently of overrideable CI variables."""
+ import jwt
+
+ origin = _gitlab_origin(api_url)
+ _require(isinstance(token, str) and 0 < len(token) <= 32768, "A bounded GitLab feedback job ID token is required.")
+ try:
+ header = jwt.get_unverified_header(token)
+ _require(
+ header.get("alg") == "RS256"
+ and header.get("typ") == "JWT"
+ and isinstance(header.get("kid"), str)
+ and 0 < len(header["kid"]) <= 256,
+ "The GitLab job token uses an unsupported signing header.",
+ )
+ matches = [k for k in _gitlab_signing_keys(origin) if isinstance(k, dict) and k.get("kid") == header["kid"]]
+ _require(
+ len(matches) == 1
+ and matches[0].get("kty") == "RSA"
+ and matches[0].get("alg", "RS256") == "RS256"
+ and matches[0].get("use", "sig") == "sig",
+ "The GitLab job signing key is unavailable.",
+ )
+ key = jwt.PyJWK.from_dict(matches[0], algorithm="RS256").key
+ _require(2048 <= key.key_size <= 8192, "The GitLab job signing key has an unsupported size.")
+ claims = jwt.decode(
+ token,
+ key,
+ algorithms=["RS256"],
+ audience=GL_AUDIENCE,
+ issuer=origin,
+ options={"strict_aud": True, "require": ["exp", "iat", "nbf", "iss", "aud"]},
+ )
+ for field in ("project_id", "pipeline_id", "job_id"):
+ _require(
+ isinstance(claims.get(field), str) and re.fullmatch(r"[1-9][0-9]{0,19}", claims[field]),
+ "The GitLab job token lacks an immutable execution identity.",
+ )
+ _require(
+ claims.get("ref_protected") in (True, "true")
+ and claims.get("ref_type") == "branch"
+ and claims.get("pipeline_source") == "pipeline"
+ and isinstance(claims.get("sha"), str)
+ and github_api.COMMIT_SHA.fullmatch(claims["sha"])
+ and isinstance(claims.get("ref"), str)
+ and bool(claims["ref"]),
+ "Only a protected downstream branch job may publish feedback.",
+ )
+ except FeedbackError:
+ raise
+ except (jwt.PyJWTError, KeyError, TypeError, ValueError, OSError, urllib.error.URLError) as exc:
+ raise FeedbackError("The GitLab feedback job identity could not be authenticated.") from exc
+ return {name: claims[name] for name in ("project_id", "pipeline_id", "job_id", "ref", "sha")}
+
+
+def validate_gitlab_config(document):
+ """Allow the installed pinned producer and the downstream-only local include.
+
+ Matching only the root blob would otherwise leave transitive local includes
+ mutable on the MR branch. The generated configuration has exactly these two
+ includes; supporting other topologies requires an explicit trust contract.
+ """
+ import yaml
+
+ if isinstance(document, bytes):
+ _require(len(document) <= 1024 * 1024, "The producer CI configuration exceeds its size limit.")
+ try:
+ document = yaml.safe_load(document)
+ except (ValueError, yaml.YAMLError, UnicodeError) as exc:
+ raise FeedbackError("The producer CI configuration is invalid.") from exc
+ _require(isinstance(document, dict), "The producer CI configuration must be an object.")
+ includes = document.get("include")
+ _require(
+ isinstance(includes, list) and len(includes) == 2, "The producer config has unsupported transitive includes."
+ )
+ remote, local = [], []
+ for item in includes:
+ _require(isinstance(item, dict), "The producer config has an unsupported include.")
+ if set(item) == {"remote"}:
+ _require(
+ isinstance(item["remote"], str)
+ and re.fullmatch(
+ r"https://raw\.githubusercontent\.com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+/[0-9a-f]{40}/ci/gitlab/all-tiers\.yml",
+ item["remote"],
+ ),
+ "The producer config must include an immutable evaluator revision.",
+ )
+ remote.append(item)
+ else:
+ expected = '$CI_PIPELINE_SOURCE == "pipeline" && $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH && $SKILL_EVAL_FEEDBACK == "true"'
+ _require(
+ item == {"local": ".gitlab/skill-feedback.yml", "rules": [{"if": expected}]},
+ "Local CI includes must be restricted to the trusted downstream feedback pipeline.",
+ )
+ local.append(item)
+ _require(
+ len(remote) == len(local) == 1, "The producer config must have one pinned evaluator and one feedback include."
+ )
+
+
+def gitlab_feedback(api, api_url: str, project: str, pipeline_id: int) -> dict:
+ """Bind the trusted downstream job to one current same-project MR producer."""
+ _positive(pipeline_id)
+ origin = _gitlab_origin(api_url)
+ _require(
+ isinstance(project, str)
+ and re.fullmatch(r"[A-Za-z0-9_.-]+(?:/[A-Za-z0-9_.-]+)*", project)
+ and ".." not in project,
+ "A valid GitLab project ID or namespace path is required.",
+ )
+ info = api.get("/projects/" + urllib.parse.quote(project, safe=""))
+ project_id = _positive(info.get("id"))
+ root = f"/projects/{project_id}"
+ if hasattr(api, "project") and isinstance(api.project, str):
+ api.project = str(project_id)
+ identity = verify_gitlab_job(api_url, os.environ.get("SKILL_EVAL_GITLAB_ID_TOKEN", ""))
+ _require(identity["project_id"] == str(project_id), "The authenticated job belongs to a different project.")
+ default = info.get("default_branch")
+ _require(
+ isinstance(default, str)
+ and identity["ref"] == default
+ and info.get("ci_config_path") in (None, "", ".gitlab-ci.yml"),
+ "The feedback job must use the protected default branch and default CI config path.",
+ )
+ publisher = api.get(f"{root}/pipelines/{identity['pipeline_id']}")
+ _require(
+ publisher.get("id") == int(identity["pipeline_id"])
+ and publisher.get("sha") == identity["sha"]
+ and publisher.get("ref") == default
+ and publisher.get("source") == "pipeline",
+ "The downstream pipeline does not match its authenticated protected job.",
+ )
+ branch = api.get(f"{root}/repository/branches/{urllib.parse.quote(default, safe='')}")
+ _require(
+ branch.get("protected") is True and branch.get("commit", {}).get("id") == identity["sha"],
+ "The feedback pipeline is no longer the current protected default branch revision.",
+ )
+ job = api.get(f"{root}/jobs/{identity['job_id']}")
+ _require(
+ job.get("id") == int(identity["job_id"])
+ and job.get("name") == "skill-evaluation-feedback"
+ and job.get("pipeline", {}).get("id") == publisher["id"]
+ and job.get("ref") == default
+ and job.get("commit", {}).get("id") == identity["sha"]
+ and job.get("status") == "running",
+ "The authenticated job is not the exact running trusted feedback job.",
+ )
+ variables = api.get(f"{root}/pipelines/{publisher['id']}/variables")
+ expected_variables = {"SKILL_EVAL_FEEDBACK": "true", "SKILL_EVAL_SOURCE_PIPELINE_ID": str(pipeline_id)}
+ # GitLab adds an opaque file variable for API trigger parameters. It is
+ # never parsed, executed or published; only the server-bound relation below
+ # authenticates the source job and pipeline.
+ _require(
+ isinstance(variables, list)
+ and len(variables) in {2, 3}
+ and all(isinstance(v, dict) and isinstance(v.get("key"), str) for v in variables)
+ and len({v["key"] for v in variables}) == len(variables)
+ and expected_variables.keys() <= {v["key"] for v in variables}
+ and all(
+ (
+ v["key"] in expected_variables
+ and v.get("variable_type") == "env_var"
+ and v.get("value") == expected_variables[v["key"]]
+ )
+ or (
+ v["key"] == "TRIGGER_PAYLOAD"
+ and v.get("variable_type") == "file"
+ and isinstance(v.get("value"), str)
+ and len(v["value"]) <= 64 * 1024
+ )
+ for v in variables
+ ),
+ "The downstream pipeline has unsupported forwarded variables.",
+ )
+ source = api.get(f"{root}/pipelines/{pipeline_id}")
+ # Other consumer jobs may keep the source pipeline pending, running or
+ # manual; completion is proven by the bound aggregate and request jobs.
+ _require(
+ source.get("id") == pipeline_id
+ and source.get("source") == "merge_request_event"
+ and isinstance(source.get("sha"), str)
+ and github_api.COMMIT_SHA.fullmatch(source["sha"]),
+ "Only same-project merge-request producers may receive feedback.",
+ )
+ _require(
+ api.get(f"{root}/pipelines/{pipeline_id}/variables") == [],
+ "Source merge-request pipelines may not override trusted producer configuration through pipeline variables.",
+ )
+ namespace = info.get("path_with_namespace")
+ _require(
+ isinstance(namespace, str) and re.fullmatch(r"[A-Za-z0-9_.-]+(?:/[A-Za-z0-9_.-]+)+", namespace),
+ "The authenticated GitLab project has no valid namespace.",
+ )
+ relationship = api.graphql(
+ "query($project:ID!,$pipeline:CiPipelineID!){project(fullPath:$project){fullPath "
+ "pipeline(id:$pipeline){id project{fullPath} sourceJob{id} "
+ "upstream{id project{fullPath} mergeRequest{iid sourceProjectId targetProjectId}}}}}",
+ {"project": namespace, "pipeline": f"gid://gitlab/Ci::Pipeline/{publisher['id']}"},
+ )
+ relation_project = relationship.get("project") if isinstance(relationship, dict) else None
+ relation = relation_project.get("pipeline") if isinstance(relation_project, dict) else None
+ _require(
+ isinstance(relation_project, dict)
+ and relation_project.get("fullPath") == namespace
+ and isinstance(relation, dict)
+ and relation.get("id") == f"gid://gitlab/Ci::Pipeline/{publisher['id']}"
+ and isinstance(relation.get("project"), dict)
+ and relation["project"].get("fullPath") == namespace
+ and isinstance(relation.get("upstream"), dict)
+ and relation["upstream"].get("id") == f"gid://gitlab/Ci::Pipeline/{pipeline_id}"
+ and isinstance(relation["upstream"].get("project"), dict)
+ and relation["upstream"]["project"].get("fullPath") == namespace
+ and isinstance(relation.get("sourceJob"), dict),
+ "The publisher lacks a server-bound same-project source pipeline and job.",
+ )
+ source_job_gid = relation["sourceJob"].get("id")
+ source_job_match = (
+ re.fullmatch(r"gid://gitlab/Ci::Build/([1-9][0-9]{0,29})", source_job_gid)
+ if isinstance(source_job_gid, str)
+ else None
+ )
+ _require(source_job_match is not None, "The publisher source must be an ordinary authenticated request job.")
+ request_job_id = int(source_job_match[1])
+
+ # Read both configurations at immutable API revisions. A pipeline variable
+ # allowlist is not a trust anchor because upstream variables can override it.
+ def config(sha):
+ value = api.get(f"{root}/repository/files/.gitlab-ci.yml?ref={sha}")
+ _require(
+ value.get("file_path") == ".gitlab-ci.yml"
+ and isinstance(value.get("blob_id"), str)
+ and github_api.COMMIT_SHA.fullmatch(value["blob_id"]),
+ "The producer config lacks a Git blob identity.",
+ )
+ _require(
+ value.get("encoding") == "base64"
+ and isinstance(value.get("content"), str)
+ and len(value["content"]) <= 2 * 1024 * 1024,
+ "The CI config lacks bounded source content.",
+ )
+ try:
+ validate_gitlab_config(base64.b64decode(value["content"].replace("\n", ""), validate=True))
+ except (ValueError, binascii.Error) as exc:
+ raise FeedbackError("The CI config source is invalid.") from exc
+ return value["blob_id"]
+
+ _require(
+ config(source["sha"]) == config(identity["sha"]),
+ "The producer CI config differs from the trusted default-branch config.",
+ )
+ linked_mr = relation["upstream"].get("mergeRequest")
+ linked_iid = linked_mr.get("iid") if isinstance(linked_mr, dict) else None
+ _require(
+ isinstance(linked_mr, dict)
+ and isinstance(linked_iid, str)
+ and re.fullmatch(r"[1-9][0-9]{0,18}", linked_iid)
+ and int(linked_iid) <= 2**63 - 1
+ and type(linked_mr.get("sourceProjectId")) is int
+ and linked_mr["sourceProjectId"] == project_id
+ and type(linked_mr.get("targetProjectId")) is int
+ and linked_mr["targetProjectId"] == project_id,
+ "The producer must have one linked same-project merge request.",
+ )
+ number = int(linked_iid)
+
+ def aggregate_job():
+ jobs = _listing(api, f"{root}/pipelines/{pipeline_id}/jobs?include_retried=false")
+ requests = [
+ j for j in jobs if j.get("name") == "skill-evaluation-request-feedback" and j.get("retried") is not True
+ ]
+ request_job = api.get(f"{root}/jobs/{request_job_id}")
+ _require(
+ len(requests) == 1
+ and requests[0].get("id") == request_job_id
+ and request_job.get("id") == request_job_id
+ and request_job.get("name") == "skill-evaluation-request-feedback"
+ and request_job.get("retried") is not True
+ and request_job.get("pipeline", {}).get("id") == pipeline_id
+ and request_job.get("commit", {}).get("id") == source["sha"]
+ and request_job.get("ref") == source.get("ref")
+ and request_job.get("status") in {"running", "success", "failed", "canceled"},
+ "The publisher source request job is not the exact current producer job.",
+ )
+ matches = [j for j in jobs if j.get("name") == "skill-evaluation-aggregate" and j.get("retried") is not True]
+ _require(len(matches) == 1, "The producer has no unique current aggregate job.")
+ value = matches[0]
+ identifier = _positive(value.get("id"))
+ _require(
+ value.get("pipeline", {}).get("id") == pipeline_id
+ and value.get("commit", {}).get("id") == source["sha"]
+ and value.get("ref") == source.get("ref")
+ and value.get("status") in {"success", "failed"}
+ and value.get("artifacts_file", {}).get("filename")
+ == f"skill-evaluator-results-{pipeline_id}-{identifier}.zip"
+ and type(value.get("artifacts_file", {}).get("size")) is int
+ and 0 < value["artifacts_file"]["size"] <= MAX_BYTES,
+ "The exact aggregate job artifact identity is invalid.",
+ )
+ return value
+
+ aggregate = aggregate_job()
+
+ def current():
+ mr = api.get(f"{root}/merge_requests/{number}")
+ latest = aggregate_job()
+ return (
+ mr.get("state") == "opened"
+ and mr.get("sha") == source["sha"]
+ and mr.get("source_project_id") == project_id
+ and mr.get("target_project_id") == project_id
+ and isinstance(mr.get("source_branch"), str)
+ and bool(mr["source_branch"])
+ # Detached MR pipelines use the internal head ref on GitLab 17.8.
+ and source["ref"] in (mr["source_branch"], f"refs/merge-requests/{number}/head")
+ and mr.get("head_pipeline", {}).get("id") == pipeline_id
+ and latest["id"] == aggregate["id"]
+ )
+
+ if not current():
+ return {"comment_action": "skipped", "comment_reason": "The merge request head or producer job changed."}
+ manifest = read_results(api.download_artifact(aggregate["id"]), prefix="skill-evaluator-results/")
+ _require(
+ all(
+ manifest[k] == v
+ for k, v in {
+ "repository": info.get("path_with_namespace"),
+ "platform": "gitlab",
+ "commit": source["sha"],
+ "run_id": str(pipeline_id),
+ "run_attempt": "1",
+ }.items()
+ ),
+ "The report manifest does not match the exact producer pipeline and revision.",
+ )
+ user = api.get("/user")
+ bot_id = _positive(user.get("id"))
+ _require(user.get("bot") is True, "The scoped feedback token must belong to a bot account.")
+ web = info.get("web_url")
+ _require(
+ isinstance(web, str) and web == origin + "/" + info.get("path_with_namespace", ""),
+ "The GitLab project web URL does not match the authenticated API origin.",
+ )
+ # GitLab removes the renderer's terminal LF when storing a note.
+ body = _body(
+ manifest,
+ f"{web}/-/pipelines/{pipeline_id}",
+ f"{web}/-/jobs/{aggregate['id']}/artifacts/download",
+ (pipeline_id, aggregate["id"]),
+ ).removesuffix("\n")
+
+ def owned(note):
+ return (
+ isinstance(note, dict)
+ and note.get("author", {}).get("id") == bot_id
+ and isinstance(note.get("body"), str)
+ and note["body"].startswith(MARKER + "\n")
+ )
+
+ result = _upsert(
+ api,
+ collection=f"{root}/merge_requests/{number}/notes",
+ member=f"{root}/merge_requests/{number}/notes/{{id}}",
+ owned=owned,
+ body=body,
+ receipt=(pipeline_id, aggregate["id"]),
+ current=current,
+ method="put",
+ )
+ if "comment_id" in result:
+ result["comment_url"] = f"{web}/-/merge_requests/{number}#note_{result['comment_id']}"
+ return result
+
+
+def _failure_diagnostic(error: BaseException) -> str:
+ """Expose only trusted code locations and a finite set of failure labels."""
+ line = main.__code__.co_firstlineno
+ trace = error.__traceback__
+ for _ in range(128):
+ if trace is None:
+ break
+ frame = trace.tb_frame
+ if frame.f_globals is globals() and frame.f_code.co_filename == __file__ and frame.f_code.co_name != "_require":
+ line = trace.tb_lineno
+ trace = trace.tb_next
+
+ if isinstance(error, urllib.error.HTTPError):
+ category = "http"
+ elif isinstance(error, (FeedbackError, publish_reports.PublicationError)):
+ category = "validation"
+ elif isinstance(error, (OSError, http.client.HTTPException)):
+ category = "transport"
+ else:
+ category = "response"
+
+ # JWT verification already imports this trusted dependency. Match actual
+ # classes, never an exception's printable name, message, notes or values.
+ jwt = sys.modules.get("jwt")
+ cause = error
+ for _ in range(8):
+ if isinstance(cause, urllib.error.HTTPError):
+ codes = {401: "http_401", 403: "http_403", 404: "http_404", 429: "http_429"}
+ category = codes.get(cause.code, "http") if type(cause.code) is int else "http"
+ return f"check=feedback.py:{line}; category={category}"
+ if jwt is not None:
+ for kind, label in (
+ (jwt.ExpiredSignatureError, "auth_expired"),
+ (jwt.InvalidAudienceError, "auth_audience"),
+ (jwt.InvalidSignatureError, "auth_signature"),
+ (jwt.InvalidIssuerError, "auth_issuer"),
+ (jwt.ImmatureSignatureError, "auth_immature"),
+ (jwt.MissingRequiredClaimError, "auth_missing_claim"),
+ ):
+ if isinstance(cause, kind):
+ return f"check=feedback.py:{line}; category={label}"
+ if isinstance(cause, jwt.PyJWTError):
+ category = "auth_invalid"
+ cause = cause.__cause__
+ if cause is None:
+ break
+ return f"check=feedback.py:{line}; category={category}"
+
+
+def main(argv=None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--platform", choices=("github", "gitlab"), required=True)
+ parser.add_argument("--repository")
+ parser.add_argument("--run-id", type=int)
+ parser.add_argument("--run-attempt", type=int)
+ parser.add_argument("--api-url")
+ parser.add_argument("--project-id")
+ parser.add_argument("--pipeline-id", type=int)
+ args = parser.parse_args(argv)
+ try:
+ if args.platform == "github":
+ token = os.environ.get("GITHUB_TOKEN", "").strip()
+ _require(bool(token), "GITHUB_TOKEN is required for trusted PR feedback.")
+ result = github_feedback(
+ publish_reports.GitHubAPI(args.repository, token), args.repository, args.run_id, args.run_attempt
+ )
+ else:
+ token = os.environ.get("SKILLEVALUATOR_GITLAB_TOKEN", "").strip()
+ _require(bool(token), "A scoped SKILLEVALUATOR_GITLAB_TOKEN is required; CI_JOB_TOKEN cannot post notes.")
+ result = gitlab_feedback(
+ GitLabAPI(args.api_url, args.project_id, token), args.api_url, args.project_id, args.pipeline_id
+ )
+ print(json.dumps(result, sort_keys=True))
+ return 0
+ except (
+ FeedbackError,
+ publish_reports.PublicationError,
+ OSError,
+ ValueError,
+ TypeError,
+ KeyError,
+ AttributeError,
+ urllib.error.URLError,
+ http.client.HTTPException,
+ ) as error:
+ # Do not print provider errors, request URLs, tokens or artifact content.
+ print(
+ "Trusted feedback could not validate its producer, current head, or bot-owned comment. "
+ f"[{_failure_diagnostic(error)}]",
+ file=sys.stderr,
+ )
+ return 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/ci/gitlab/all-tiers.yml b/ci/gitlab/all-tiers.yml
new file mode 100644
index 00000000..72961eb1
--- /dev/null
+++ b/ci/gitlab/all-tiers.yml
@@ -0,0 +1,285 @@
+# SPDX-License-Identifier: Apache-2.0
+# Include this at a reviewed commit. The legacy Tier 1 runner is unchanged.
+variables:
+ SKILL_EVAL_PATHS: skills
+ SKILL_EVAL_SCAN_MODE: auto
+ SKILL_EVAL_MIN_SCORE: '70'
+ SKILL_EVAL_RUNNER: docker
+ SKILL_EVAL_ENVIRONMENT: skillevaluator
+ SKILL_EVAL_TIERS: '1,2,3'
+ SKILL_EVAL_ENV_MODE: docker
+ SKILL_EVAL_PROVIDER: openai
+ SKILL_EVAL_MODEL: ''
+ SKILL_EVAL_EMBEDDING_PROVIDER: ''
+ SKILL_EVAL_EMBEDDING_MODEL: ''
+ SKILL_EVAL_AGENTS: ''
+ SKILL_EVAL_N_ATTEMPTS: '1'
+ SKILL_EVAL_N_CONCURRENT: '1'
+ # Ends min(20 minutes, a quarter) before the 5-hour native job timeout so
+ # setup and the evidence copy fit; the CLI renders the same formula.
+ SKILL_EVAL_TIMEOUT_SECONDS: '16800'
+ SKILL_EVAL_TOOLS_REPOSITORY: NVIDIA/SkillEvaluator
+ GIT_DEPTH: '0'
+ PYTHON_DOTENV_DISABLED: '1'
+
+skill-evaluation:
+ stage: test
+ image:
+ name: "$SKILL_EVAL_IMAGE"
+ entrypoint: [""]
+ variables:
+ GIT_DEPTH: "0"
+ LLM_ENABLED: "false"
+ script:
+ - |
+ set -eu
+ artifact_dir="$CI_PROJECT_DIR/skill-evaluator-report"
+ if [ -e "$artifact_dir" ] || [ -L "$artifact_dir" ]; then
+ echo "skill-evaluator-report already exists; choose a clean checkout for the report." >&2
+ exit 1
+ fi
+ reports_dir="$(mktemp -d /tmp/skillevaluator-reports.XXXXXX)"
+ trap 'rm -rf "$reports_dir"' EXIT
+ export SKILL_PATHS="$SKILL_EVAL_PATHS"
+ export MIN_SCORE="$SKILL_EVAL_MIN_SCORE"
+ # Report links must be HTTPS; an instance served over HTTP gets no job link.
+ case "${CI_JOB_URL:-}" in
+ https://*) export REPORT_RUN_URL="$CI_JOB_URL" ;;
+ *) export REPORT_RUN_URL="" ;;
+ esac
+ export REPORT_COMMIT="${CI_COMMIT_SHA:-}"
+ export REPORT_IMAGE="$SKILL_EVAL_IMAGE"
+ case "$SKILL_EVAL_SCAN_MODE" in
+ auto)
+ if [ "${CI_PIPELINE_SOURCE:-}" = "merge_request_event" ]; then
+ export SCAN_MODE=changed
+ else
+ export SCAN_MODE=all
+ fi
+ ;;
+ all|changed) export SCAN_MODE="$SKILL_EVAL_SCAN_MODE" ;;
+ *) echo "SKILL_EVAL_SCAN_MODE must be auto, all, or changed." >&2; exit 1 ;;
+ esac
+ if [ "$SCAN_MODE" = changed ]; then
+ if [ "${CI_PIPELINE_SOURCE:-}" != "merge_request_event" ] || [ "${CI_MERGE_REQUEST_EVENT_TYPE:-detached}" != detached ]; then
+ echo "Changed-skill selection requires a detached merge-request pipeline." >&2
+ exit 1
+ fi
+ export DIFF_BASE_SHA="${CI_MERGE_REQUEST_DIFF_BASE_SHA:-}"
+ export DIFF_HEAD_SHA="${CI_COMMIT_SHA:-}"
+ fi
+ # Changes to CI onboarding must exercise real skills on the setup MR. The
+ # inline check equals select_changed_skills.setup_changed, which Tiers 2
+ # and 3 use; it stays inline because the pinned image can predate it.
+ if [ "$SCAN_MODE" = changed ]; then
+ SCAN_MODE="$(python -I - <<'PYTHON'
+ import os, re, sys
+ from pathlib import Path
+ sys.path.insert(0, "/opt/skillevaluator/ci")
+ from select_changed_skills import _git
+ base, head = os.environ["DIFF_BASE_SHA"], os.environ["DIFF_HEAD_SHA"]
+ if any(not re.fullmatch(r"[0-9a-f]{40}", value) for value in (base, head)):
+ raise SystemExit("Changed mode requires exact base and head commits")
+ changed = _git(Path(os.environ["CI_PROJECT_DIR"]).resolve(), "diff", "--name-only", "-z", "--no-renames", base, head, "--").split(b"\0")
+ setup = any(path.startswith((b".github/", b".gitlab/", b".skillevaluator/ci")) or path == b".gitlab-ci.yml" for path in changed)
+ print("all" if setup else "changed")
+ PYTHON
+ )"
+ export SCAN_MODE
+ fi
+ set +e
+ python /opt/skillevaluator/ci/run_tier1.py --workspace "$CI_PROJECT_DIR" --reports "$reports_dir"
+ result=$?
+ set -e
+ mkdir "$artifact_dir"
+ cp -R "$reports_dir/." "$artifact_dir/"
+ exit "$result"
+ artifacts:
+ when: always
+ paths:
+ - skill-evaluator-report/
+ expire_in: 14 days
+ rules:
+ - if: '$SKILL_EVAL_FEEDBACK == "true"'
+ when: never
+ - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
+ - if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
+ - if: '$CI_PIPELINE_SOURCE == "web"'
+
+# Feedback pipelines run on the protected default branch. Root jobs outside this
+# include must not run there: start their rules with this guard, or extend this
+# job when they have no rules, only or except of their own.
+.skill-evaluation-not-feedback:
+ rules:
+ - if: '$SKILL_EVAL_FEEDBACK == "true"'
+ when: never
+ - when: on_success
+
+.skill-evaluation-tools:
+ image: python:3.12.12-slim
+ before_script:
+ - |
+ if ! command -v git >/dev/null 2>&1; then
+ if [ "$(id -u)" != 0 ] || ! command -v apt-get >/dev/null 2>&1; then
+ echo 'Install git on this native runner before retrying.' >&2; exit 1
+ fi
+ apt-get update -qq && apt-get install -y --no-install-recommends git ca-certificates
+ fi
+ - |
+ set -eu
+ case "$SKILL_EVAL_TOOLS_REF" in
+ *[!a-f0-9]*|'') echo 'SKILL_EVAL_TOOLS_REF must be an immutable commit' >&2; exit 1 ;;
+ esac
+ test "${#SKILL_EVAL_TOOLS_REF}" -eq 40
+ case "$SKILL_EVAL_TOOLS_REPOSITORY" in
+ *[!a-zA-Z0-9_./-]*|/*|*..*) exit 1 ;;
+ esac
+ tools_dir="$(mktemp -d /tmp/skillevaluator-tools.XXXXXX)"
+ export SKILL_EVAL_TOOLS_DIR="$tools_dir"
+ git -C "$tools_dir" init -q
+ git -C "$tools_dir" remote add origin "https://github.com/$SKILL_EVAL_TOOLS_REPOSITORY.git"
+ git -C "$tools_dir" fetch -q --depth 1 origin "$SKILL_EVAL_TOOLS_REF"
+ git -C "$tools_dir" checkout -q --detach FETCH_HEAD
+ export REPORT_COMMIT="$CI_COMMIT_SHA"
+ export REPORT_REPOSITORY="$CI_PROJECT_PATH"
+ export REPORT_RUN_URL="$CI_PIPELINE_URL"
+ export DIFF_BASE_SHA="${CI_MERGE_REQUEST_DIFF_BASE_SHA:-}"
+ export DIFF_HEAD_SHA="$CI_COMMIT_SHA"
+ export SKILLEVALUATOR_RUNTIME_DIR="$(mktemp -d /tmp/skillevaluator-runtimes.XXXXXX)"
+
+skill-evaluation-native:
+ # Both native tiers are advisory; the aggregate gates only on Tier 1.
+ # Execution failures must retain evidence.
+ allow_failure: true
+ extends: .skill-evaluation-tools
+ stage: test
+ timeout: 5 hours
+ tags: [$SKILL_EVAL_RUNNER]
+ # Environment-scoped secrets and protection still apply. `prepare` records no
+ # deployment, so "Prevent outdated deployment jobs" never drops an older MR.
+ environment:
+ name: $SKILL_EVAL_ENVIRONMENT
+ action: prepare
+ parallel:
+ matrix:
+ - SKILL_EVAL_TIER: ['2', '3']
+ # Docker mode requires a privileged runner supporting Docker-in-Docker and
+ # sharing /certs/client (runner volumes = ["/certs/client"]). TLS client
+ # certificates stay in the job and service; agent containers cannot use the
+ # daemon. For local mode select a native runner and remove this service.
+ services:
+ - name: docker:28.5.1-dind
+ alias: docker
+ variables:
+ DOCKER_HOST: tcp://docker:2376
+ DOCKER_TLS_CERTDIR: /certs
+ DOCKER_TLS_VERIFY: '1'
+ DOCKER_CERT_PATH: /certs/client
+ script:
+ - |
+ set -eu
+ case ",$SKILL_EVAL_TIERS," in
+ *",$SKILL_EVAL_TIER,"*) ;;
+ *) echo "Tier $SKILL_EVAL_TIER is not selected"; exit 0 ;;
+ esac
+ python -I "$SKILL_EVAL_TOOLS_DIR/ci/eligible_gitlab.py"
+ unset SKILLEVALUATOR_GITLAB_READ_TOKEN
+ if [ "$SKILL_EVAL_TIER" = 3 ]; then
+ if [ "$SKILL_EVAL_ENV_MODE" = docker ] && { ! command -v docker >/dev/null 2>&1 || ! docker compose version >/dev/null 2>&1 || ! docker buildx version >/dev/null 2>&1; }; then
+ if [ "$(id -u)" != 0 ] || ! command -v apt-get >/dev/null 2>&1; then
+ echo 'Install the Docker CLI, Compose v2 and Buildx on this runner before retrying.' >&2; exit 1
+ fi
+ apt-get update -qq && apt-get install -y --no-install-recommends docker-cli docker-compose docker-buildx
+ elif [ "$SKILL_EVAL_ENV_MODE" = local ] && ! command -v npm >/dev/null 2>&1; then
+ if [ "$(id -u)" != 0 ] || ! command -v apt-get >/dev/null 2>&1; then
+ echo 'Install Node/npm on this native local runner before retrying.' >&2; exit 1
+ fi
+ apt-get update -qq && apt-get install -y --no-install-recommends nodejs npm
+ fi
+ fi
+ 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 "$SKILL_EVAL_TOOLS_DIR/.uv-cache" sync --locked --no-dev --extra "tier$SKILL_EVAL_TIER" --project "$SKILL_EVAL_TOOLS_DIR" --python 3.12 --default-index https://pypi.org/simple
+ export PATH="$SKILL_EVAL_TOOLS_DIR/.venv/bin:$PATH"
+ if [ "$SKILL_EVAL_TIER" = 3 ]; then
+ python -I "$SKILL_EVAL_TOOLS_DIR/ci/bootstrap_tiers.py" || true
+ fi
+ reports_dir="$(mktemp -d /tmp/skillevaluator-reports.XXXXXX)"
+ trap 'rm -rf "$reports_dir"' EXIT
+ set +e
+ python -I "$SKILL_EVAL_TOOLS_DIR/ci/run_tiers.py" evaluate --tier "$SKILL_EVAL_TIER" --workspace "$CI_PROJECT_DIR" --reports "$reports_dir"
+ result=$?
+ set -e
+ artifact_dir="$CI_PROJECT_DIR/skill-evaluator-native"
+ if [ -e "$artifact_dir" ] || [ -L "$artifact_dir" ]; then
+ echo 'Use a clean checkout: skill-evaluator-native already exists.' >&2
+ exit 1
+ fi
+ mkdir "$artifact_dir"
+ cp -R "$reports_dir/." "$artifact_dir/"
+ exit "$result"
+ artifacts:
+ when: always
+ paths: [skill-evaluator-native/]
+ expire_in: 14 days
+ rules:
+ - if: '$SKILL_EVAL_FEEDBACK == "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"'
+ - if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
+ - if: '$CI_PIPELINE_SOURCE == "web" && $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
+
+skill-evaluation-aggregate:
+ extends: .skill-evaluation-tools
+ stage: test
+ when: always
+ needs:
+ - job: skill-evaluation
+ artifacts: true
+ optional: true
+ - job: skill-evaluation-native
+ artifacts: true
+ optional: true
+ script:
+ - |
+ set -eu
+ 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 "$SKILL_EVAL_TOOLS_DIR/.uv-cache" sync --locked --no-dev --project "$SKILL_EVAL_TOOLS_DIR" --python 3.12 --default-index https://pypi.org/simple
+ export PATH="$SKILL_EVAL_TOOLS_DIR/.venv/bin:$PATH"
+ mkdir -p skill-evaluator-results/tier1
+ if [ -d skill-evaluator-report ]; then
+ cp -R skill-evaluator-report/. skill-evaluator-results/tier1/
+ fi
+ if [ -d skill-evaluator-native ]; then
+ cp -R skill-evaluator-native/. skill-evaluator-results/
+ fi
+ python -I "$SKILL_EVAL_TOOLS_DIR/ci/run_tiers.py" aggregate --reports "$CI_PROJECT_DIR/skill-evaluator-results" --tiers "$SKILL_EVAL_TIERS"
+ artifacts:
+ when: always
+ name: skill-evaluator-results-$CI_PIPELINE_ID-$CI_JOB_ID
+ paths: [skill-evaluator-results/]
+ expire_in: 14 days
+ rules:
+ - if: '$SKILL_EVAL_FEEDBACK == "true"'
+ when: never
+ - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
+ - if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
+ - if: '$CI_PIPELINE_SOURCE == "web"'
+
+skill-evaluation-request-feedback:
+ allow_failure: true
+ extends: .skill-evaluation-tools
+ stage: test
+ needs:
+ - job: skill-evaluation-aggregate
+ artifacts: false
+ when: always
+ variables:
+ GIT_STRATEGY: none
+ # The job-token API records the real source job/pipeline relationship and
+ # supports the same project's protected default branch. No provider work runs.
+ script:
+ - python -I "$SKILL_EVAL_TOOLS_DIR/ci/request_gitlab_feedback.py"
+ rules:
+ - if: '$CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_SOURCE_PROJECT_ID == $CI_PROJECT_ID'
diff --git a/ci/gitlab/feedback.yml b/ci/gitlab/feedback.yml
new file mode 100644
index 00000000..5deeb112
--- /dev/null
+++ b/ci/gitlab/feedback.yml
@@ -0,0 +1,68 @@
+spec:
+ inputs:
+ tools-ref:
+ type: string
+ regex: "^[0-9a-f]{40}$"
+ tools-repository:
+ type: string
+ default: NVIDIA/SkillEvaluator
+ regex: "^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$"
+ api-url:
+ type: string
+ regex: "^https://[A-Za-z0-9.-]+(:[0-9]+)?(/[A-Za-z0-9._~-]+)*/api/v4$"
+ project-id:
+ type: string
+ regex: "^[A-Za-z0-9_.-]+(/[A-Za-z0-9_.-]+)*$"
+---
+# SPDX-License-Identifier: Apache-2.0
+# Install the thin include on the protected default branch before opening MRs.
+skill-evaluation-feedback:
+ # Serializes comment updates; each job checks its own MR and current commit.
+ resource_group: skillevaluator-feedback
+ image: python:3.12.12-slim
+ stage: test
+ # The protected environment scopes the publisher token and restricts who can
+ # run this job. `prepare` records no deployment, so "Prevent outdated
+ # deployment jobs" never drops an older MR's feedback.
+ environment:
+ name: skillevaluator-feedback
+ action: prepare
+ id_tokens:
+ SKILL_EVAL_GITLAB_ID_TOKEN:
+ aud: urn:skillevaluator:feedback:v1
+ variables:
+ GIT_STRATEGY: none
+ script:
+ - |
+ set -eu
+ export PATH=/usr/local/bin:/usr/bin:/bin
+ unset GIT_CONFIG_COUNT GIT_CONFIG_PARAMETERS GIT_CONFIG_GLOBAL GIT_CONFIG_SYSTEM GIT_EXEC_PATH GIT_TEMPLATE_DIR
+ unset GIT_DIR GIT_WORK_TREE GIT_COMMON_DIR GIT_INDEX_FILE GIT_OBJECT_DIRECTORY GIT_ALTERNATE_OBJECT_DIRECTORIES
+ unset LD_PRELOAD LD_LIBRARY_PATH DYLD_INSERT_LIBRARIES DYLD_LIBRARY_PATH PYTHONPATH PYTHONHOME
+ test "$CI_COMMIT_REF_PROTECTED" = true
+ test -n "$SKILLEVALUATOR_GITLAB_TOKEN"
+ # Include inputs are fixed in the protected default-branch configuration;
+ # source-pipeline variables cannot replace the privileged bootstrap.
+ tools_ref='$[[ inputs.tools-ref ]]'
+ tools_repository='$[[ inputs.tools-repository ]]'
+ env -i PATH="$PATH" apt-get update -qq
+ env -i PATH="$PATH" apt-get install -y --no-install-recommends git ca-certificates
+ tools_dir="$(mktemp -d /tmp/skillevaluator-feedback.XXXXXX)"
+ env -i PATH="$PATH" GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_SYSTEM=/dev/null git -C "$tools_dir" init -q
+ env -i PATH="$PATH" GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_SYSTEM=/dev/null git -C "$tools_dir" remote add origin "https://github.com/$tools_repository.git"
+ env -i PATH="$PATH" GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_SYSTEM=/dev/null git -C "$tools_dir" fetch -q --depth 1 origin "$tools_ref"
+ env -i PATH="$PATH" GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_SYSTEM=/dev/null git -C "$tools_dir" checkout -q --detach FETCH_HEAD
+ env -i PATH="$PATH" 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 "$tools_dir/.uv-cache" sync --locked --no-dev --extra publisher --project "$tools_dir" --python 3.12 --default-index https://pypi.org/simple
+ "$tools_dir/.venv/bin/python" -I - "$tools_dir/ci/feedback.py" --platform gitlab --api-url '$[[ inputs.api-url ]]' --project-id '$[[ inputs.project-id ]]' --pipeline-id "$SKILL_EVAL_SOURCE_PIPELINE_ID" <<'PYTHON'
+ import os, runpy, sys
+ # Preserve credentials only in the process environment, never CLI arguments.
+ retained = {key: os.environ[key] for key in ('PATH', 'SKILLEVALUATOR_GITLAB_TOKEN', 'SKILL_EVAL_GITLAB_ID_TOKEN') if key in os.environ}
+ os.environ.clear()
+ os.environ.update(retained)
+ sys.argv = sys.argv[1:]
+ sys.path.insert(0, os.path.dirname(sys.argv[0]))
+ runpy.run_path(sys.argv[0], run_name='__main__')
+ PYTHON
+ rules:
+ - if: '$CI_PIPELINE_SOURCE == "pipeline" && $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH && $CI_COMMIT_REF_PROTECTED == "true" && $SKILL_EVAL_FEEDBACK == "true"'
diff --git a/ci/native_reports.py b/ci/native_reports.py
index 36f4b3c9..7ee402dd 100644
--- a/ci/native_reports.py
+++ b/ci/native_reports.py
@@ -81,10 +81,14 @@ def _trusted_inline_code() -> frozenset[str]:
def constrain_native_html(document: str) -> str:
"""Reject executable markup absent from the trusted Tier 1 template."""
+ return _constrain_native_html(document, _trusted_inline_code())
+
+
+def _constrain_native_html(document: str, trusted_code: frozenset[str]) -> str:
parser = _InlineCode()
parser.feed(document)
code = {*parser.scripts, *parser.handlers}
- if parser.external_script or not code <= _trusted_inline_code():
+ if parser.external_script or not code <= trusted_code:
raise ValueError("Unexpected executable markup in the native report")
hashes = sorted(
{"'sha256-" + base64.b64encode(hashlib.sha256(code.encode()).digest()).decode() + "'" for code in code}
@@ -109,6 +113,51 @@ def constrain_native_html(document: str) -> str:
)
+def render_native_retained_report(
+ payload: dict,
+ *,
+ skill_name: str,
+ expected_skill_name: str | None = None,
+ context: dict | None = None,
+ scan_root: str | None = None,
+) -> str:
+ """Render every tier from typed JSON, then constrain trusted generated code.
+
+ Tier 3 templates contain JSON-escaped data in dynamic scripts and handlers.
+ Their CSP hashes must be calculated from a fresh trusted template render,
+ never from artifact-supplied markup. This entrypoint accepts JSON only. The
+ public ``constrain_native_html`` remains strict for legacy supplied HTML.
+ Remote chart code is omitted; native score tables and local UI remain usable
+ offline, and no external network access is authorized by the CSP.
+ """
+ context = dict(context or {})
+ canonical = context.pop("canonical_json_url", None)
+ index = context.pop("report_index_url", None)
+ if canonical is not None:
+ if canonical not in {f"skillevaluator-tier{tier}.json" for tier in (1, 2, 3)}:
+ raise ValueError("Invalid canonical native report filename")
+ context["canonical_json_url"] = "skillevaluator-tier1.json"
+ if index is not None:
+ if index not in {"../index.html", "../../index.html"}:
+ raise ValueError("Invalid native report index path")
+ context["report_index_url"] = "../index.html"
+ document = render_retained_report(
+ payload,
+ skill_name=skill_name,
+ expected_skill_name=expected_skill_name,
+ context=context,
+ scan_root=scan_root,
+ )
+ if canonical is not None:
+ document = document.replace('href="skillevaluator-tier1.json"', f'href="{canonical}"')
+ if index is not None:
+ document = document.replace('href="../index.html"', f'href="{index}"')
+ document = re.sub(r"<script\b[^>]*\bsrc=[^>]*>\s*</script\s*>", "", document, flags=re.IGNORECASE)
+ generated = _InlineCode()
+ generated.feed(document)
+ return _constrain_native_html(document, frozenset([*generated.scripts, *generated.handlers]))
+
+
_STYLE = """
:root{--brand-core:#76b900;--brand-green:#3e6500;--bg:#fff;--page:#f5f6f7;--tx:#24292f;--muted:#59636e;--line:#dfe3e6;--line-soft:#eaecef;--th:#fafbfc;--link:#3e6500;--focus:#3d6b00;
--pass-bg:#edf5e4;--pass-tx:#315b25;--fail-bg:#fff0ef;--fail-tx:#a3232b;--warn-bg:#fff5df;--warn-tx:#7a4e00;--rail:#1e2328;--rail-tx:#bfc6ce;--rail-link:#34402d;--rail-link-tx:#e6f2d4;
diff --git a/ci/publish_reports.py b/ci/publish_reports.py
index 1fbe1aa3..22724516 100644
--- a/ci/publish_reports.py
+++ b/ci/publish_reports.py
@@ -252,7 +252,7 @@ def validate_report(report: dict, row: dict) -> None:
from skillevaluator.reporting.run_status import resolve_run_status
try:
- retained = retained_results(report, copy_metadata=False)
+ retained = retained_results(report, copy_metadata=False, allowed_tiers={1})
except RetainedReportError as exc:
raise PublicationError("A per-skill report contains invalid retained evidence.") from exc
incomplete = []
diff --git a/ci/request_gitlab_feedback.py b/ci/request_gitlab_feedback.py
new file mode 100644
index 00000000..2430db56
--- /dev/null
+++ b/ci/request_gitlab_feedback.py
@@ -0,0 +1,155 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: Apache-2.0
+# ruff: noqa: T201 — command-line helper diagnostics
+"""Request protected-default-branch feedback with the running job's token."""
+
+from __future__ import annotations
+
+import http.client
+import json
+import os
+import re
+import urllib.error
+import urllib.parse
+import urllib.request
+from collections.abc import Mapping
+
+MAX_RESPONSE_BYTES = 1024 * 1024
+MAX_ID = 2**63 - 1
+SKIPPED = "Automatic MR feedback is skipped for this pipeline; the aggregate still gates Tier 1."
+# GitLab refuses a trigger the job's user or token may not make with 400-404.
+REFUSED_STATUSES = frozenset({400, 401, 403, 404})
+REFUSED = (
+ "GitLab refused the request: the pipeline user needs permission to run pipelines on the protected "
+ "default branch and to pass pipeline variables."
+)
+NO_JOBS = "HTTP 400 can also mean the default-branch configuration added no jobs to the pipeline."
+SERVER_ERROR = "GitLab did not create the feedback pipeline; retry this job, and check the GitLab API if it persists."
+TRANSPORT_ERROR = "GitLab could not be reached; check the runner's access to the GitLab API, then retry this job."
+INVALID_CONTEXT = (
+ "This job needs a same-project merge request pipeline with GitLab's predefined CI variables and an HTTPS API URL."
+)
+INVALID_RESPONSE = "GitLab's response did not confirm a default-branch pipeline in this project."
+
+
+class _NoRedirect(urllib.request.HTTPRedirectHandler):
+ def redirect_request(self, *_args, **_kwargs):
+ return None
+
+
+def _identifier(value: str) -> int:
+ if not re.fullmatch(r"[1-9][0-9]{0,18}", value) or int(value) > MAX_ID:
+ raise ValueError("Invalid identifier")
+ return int(value)
+
+
+def _https_url(value: str):
+ if not value or any(ord(character) <= 32 or ord(character) == 127 for character in value):
+ raise ValueError("Invalid API origin")
+ parsed = urllib.parse.urlsplit(value)
+ if (
+ parsed.scheme != "https"
+ or not parsed.hostname
+ or parsed.username
+ or parsed.password
+ or parsed.query
+ or parsed.fragment
+ or "\\" in value
+ ):
+ raise ValueError("Invalid API origin")
+ _ = parsed.port
+ return parsed
+
+
+def _configuration(env: Mapping[str, str]) -> tuple[str, int, str, str, str]:
+ project = _identifier(env.get("CI_PROJECT_ID", ""))
+ source = env.get("CI_PIPELINE_ID", "")
+ _identifier(source)
+ if env.get("CI_PIPELINE_SOURCE") != "merge_request_event" or env.get("CI_MERGE_REQUEST_SOURCE_PROJECT_ID") != str(
+ project
+ ):
+ raise ValueError("Not a same-project MR")
+ api = _https_url(env.get("CI_API_V4_URL", ""))
+ server = _https_url(env.get("CI_SERVER_URL", ""))
+ if api.netloc != server.netloc or api.path.rstrip("/") != server.path.rstrip("/") + "/api/v4":
+ raise ValueError("API origin does not match GitLab")
+ ref = env.get("CI_DEFAULT_BRANCH", "")
+ if (
+ not ref
+ or len(ref) > 1024
+ or ref == "@"
+ or ref.startswith("-")
+ or ref.endswith(".")
+ or ".." in ref
+ or "@{" in ref
+ or re.search(r"[~^:?*\[\\\x00-\x20\x7f]", ref)
+ or any(not part or part.startswith(".") or part.endswith(".lock") for part in ref.split("/"))
+ ):
+ raise ValueError("Invalid default branch")
+ token = env.get("CI_JOB_TOKEN", "")
+ if not token or len(token) > 8192 or any(ord(character) <= 32 or ord(character) == 127 for character in token):
+ raise ValueError("Invalid job token")
+ endpoint = urllib.parse.urlunsplit((api.scheme, api.netloc, api.path.rstrip("/"), "", ""))
+ return endpoint, project, source, ref, token
+
+
+def _skipped(reason: str, hint: str) -> int:
+ print(f"Feedback pipeline could not be requested ({reason}).")
+ print(SKIPPED)
+ print(hint)
+ # The request job is allow_failure: a failure warns without blocking the MR.
+ return 2
+
+
+def main() -> int:
+ try:
+ base, project, source, ref, token = _configuration(os.environ)
+ payload = urllib.parse.urlencode(
+ {
+ "token": token,
+ "ref": ref,
+ "variables[SKILL_EVAL_FEEDBACK]": "true",
+ "variables[SKILL_EVAL_SOURCE_PIPELINE_ID]": source,
+ }
+ ).encode()
+ request = urllib.request.Request(
+ f"{base}/projects/{project}/trigger/pipeline",
+ data=payload,
+ method="POST",
+ headers={"Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json"},
+ )
+ except ValueError as error:
+ return _skipped(type(error).__name__, INVALID_CONTEXT)
+ try:
+ # No inherited proxy can redirect this credential-bearing request.
+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), _NoRedirect())
+ with opener.open(request, timeout=30) as response:
+ body = response.read(MAX_RESPONSE_BYTES + 1)
+ except urllib.error.HTTPError as error:
+ if error.code not in REFUSED_STATUSES:
+ return _skipped(f"HTTP {error.code}", SERVER_ERROR)
+ return _skipped(f"HTTP {error.code}", REFUSED + (" " + NO_JOBS if error.code == 400 else ""))
+ except (OSError, ValueError, http.client.HTTPException) as error:
+ return _skipped(type(error).__name__, TRANSPORT_ERROR)
+ try:
+ if len(body) > MAX_RESPONSE_BYTES:
+ raise ValueError("Oversized response")
+ result = json.loads(body)
+ if (
+ not isinstance(result, dict)
+ or type(result.get("id")) is not int
+ or not 0 < result["id"] <= MAX_ID
+ or type(result.get("project_id")) is not int
+ or result["project_id"] != project
+ or result.get("ref") != ref
+ or result.get("source") != "pipeline"
+ ):
+ raise ValueError("Invalid feedback pipeline")
+ except ValueError as error:
+ return _skipped(type(error).__name__, INVALID_RESPONSE)
+ print(f"Feedback pipeline requested (pipeline {result['id']}).")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/ci/run_tiers.py b/ci/run_tiers.py
new file mode 100644
index 00000000..d8384a2d
--- /dev/null
+++ b/ci/run_tiers.py
@@ -0,0 +1,847 @@
+# SPDX-License-Identifier: Apache-2.0
+# ruff: noqa: INP001, T201 -- trusted reusable CI entrypoint.
+"""Evaluate one CI tier, then aggregate retained evidence without running source code.
+
+The local onboarding wizard never calls this module. Reusable CI workflows do;
+all outputs live outside the consumer checkout and provider subprocesses never
+inherit repository or feedback credentials.
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import importlib.metadata
+import json
+import os
+import platform
+import re
+import signal
+import subprocess
+import sys
+import tempfile
+import time
+from contextlib import suppress
+from pathlib import Path
+
+# Isolated Python deliberately omits the script directory. These siblings are
+# from the pinned tools checkout; the consumer working directory is never added.
+if not __package__:
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
+
+from skillevaluator.reporting.run_status import resolve_run_status
+from skillevaluator.utils.secret_redaction import Redactor
+
+try:
+ from diagnostics import TierBudget, retain_diagnostics
+ from github_api import strict_json
+ from run_tier1 import discover_skills
+ from secret_redaction import collect_sensitive_values
+ from select_changed_skills import (
+ SelectionError,
+ _git,
+ _paths,
+ select_changed_skills,
+ setup_changed,
+ skill_roots,
+ )
+except ModuleNotFoundError:
+ from ci.diagnostics import TierBudget, retain_diagnostics
+ from ci.github_api import strict_json
+ from ci.run_tier1 import discover_skills
+ from ci.secret_redaction import collect_sensitive_values
+ from ci.select_changed_skills import (
+ SelectionError,
+ _git,
+ _paths,
+ select_changed_skills,
+ setup_changed,
+ skill_roots,
+ )
+
+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"}
+ATTEMPT = re.compile(r"[1-9][0-9]{0,7}")
+TIER_ARTIFACT = re.compile(r"skill-evaluator-tier([123])-attempt-([1-9][0-9]{0,7})")
+
+
+class ConfigurationError(ValueError):
+ """A fixed diagnostic that contains no credential or untrusted command output."""
+
+
+def integer(env: dict, key: str, default: int, minimum: int, maximum: int) -> int:
+ value = str(env.get(key, default))
+ if not re.fullmatch(r"[0-9]{1,8}", value) or not minimum <= int(value) <= maximum:
+ raise ConfigurationError(f"{key} must be between {minimum} and {maximum}.")
+ return int(value)
+
+
+def boolean(env: dict, key: str, default: bool = False) -> bool:
+ value = str(env.get(key, str(default))).lower()
+ if value not in {"true", "false"}:
+ raise ConfigurationError(f"{key} must be true or false.")
+ 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 select_skills(workspace: Path, env: dict) -> tuple[list[Path], dict]:
+ roots = env.get("SKILL_EVAL_PATHS", "skills")
+ mode = env.get("SKILL_EVAL_SCAN_MODE", "auto")
+ if mode not in {"auto", "all"}:
+ raise ConfigurationError("SKILL_EVAL_SCAN_MODE must be auto or all.")
+ base, head = env.get("DIFF_BASE_SHA", ""), env.get("REPORT_COMMIT") or env.get("DIFF_HEAD_SHA", "")
+ actual = _git(workspace, "rev-parse", "HEAD").decode().strip()
+ if not SHA.fullmatch(head) or actual != head:
+ raise ConfigurationError("The evaluated commit must match the checkout HEAD.")
+ if base and mode == "auto":
+ selected, selection = select_changed_skills(workspace, roots, base, head)
+ # Tier 1 applies the same setup predicate, so every tier selects the same skills.
+ changed = _paths(_git(workspace, "diff", "--name-only", "-z", "--no-renames", f"{base}...{head}", "--"))
+ if not setup_changed(changed):
+ return selected, selection
+ reason = "ci_configuration_changed"
+ else:
+ selection, reason = {}, "full_scan"
+ configured = skill_roots(workspace, roots)
+ if _git(
+ workspace, "status", "--porcelain=v1", "-z", "--untracked-files=all", "--ignored=matching", "--", *configured
+ ):
+ raise ConfigurationError("Configured skill trees must match the evaluated commit.")
+ selected = discover_skills(workspace, roots)
+ return selected, {
+ **selection,
+ "reason": reason,
+ "selected": [p.relative_to(workspace).as_posix() for p in selected],
+ }
+
+
+def context(env: dict) -> dict:
+ mode = env.get("SKILL_EVAL_ENV_MODE", "docker")
+ if mode not in {"docker", "local"}:
+ raise ConfigurationError("Tier 3 onboarding supports docker or local.")
+ platform_name = "gitlab" if env.get("CI_PIPELINE_ID") else "github"
+ return {
+ "schema_version": 1,
+ "report_contract": "skillevaluator-ci-v1",
+ "commit": env.get("REPORT_COMMIT") or env.get("DIFF_HEAD_SHA", ""),
+ "base_commit": env.get("DIFF_BASE_SHA") or None,
+ "repository": env.get("REPORT_REPOSITORY")
+ or env.get("GITHUB_REPOSITORY")
+ or env.get("CI_PROJECT_PATH", "local/consumer"),
+ "platform": platform_name,
+ "run_id": env.get("CI_PIPELINE_ID") or env.get("GITHUB_RUN_ID", "1"),
+ "run_attempt": env.get("GITHUB_RUN_ATTEMPT", "1"),
+ "environment": mode,
+ "runtime": {
+ "os": platform.system(),
+ "architecture": platform.machine(),
+ "evaluator": importlib.metadata.version("skillevaluator"),
+ "tools_ref": env.get("SKILLEVALUATOR_TOOLS_REF", ""),
+ },
+ }
+
+
+def write_json(path: Path, payload: dict) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ if path.is_symlink():
+ raise ConfigurationError("Report outputs must be regular files.")
+ temporary = path.with_suffix(".tmp")
+ with temporary.open("x", encoding="utf-8") as stream:
+ stream.write(json.dumps(payload, indent=2, ensure_ascii=True, allow_nan=False) + "\n")
+ temporary.replace(path)
+
+
+def read_json(path: Path) -> dict:
+ if path.is_symlink() or not path.is_file() or path.stat().st_size > MAX_JSON_BYTES:
+ raise ConfigurationError("A required report is missing, linked or oversized.")
+ value = strict_json(path.read_bytes(), ConfigurationError, "Report JSON is invalid.")
+ if not isinstance(value, dict):
+ raise ConfigurationError("Report JSON must be an object.")
+ return value
+
+
+def run_command(args: list[str], *, env: dict, cwd: Path, timeout: float, log: Path) -> int:
+ """Bound subprocess lifetime and stop the entire process group on timeout."""
+ if timeout <= 0:
+ return 124
+ with log.open("wb") as stream:
+ process = subprocess.Popen(
+ args, cwd=cwd, env=env, stdout=stream, stderr=subprocess.STDOUT, start_new_session=True
+ )
+ try:
+ return process.wait(timeout=timeout)
+ except BaseException:
+ try:
+ os.killpg(process.pid, signal.SIGTERM)
+ process.wait(timeout=5)
+ except (ProcessLookupError, subprocess.TimeoutExpired):
+ with suppress(ProcessLookupError):
+ os.killpg(process.pid, signal.SIGKILL)
+ process.wait()
+ if sys.exc_info()[0] is subprocess.TimeoutExpired:
+ return 124
+ raise
+
+
+def skill_command(tier: int, skill: Path, output: Path, env: dict, *, catalog: Path | None = None) -> list[str]:
+ args = [sys.executable, "-I", "-m", "skillevaluator.cli"]
+ if tier == 1:
+ args += ["tier1", str(skill), "--no-llm", "--min-score", str(integer(env, "SKILL_EVAL_MIN_SCORE", 70, 0, 100))]
+ elif tier == 2:
+ args += ["tier2", str(skill)]
+ if catalog:
+ args += ["--catalog", str(catalog)]
+ else:
+ return [
+ sys.executable,
+ "-I",
+ str(Path(__file__).resolve()),
+ "native-tier3",
+ "--skill",
+ str(skill),
+ "--output",
+ str(output),
+ "--config",
+ str(output / "ci-options.json"),
+ "--env-mode",
+ env.get("SKILL_EVAL_ENV_MODE", "docker"),
+ ]
+ return [*args, "-r", "json", "-o", str(output)]
+
+
+def tier3_options(skill: Path, output: Path, env: dict):
+ """Use the native service directly: combined validate requires Tier 1."""
+ from skillevaluator.evaluation.options import EvaluationOptions
+
+ source = {
+ "repository": env.get("REPORT_REPOSITORY") or env.get("GITHUB_REPOSITORY") or env.get("CI_PROJECT_PATH"),
+ "commit": env.get("REPORT_COMMIT"),
+ }
+ revision = env.get("SKILLEVALUATOR_TOOLS_REF") or env.get("SKILL_EVAL_TOOLS_REF")
+ if revision and SHA.fullmatch(revision):
+ source["evaluator_container_revision"] = revision
+ return EvaluationOptions(
+ skill_path=skill,
+ env_mode=env.get("SKILL_EVAL_ENV_MODE", "docker"),
+ agents=env.get("SKILL_EVAL_AGENTS") or None,
+ # CI's shared chat/judge model is carried in the provider environment.
+ # Native resolution adds adapter namespaces and honors authored agent
+ # overrides; a global CLI override would bypass that resolution.
+ model=None,
+ skip_baseline=False,
+ skip_with_skill=False,
+ max_cases=None,
+ stop_on_pass=False,
+ n_attempts=integer(env, "SKILL_EVAL_N_ATTEMPTS", 1, 1, 100),
+ n_concurrent=integer(env, "SKILL_EVAL_N_CONCURRENT", 1, 1, 16),
+ max_agents=1,
+ results_dir=output / "harbor",
+ evaluated_source=source,
+ )
+
+
+def native_tier3(skill: Path, output: Path, env: dict) -> int:
+ """Run both native Harbor arms and emit their canonical typed JSON."""
+ from skillevaluator.evaluation.service import EvaluationService
+ from skillevaluator.evaluation.tier3_report import advisory_skip_result, agent_eval_result_from_run
+ from skillevaluator.reporting.json_reporter import JSONReporter
+
+ dataset_preflight(skill)
+ service = EvaluationService()
+ options = tier3_options(skill, output, env)
+ engine = service.evaluate(options)
+ result = agent_eval_result_from_run(
+ skill, results_dir=options.results_dir, env_mode=options.env_mode, engine_result=engine
+ )
+ 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)}
+ 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}
+ result.metadata["evaluated_source"] = options.evaluated_source
+ if service.failure_reason(engine):
+ result.mark_scan_incomplete("Tier 3 execution")
+ document = JSONReporter(expected_skill_name=skill.name).render_all([result])
+ (output / "skillevaluator-tier3.json").write_text(document, encoding="utf-8")
+ return int(resolve_run_status([result]).headline.value != "passed")
+
+
+def dataset_preflight(skill: Path) -> dict[str, str]:
+ from skillevaluator.tier3.evals_config import load_evals_config
+ from skillevaluator.tier3.evals_spec import validate_tier3_source
+
+ source, findings = validate_tier3_source(skill)
+ if source in {"invalid", "missing"} or any(f.status in {"error", "warning", "missing"} for f in findings):
+ raise ConfigurationError("A committed Tier 3 dataset/task source failed strict validation.")
+ configuration, _ = load_evals_config(skill)
+ if (configuration.get("harbor") or {}).get("max_cases") is not None:
+ raise ConfigurationError("CI requires the complete Tier 3 dataset; remove harbor.max_cases.")
+ authored = skill / "evals"
+ digests = {}
+ total = 0
+ for path in sorted(authored.rglob("*")):
+ if "results" in path.relative_to(authored).parts:
+ continue
+ if path.is_symlink():
+ raise ConfigurationError("Tier 3 authored inputs cannot contain symlinks.")
+ if path.is_file():
+ total += path.stat().st_size
+ if total > MAX_JSON_BYTES or len(digests) >= 10000:
+ raise ConfigurationError("Tier 3 authored inputs exceed CI limits.")
+ digests[path.relative_to(skill).as_posix()] = hashlib.sha256(path.read_bytes()).hexdigest()
+ return digests
+
+
+def _combined(statuses: list[str]) -> str:
+ return next(
+ (
+ status
+ for status in ("failed", "incomplete", "needs_action", "not_run", "neutral", "passed", "skipped")
+ if status in statuses
+ ),
+ "not_run",
+ )
+
+
+def _retain(raw: Path, destination: Path, tier: int, tokens: set[str], skill: Path, code: int) -> dict:
+ from skillevaluator.reporting.retained import retained_results
+
+ try:
+ from native_reports import render_native_retained_report
+ from tier_manifest import tier3_execution_complete
+ except ModuleNotFoundError:
+ from ci.native_reports import render_native_retained_report
+ from ci.tier_manifest import tier3_execution_complete
+ documents = sorted(raw.glob("skillevaluator*.json"))
+ if len(documents) != 1:
+ raise ConfigurationError("The evaluator did not produce one canonical JSON report.")
+ report = Redactor(tokens).object(read_json(documents[0]))
+ results = retained_results(report, allowed_tiers={tier})
+ if tier == 2:
+ # Standalone Tier 2 gates its CLI exit; CI keeps the same evidence and
+ # tier verdict while declaring that verdict advisory in every format.
+ for result, row in zip(results, report["results"], strict=True):
+ result.metadata["gating"] = {**result.metadata.get("gating", {}), "tier": 2, "blocking": False}
+ row["gating"] = result.metadata["gating"]
+ report["gating"] = {"tiers": {"2": {"blocking": False, "validators": [r.validator_name for r in results]}}}
+ run_status = resolve_run_status(results)
+ if tier == 2:
+ report.update(overall_passed=run_status.headline.value == "passed", overall_status=run_status.headline.value)
+ status = run_status.tiers[tier].status.value
+ # A confirmed failure outranks incomplete evidence in the status, so record
+ # completeness on its own: the caller keeps diagnostics for incomplete runs.
+ complete = tier3_execution_complete(report) if tier == 3 else not any(result.is_incomplete for result in results)
+ if status == "not_run" or (code and status == "passed"):
+ status = "incomplete"
+ if tier == 3:
+ if status == "passed" and not complete:
+ status = "incomplete"
+ elif status == "passed" and report.get("tier3", {}).get("verdict") == "neutral":
+ status = "neutral"
+ destination.mkdir(parents=True, exist_ok=True)
+ name = f"skillevaluator-tier{tier}"
+ write_json(destination / f"{name}.json", report)
+ (destination / f"{name}.html").write_text(
+ render_native_retained_report(
+ report,
+ skill_name=skill.name,
+ expected_skill_name=skill.name,
+ context={"report_index_url": "../../index.html", "canonical_json_url": f"{name}.json"},
+ ),
+ encoding="utf-8",
+ )
+ from skillevaluator.reporting.markdown import MarkdownReporter
+
+ (destination / f"{name}.md").write_text(MarkdownReporter().render_all(results), encoding="utf-8")
+ metrics = {"findings": sum(len(result.findings) for result in results)}
+ if tier == 3:
+ payload = report.get("tier3") or {}
+ summary = payload.get("summary") or payload
+ metrics.update(
+ {
+ "score": summary.get("overall_score"),
+ "skill_lift": summary.get("overall_lift"),
+ "coverage": f"{summary.get('scored_attempts', 0)}/{summary.get('expected_attempts', 0)}",
+ "execution_complete": complete,
+ }
+ )
+ return {"status": status, "metrics": metrics, "complete": complete}
+
+
+def _build_catalog(workspace: Path, selected: list[Path], path: Path) -> None:
+ from skillevaluator.embedding.client import EmbeddingClient
+ from skillevaluator.embedding.registry import EmbeddingRegistry
+
+ registry = EmbeddingRegistry(EmbeddingClient())
+ registry.build_from_paths(workspace, selected)
+ registry.save_catalog(path)
+
+
+def evaluate(tier: int, workspace: Path, reports: Path, env: dict[str, str]) -> int:
+ if tier not in {1, 2, 3}:
+ raise ConfigurationError("Select Tier 1, 2 or 3.")
+ workspace = workspace.resolve(strict=True)
+ reports = reports.resolve()
+ if reports.is_relative_to(workspace) or any(p.is_symlink() for p in [reports, *reports.parents]):
+ raise ConfigurationError("Reports must be outside the consumer checkout in an unlinked directory.")
+ document = context(env)
+ required = tier == 1
+ selected, selection = select_skills(workspace, env)
+ row = {
+ "tier": tier,
+ "required": required,
+ "status": "skipped" if not selected else "incomplete",
+ "skills": [
+ {
+ "path": skill.relative_to(workspace).as_posix(),
+ "status": "incomplete",
+ "report_json": None,
+ "report_html": None,
+ }
+ for skill in selected
+ ],
+ }
+ document.update({"tiers": [row], "expected_tiers": [tier], "selection": selection})
+ destination = reports / f"tier{tier}"
+ destination.mkdir(parents=True, exist_ok=True)
+ if (destination / "ci-tier.json").exists():
+ raise ConfigurationError("Use a fresh report directory for each run attempt.")
+
+ # Reserve honest initial evidence before external work starts.
+ def retain():
+ document["overall_passed"] = not required or row["status"] in SUCCESS
+ write_json(destination / "ci-tier.json", document)
+
+ retain()
+ if not selected:
+ row["reason"] = "No selected skills changed; evaluation did not run."
+ retain()
+ return 0
+ if env.get("SKILL_EVAL_DATASET_ROOT"):
+ 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"]])
+ 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()
+ return int(required)
+ deadline = time.monotonic() + integer(env, "SKILL_EVAL_TIMEOUT_SECONDS", 18000, 1, 86400)
+ budget = TierBudget()
+ with tempfile.TemporaryDirectory(prefix="skillevaluator-ci-") as temporary:
+ scratch = Path(temporary).resolve()
+ child["HOME"] = str(scratch / "home")
+ Path(child["HOME"]).mkdir(mode=0o700)
+ child["TMPDIR"] = str(scratch)
+ child["SKILLEVALUATOR_OUTPUT_PROVENANCE_KEY_FILE"] = str(scratch / "output-provenance.key")
+ catalog = None
+ if tier == 2:
+ roots = env.get("SKILL_EVAL_PATHS", "skills")
+ all_skills = discover_skills(workspace, roots)
+ if len(all_skills) > 1:
+ catalog = scratch / "catalog.json"
+ # A helper subprocess preserves the same timeout and secret boundary as checks.
+ request = scratch / "catalog-input.json"
+ write_json(request, {"workspace": str(workspace), "skills": [str(p) for p in all_skills]})
+ args = [
+ sys.executable,
+ "-I",
+ str(Path(__file__).resolve()),
+ "catalog",
+ "--input",
+ str(request),
+ "--output",
+ str(catalog),
+ ]
+ if run_command(
+ args, env=child, cwd=workspace, timeout=deadline - time.monotonic(), log=scratch / "catalog.log"
+ ):
+ row["reason"] = (
+ "The complete comparison catalog could not be built; inspect provider and embedding configuration."
+ )
+ diagnostics = scratch / "catalog-diagnostics"
+ diagnostics.mkdir()
+ retain_diagnostics(
+ diagnostics,
+ destination / "catalog",
+ provider_tokens,
+ command_log=scratch / "catalog.log",
+ budget=budget,
+ )
+ retain()
+ return int(required)
+ doctor_done = False
+ for index, skill in enumerate(selected, 1):
+ skill_row = row["skills"][index - 1]
+ raw = scratch / f"skill-{index:03}"
+ raw.mkdir()
+ leaf = destination / f"skill-{index:03}"
+ tokens = provider_tokens
+ command_log = scratch / f"skill-{index:03}.log"
+ code = None
+ complete = True
+ try:
+ digests = dataset_preflight(skill) if tier == 3 else {}
+ tokens = collect_sensitive_values(skill) | provider_tokens
+ if tier == 3 and not doctor_done:
+ args = [
+ sys.executable,
+ "-I",
+ "-m",
+ "skillevaluator.cli",
+ "doctor",
+ "--tier",
+ "3",
+ "--env-mode",
+ document["environment"],
+ ]
+ if env.get("SKILL_EVAL_AGENTS"):
+ args += ["--agents", env["SKILL_EVAL_AGENTS"]]
+ command_log = scratch / "doctor.log"
+ if run_command(
+ args,
+ env=child,
+ cwd=workspace,
+ timeout=min(180, deadline - time.monotonic()),
+ log=command_log,
+ ):
+ raise ConfigurationError(
+ "Tier 3 runtime preflight failed; check the selected mode, agent and provider."
+ )
+ doctor_done = True
+ if tier == 3:
+ config_keys = (
+ "SKILL_EVAL_ENV_MODE",
+ "SKILL_EVAL_AGENTS",
+ "SKILL_EVAL_MODEL",
+ "SKILL_EVAL_N_ATTEMPTS",
+ "SKILL_EVAL_N_CONCURRENT",
+ "REPORT_REPOSITORY",
+ "REPORT_COMMIT",
+ "GITHUB_REPOSITORY",
+ "CI_PROJECT_PATH",
+ "SKILLEVALUATOR_TOOLS_REF",
+ "SKILL_EVAL_TOOLS_REF",
+ )
+ write_json(raw / "ci-options.json", {key: env[key] for key in config_keys if key in env})
+ command_log = scratch / f"skill-{index:03}.log"
+ code = run_command(
+ skill_command(tier, skill, raw, env, catalog=catalog),
+ env=child,
+ cwd=workspace,
+ timeout=deadline - time.monotonic(),
+ log=command_log,
+ )
+ if code == 124:
+ skill_row["error"] = "Evaluation exceeded the configured time budget."
+ retained = _retain(raw, leaf, tier, tokens, skill, code)
+ complete = retained.pop("complete")
+ skill_row.update(retained)
+ if tier == 3 and dataset_preflight(skill) != digests:
+ skill_row.update(status="incomplete", error="Authored evaluation inputs changed during execution.")
+ skill_row["dataset_digests"] = digests
+ skill_row["report_json"] = (leaf / f"skillevaluator-tier{tier}.json").relative_to(reports).as_posix()
+ skill_row["report_html"] = (leaf / f"skillevaluator-tier{tier}.html").relative_to(reports).as_posix()
+ except (OSError, ValueError, ImportError) as exc:
+ # A failure after _retain must not leave a clean status beside an execution error.
+ skill_row["status"] = "incomplete"
+ # SDK and provider exception messages can carry credentials. Only fixed local diagnostics are safe.
+ # An earlier specific diagnostic, such as the time budget, explains the missing report better.
+ skill_row["error"] = skill_row.get("error") or (
+ str(exc)
+ if isinstance(exc, ConfigurationError)
+ else "Evaluation evidence could not be safely retained; check the runtime and provider."
+ )
+ finally:
+ # Incomplete execution keeps diagnostics even behind a failed verdict. Exit
+ # codes other than pass (0) and fail (1) mean the worker itself went wrong.
+ if skill_row["status"] in EXECUTION_FAILURES or not complete or code not in {None, 0, 1}:
+ try:
+ retain_diagnostics(
+ raw,
+ leaf,
+ tokens,
+ command_log=command_log if command_log.is_file() else None,
+ budget=budget,
+ )
+ except (OSError, ValueError):
+ # Diagnostic failures must never replace the evaluation
+ # outcome or expose raw worker exception messages.
+ skill_row["diagnostics_error"] = "Worker diagnostics could not be safely retained."
+ row["status"] = _combined([r["status"] for r in row["skills"]])
+ retain()
+ print(f"Tier {tier}: completed {index}/{len(selected)} selected skills; {skill_row['status']}.", flush=True)
+ row["status"] = _combined([r["status"] for r in row["skills"]])
+ retain()
+ return int(required and row["status"] not in SUCCESS)
+
+
+def select_attempts(artifacts: Path, reports: Path, current: int) -> dict[str, str]:
+ """Place each tier's newest artifact from this or an earlier attempt of the run.
+
+ GitHub's "Re-run failed jobs" reruns only failed jobs and their dependents.
+ Tier jobs that already completed keep artifacts named for their own attempt.
+ """
+ chosen: dict[int, tuple[int, Path]] = {}
+ if artifacts.is_dir():
+ for path in artifacts.iterdir():
+ match = TIER_ARTIFACT.fullmatch(path.name)
+ if not match or int(match[2]) > current:
+ continue
+ if path.is_symlink() or not path.is_dir():
+ raise ConfigurationError("Downloaded tier artifacts must be regular directories.")
+ tier, attempt = int(match[1]), int(match[2])
+ if attempt > chosen.get(tier, (0, path))[0]:
+ chosen[tier] = (attempt, path)
+ reports.mkdir(parents=True, exist_ok=True)
+ selected = {}
+ for tier, (attempt, path) in sorted(chosen.items()):
+ # Tier 1 uploads its report root; Tier 2/3 upload a root containing tierN/.
+ source = path if tier == 1 else path / f"tier{tier}"
+ target = reports / f"tier{tier}"
+ if source.is_symlink() or not source.is_dir():
+ continue
+ if target.exists() or target.is_symlink():
+ raise ConfigurationError("Use a fresh report directory for each aggregate.")
+ source.rename(target)
+ selected[str(tier)] = str(attempt)
+ print(f"Tier {tier}: using retained evidence from run attempt {attempt}.", flush=True)
+ write_json(reports / "source-attempts.json", selected)
+ return selected
+
+
+def _source_attempts(reports: Path, current: int) -> dict[int, str]:
+ path = reports / "source-attempts.json"
+ if not path.exists() and not path.is_symlink():
+ return {}
+ recorded = read_json(path)
+ if not all(
+ key in {"1", "2", "3"} and isinstance(value, str) and ATTEMPT.fullmatch(value) and int(value) <= current
+ for key, value in recorded.items()
+ ):
+ raise ConfigurationError("Recorded tier attempts are invalid.")
+ return {int(key): value for key, value in recorded.items()}
+
+
+def _keep_selected(row: dict, selected) -> None:
+ """Record which skills the tier selected, so a summary can tell 'not selected' from missing."""
+ row.pop("selected", None)
+ if isinstance(selected, list) and all(isinstance(path, str) for path in selected):
+ row["selected"] = selected
+
+
+def aggregate(reports: Path, tiers: tuple[int, ...], env: dict) -> int:
+ try:
+ from tier_manifest import validate_manifest, write_reports
+ except ModuleNotFoundError:
+ from ci.tier_manifest import validate_manifest, write_reports
+ result = context(env)
+ result["expected_tiers"] = list(tiers)
+ result["tiers"] = []
+ current = integer(env, "GITHUB_RUN_ATTEMPT", 1, 1, 99_999_999)
+ recorded = _source_attempts(reports, current)
+ for tier in tiers:
+ required = tier == 1
+ path = reports / f"tier{tier}" / "ci-tier.json"
+ if path.exists():
+ incoming = validate_manifest(read_json(path))
+ for field in ("commit", "base_commit", "repository", "platform", "run_id", "environment"):
+ if incoming.get(field) != result[field]:
+ raise ConfigurationError("Tier artifacts do not identify the same evaluation run.")
+ # Evidence from an earlier attempt of this run stays valid after "Re-run failed jobs".
+ attempt = incoming["run_attempt"]
+ if int(attempt) > current or recorded.get(tier, attempt) != attempt:
+ raise ConfigurationError("Tier artifacts do not identify the same evaluation run.")
+ rows = incoming.get("tiers")
+ if not isinstance(rows, list) or len(rows) != 1 or rows[0].get("tier") != tier:
+ raise ConfigurationError("A tier artifact does not identify its expected tier.")
+ row = {**rows[0], "required": required, "source_attempt": attempt}
+ selection = incoming.get("selection", {})
+ selected = selection.get("selected") if isinstance(selection, dict) else None
+ # A retained checkpoint must cover every selected skill before it can claim completion.
+ if (
+ row.get("status") in {"passed", "neutral", "skipped"}
+ and isinstance(selected, list)
+ and set(selected) != {skill.get("path") for skill in row.get("skills", [])}
+ ):
+ row.update(
+ status="incomplete", reason="Results are missing for selected skills; the tier did not complete."
+ )
+ _keep_selected(row, selected)
+ elif tier == 1 and (reports / "tier1/summary.json").is_file():
+ legacy = read_json(reports / "tier1/summary.json")
+ try:
+ from publish_reports import validate_report, validate_summary
+ except ModuleNotFoundError:
+ from ci.publish_reports import validate_report, validate_summary
+ validate_summary(legacy)
+ if (
+ legacy.get("overall_status") in {"passed", "skipped"}
+ and legacy.get("execution", {}).get("commit") != result["commit"]
+ ):
+ raise ConfigurationError("Legacy Tier 1 evidence identifies a different evaluated commit.")
+ status = legacy.get("overall_status", "incomplete")
+ row = {"tier": 1, "required": True, "status": "incomplete" if status == "error" else status, "skills": []}
+ if status == "skipped":
+ row["reason"] = "No selected skills changed; Tier 1 evaluation did not run."
+ elif legacy.get("error"):
+ row["reason"] = legacy["error"]
+ for skill in legacy.get("skills", []):
+ directory = skill.get("report_dir", "")
+ if not re.fullmatch(r"skill-[0-9]{3}", directory):
+ raise ConfigurationError("A legacy Tier 1 report directory is invalid.")
+ native = reports / "tier1" / directory
+ json_path, html_path = native / "skillevaluator-tier1.json", native / "skillevaluator-tier1.html"
+ skill_status = skill.get("overall_status", "incomplete")
+ if json_path.is_file() and not json_path.is_symlink() and skill_status != "error":
+ validate_report(read_json(json_path), skill)
+ elif skill_status == "passed":
+ skill_status = "incomplete"
+ row["skills"].append(
+ {
+ "path": skill["path"],
+ "status": "incomplete" if skill_status == "error" else skill_status,
+ "report_json": json_path.relative_to(reports).as_posix() if json_path.is_file() else None,
+ "report_html": html_path.relative_to(reports).as_posix() if html_path.is_file() else None,
+ }
+ )
+ if row["skills"]:
+ row["status"] = _combined([s["status"] for s in row["skills"]])
+ selection = legacy.get("selection")
+ _keep_selected(row, selection.get("selected") if isinstance(selection, dict) else None)
+ if tier in recorded:
+ row["source_attempt"] = recorded[tier]
+ else:
+ row = {
+ "tier": tier,
+ "required": required,
+ "status": "incomplete",
+ "skills": [],
+ "reason": "The tier did not produce retained evidence; inspect its failed or cancelled CI job.",
+ }
+ result["tiers"].append(row)
+ result["overall_passed"] = all(not r["required"] or r["status"] in SUCCESS for r in result["tiers"])
+ write_reports(reports, validate_manifest(result))
+ return int(not result["overall_passed"])
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ commands = parser.add_subparsers(dest="command", required=True)
+ evaluate_parser = commands.add_parser("evaluate")
+ evaluate_parser.add_argument("--tier", type=int, required=True)
+ evaluate_parser.add_argument("--workspace", type=Path, required=True)
+ evaluate_parser.add_argument("--reports", type=Path, required=True)
+ aggregate_parser = commands.add_parser("aggregate")
+ aggregate_parser.add_argument("--reports", type=Path, required=True)
+ aggregate_parser.add_argument("--tiers", default="1,2,3")
+ attempts_parser = commands.add_parser("select-attempts")
+ attempts_parser.add_argument("--artifacts", type=Path, required=True)
+ attempts_parser.add_argument("--reports", type=Path, required=True)
+ catalog_parser = commands.add_parser("catalog")
+ catalog_parser.add_argument("--input", type=Path, required=True)
+ catalog_parser.add_argument("--output", type=Path, required=True)
+ native_parser = commands.add_parser("native-tier3")
+ native_parser.add_argument("--skill", type=Path, required=True)
+ native_parser.add_argument("--output", type=Path, required=True)
+ native_parser.add_argument("--config", type=Path, required=True)
+ native_parser.add_argument("--env-mode", choices=["local", "docker"], required=True)
+ args = parser.parse_args(argv)
+ try:
+ if args.command == "evaluate":
+ return evaluate(args.tier, args.workspace, args.reports, dict(os.environ))
+ if args.command == "select-attempts":
+ current = integer(os.environ, "GITHUB_RUN_ATTEMPT", 1, 1, 99_999_999)
+ select_attempts(args.artifacts, args.reports, current)
+ return 0
+ if args.command == "catalog":
+ request = read_json(args.input)
+ _build_catalog(Path(request["workspace"]), [Path(p) for p in request["skills"]], args.output)
+ return 0
+ if args.command == "native-tier3":
+ config = read_json(args.config)
+ config["SKILL_EVAL_ENV_MODE"] = args.env_mode
+ return native_tier3(args.skill, args.output, config)
+ tiers = tuple(int(tier) for tier in args.tiers.split(","))
+ if not tiers or len(set(tiers)) != len(tiers) or not set(tiers) <= {1, 2, 3}:
+ raise ConfigurationError("Select unique tiers from 1,2,3.")
+ return aggregate(args.reports, tiers, dict(os.environ))
+ except (OSError, ValueError, KeyError) as exc:
+ print(
+ str(exc)
+ if isinstance(exc, ConfigurationError | SelectionError)
+ else "CI execution could not complete safely.",
+ file=sys.stderr,
+ )
+ return 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/ci/select_changed_skills.py b/ci/select_changed_skills.py
index 17148865..469a472d 100644
--- a/ci/select_changed_skills.py
+++ b/ci/select_changed_skills.py
@@ -25,6 +25,17 @@ MAX_ROOTS = 100
MAX_ROOTS_TEXT = 16384
GIT_TIMEOUT = 30
_SHA = re.compile(r"(?:[0-9a-fA-F]{40}|[0-9a-fA-F]{64})")
+# A pull request that changes CI setup evaluates every skill in every tier, so
+# the setup change is exercised. run_tiers uses this predicate directly; the
+# GitHub eligibility script and the GitLab Tier 1 job keep inline copies that
+# tests hold equal to these values.
+SETUP_PREFIXES = (".github/", ".gitlab/", ".skillevaluator/ci")
+SETUP_FILES = frozenset({".gitlab-ci.yml"})
+
+
+def setup_changed(paths: list[str]) -> bool:
+ """Return whether any changed path (both sides of a rename) is CI setup."""
+ return any(path.startswith(SETUP_PREFIXES) or path in SETUP_FILES for path in paths)
class SelectionError(ValueError):
diff --git a/ci/summary_metrics.py b/ci/summary_metrics.py
new file mode 100644
index 00000000..584748c3
--- /dev/null
+++ b/ci/summary_metrics.py
@@ -0,0 +1,115 @@
+# SPDX-License-Identifier: Apache-2.0
+# ruff: noqa: INP001 -- shared trusted CI comment helper.
+"""Summarize already-validated native results without trusting producer metrics."""
+
+from __future__ import annotations
+
+import math
+import unicodedata
+from typing import TYPE_CHECKING
+
+from skillevaluator.models import Severity
+from skillevaluator.reporting.finding_summary import summarize_messages
+from skillevaluator.reporting.run_status import Status, result_status
+
+if TYPE_CHECKING:
+ from skillevaluator.models import ValidationResult
+
+_ISSUE_SEVERITIES = (Severity.CRITICAL, Severity.HIGH, Severity.MEDIUM, Severity.LOW)
+_PLAIN_TEXT = str.maketrans(dict.fromkeys("<>[]`*_~|\\", " ") | {"@": "(at)"})
+_TOP_ISSUE_LIMIT = 160
+
+
+def _plain_text(message: str) -> str | None:
+ # Keep only retained finding/gate text. In particular, do not copy source
+ # lines, legacy provider diagnostics, metadata or suggestions into a comment.
+ printable = "".join(" " if unicodedata.category(character).startswith("C") else character for character in message)
+ text = " ".join(printable.translate(_PLAIN_TEXT).split())
+ if len(text) > _TOP_ISSUE_LIMIT:
+ text = text[: _TOP_ISSUE_LIMIT - 1].rstrip() + "…"
+ return text or None
+
+
+def _number(value: object, *, minimum: float) -> bool:
+ return type(value) in (int, float) and math.isfinite(value) and minimum <= value <= 1
+
+
+def _tier3_metrics(results: list[ValidationResult]) -> tuple[dict, bool]:
+ payloads = [
+ result.metadata["agent_eval"] for result in results if isinstance(result.metadata.get("agent_eval"), dict)
+ ]
+ if len(payloads) != 1:
+ return {}, False
+ payload = payloads[0]
+ summary = payload.get("summary") or payload
+ expected, scored = summary.get("expected_attempts"), summary.get("scored_attempts")
+ coverage_known = type(expected) is int and type(scored) is int and expected > 0 and 0 <= scored <= expected
+ metrics = {"coverage": f"{scored}/{expected}"} if coverage_known else {}
+ complete = (
+ coverage_known
+ and scored == expected
+ and payload.get("execution_status", summary.get("execution_status")) == "succeeded"
+ and not payload.get("execution_errors")
+ and not summary.get("execution_errors")
+ )
+ if complete:
+ for name, key, minimum in (("score", "overall_score", 0), ("skill_lift", "overall_lift", -1)):
+ value = summary.get(key)
+ if _number(value, minimum=minimum):
+ metrics[name] = value
+ return metrics, complete
+
+
+def summarize_results(results: list[ValidationResult], *, tier: int, native: dict | None = None) -> dict:
+ """Return observed issue counts, completeness and one safe highest-severity issue.
+
+ Call only after ``retained_results`` validates the native document. Issue
+ counts include critical/high/medium/low findings, deduplicated by canonical
+ finding ID with their highest severity, plus independent errors and warnings.
+ Canonical message reconciliation excludes finding mirrors and workflow-scope
+ warnings; INFO and success records require no action. Stored summary counters
+ are ignored. Counts remain observed lower bounds when ``issue_count_known``
+ is false; an incomplete zero must not imply clean. With no finding, a retained
+ gate failure or generic diagnostic notice explains the issue without copying
+ legacy execution/provider text into the comment.
+
+ ``native`` is accepted for the caller's uniform interface but is intentionally
+ unused: optional Tier 3 values come from validated result metadata instead.
+ The renderer must still escape all text for its output format.
+ """
+ unique = {}
+ for result in results:
+ for finding in result.findings:
+ if finding.severity not in _ISSUE_SEVERITIES:
+ continue
+ identity = finding.finding_id
+ previous = unique.get(identity)
+ if previous is None or _ISSUE_SEVERITIES.index(finding.severity) < _ISSUE_SEVERITIES.index(
+ previous.severity
+ ):
+ unique[identity] = finding
+ findings = list(unique.values())
+ known = bool(results) and all(
+ not result.is_incomplete
+ and not result.metadata.get("skipped")
+ and result_status(result) not in {Status.INCOMPLETE, Status.SKIPPED, Status.NOT_RUN}
+ for result in results
+ )
+ highest = min(findings, key=lambda finding: _ISSUE_SEVERITIES.index(finding.severity)) if findings else None
+ messages = summarize_messages(results)
+ independent = messages["independent_errors"] + messages["independent_warnings"]
+ message = highest.message if highest else next((gate for result in results for gate in result.gate_failures), None)
+ if not message and independent:
+ message = "Additional validation errors/warnings; see report"
+ metrics = {
+ "issue_count": len(findings) + independent,
+ "issue_count_known": known,
+ "critical_count": sum(finding.severity == Severity.CRITICAL for finding in findings),
+ "high_count": sum(finding.severity == Severity.HIGH for finding in findings),
+ "top_issue": _plain_text(message) if message else None,
+ }
+ if tier == 3:
+ execution, complete = _tier3_metrics(results)
+ metrics.update(execution)
+ metrics["issue_count_known"] = known and complete
+ return metrics
diff --git a/ci/templates/README.md b/ci/templates/README.md
index 62a08c49..c7fdf41f 100644
--- a/ci/templates/README.md
+++ b/ci/templates/README.md
@@ -60,3 +60,42 @@ Open a pull request or merge request that changes a skill to see the checks.
Enable the platform's CI service, allow the referenced workflows or includes,
and provide a compatible runner. The [platform guides](../../docs/repository-integration.mdx)
cover results and merge-gating settings.
+
+
+## Candidate all-tier templates
+
+The unreleased all-tier setup uses two thin consumer files per platform:
+
+| Platform | Evaluation | Trusted feedback |
+| --- | --- | --- |
+| GitHub | [skill-checks-all-tiers.yml](all-tiers/skill-checks-all-tiers.yml) | [feedback-all-tiers.yml](all-tiers/feedback-all-tiers.yml) |
+| GitLab | [gitlab-all-tiers.yml](all-tiers/gitlab-all-tiers.yml) | [gitlab-feedback-all-tiers.yml](all-tiers/gitlab-feedback-all-tiers.yml) |
+
+These files contain placeholders. Use a reviewed schema-version 2 release
+with the platform's all-tier capability and immutable workflow, tools and
+image pins. Released 0.8.0 downloads remain Tier 1 only. Install a reviewed
+candidate build and use `ci init --tiers 1,2,3` to select its bundled
+`ci-release-all-tiers.json`; use `--release` to review an alternate descriptor.
+The all-tier CLI renders these references and approves the exact GitHub caller blob. See
+[the onboarding guide](../../docs/cli-onboarding.mdx#opt-in-to-three-tier-ci).
+Merge the trusted feedback entrypoint onto the default branch before the
+first demo PR/MR. On GitLab, merging into an existing root `.gitlab-ci.yml`
+means replacing the Tier 1 include with exactly the two all-tier includes,
+keeping `test` in any `stages` list, and starting every other job's rules with
+`- if: '$SKILL_EVAL_FEEDBACK == "true"'` / `when: never`, because trusted
+feedback runs as a default-branch pipeline. Merge those guards to the default
+branch before the setup MR; see the
+[GitLab guide](../../docs/gitlab-ci.mdx#merge-into-an-existing-root-configuration).
+Only Tier 1 gates CI; Tier 2 and Tier 3 remain advisory, including failed or
+incomplete outcomes, with their native evidence retained.
+The CLI's `--tier3-required`, GitHub's `tier3-required` input and GitLab's
+`SKILL_EVAL_TIER3_REQUIRED` variable are deprecated and ignored; they cannot
+make Tier 3 blocking. Reports expire after 14 days, Docker is the default, and
+native local mode is also supported.
+
+Maintainers must refresh the candidate descriptor's `workflow_ref`,
+`feedback_ref`, `gitlab_ref` and `tools_ref` together after workflow, runtime or
+feedback fixes, so new consumers receive the reviewed implementation.
+`evaluator_version` and `runtime_lock_sha256` must match the package version and
+`uv.lock` at `tools_ref`. Keep the image digest independently pinned to the
+reviewed Tier 1 image.
diff --git a/ci/templates/all-tiers/feedback-all-tiers.yml b/ci/templates/all-tiers/feedback-all-tiers.yml
new file mode 100644
index 00000000..4a3e6c64
--- /dev/null
+++ b/ci/templates/all-tiers/feedback-all-tiers.yml
@@ -0,0 +1,19 @@
+# SPDX-License-Identifier: Apache-2.0
+# Merge this onto the default branch before expecting automatic PR feedback.
+name: Skill feedback (all tiers)
+on:
+ workflow_run:
+ workflows: ['Skill checks (all tiers)']
+ types: [completed]
+permissions:
+ contents: read
+ actions: read
+ pull-requests: write
+jobs:
+ feedback:
+ uses: NVIDIA/SkillEvaluator/.github/workflows/feedback-all-tiers.yml@RELEASE_WORKFLOW_SHA
+ 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_BLOB
diff --git a/ci/templates/all-tiers/gitlab-all-tiers.yml b/ci/templates/all-tiers/gitlab-all-tiers.yml
new file mode 100644
index 00000000..43f11369
--- /dev/null
+++ b/ci/templates/all-tiers/gitlab-all-tiers.yml
@@ -0,0 +1,48 @@
+# SPDX-License-Identifier: Apache-2.0
+# Root .gitlab-ci.yml; keep MR rules here even though jobs are included.
+# Tier 1 is required; Tier 2 and Tier 3 are advisory.
+# Merging into an existing root file: use exactly these two includes (remove
+# the Tier 1 skill-evaluation.yml include) and keep the file plain YAML.
+# If the root defines stages, keep test: every SkillEvaluator job uses it.
+# Start every other job's rules with the guard shown on build-example below and
+# merge those guards to the default branch first: feedback pipelines run that
+# branch's configuration.
+include:
+ - remote: https://raw.githubusercontent.com/NVIDIA/SkillEvaluator/RELEASE_WORKFLOW_SHA/ci/gitlab/all-tiers.yml
+ - local: .gitlab/skill-feedback.yml
+ rules:
+ - if: '$CI_PIPELINE_SOURCE == "pipeline" && $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH && $SKILL_EVAL_FEEDBACK == "true"'
+variables:
+ SKILL_EVAL_IMAGE: ghcr.io/nvidia/skillevaluator-tier1@sha256:RELEASE_IMAGE_DIGEST
+ SKILL_EVAL_TOOLS_REPOSITORY: NVIDIA/SkillEvaluator
+ SKILL_EVAL_TOOLS_REF: RELEASE_WORKFLOW_SHA
+ SKILL_EVAL_PATHS: skills
+ SKILL_EVAL_TIERS: '1,2,3'
+ SKILL_EVAL_ENV_MODE: docker
+ SKILL_EVAL_PROVIDER: openai
+ SKILL_EVAL_RUNNER: docker
+ SKILL_EVAL_ENVIRONMENT: skillevaluator
+ # Job minutes minus min(20, minutes / 4): leave time to retain evidence.
+ SKILL_EVAL_TIMEOUT_SECONDS: '16800'
+skill-evaluation:
+ rules:
+ - if: '$SKILL_EVAL_FEEDBACK == "true"'
+ when: never
+ - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
+ - if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
+ - if: '$CI_PIPELINE_SOURCE == "web"'
+
+# Job duration must be a literal; GitLab 17.8 does not expand CI variables here.
+skill-evaluation-native:
+ timeout: 5 hours
+
+# Existing jobs: guard them so trusted feedback pipelines skip them. A job
+# without rules, only or except gets the guard followed by `- when: on_success`.
+# Write the guards as rules: the all-tiers include defines the hidden job, so
+# only a job added after this file is on the default branch, without rules,
+# only or except, can use `extends: .skill-evaluation-not-feedback` instead.
+# build-example:
+# rules:
+# - if: '$SKILL_EVAL_FEEDBACK == "true"'
+# when: never
+# - if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
diff --git a/ci/templates/all-tiers/gitlab-feedback-all-tiers.yml b/ci/templates/all-tiers/gitlab-feedback-all-tiers.yml
new file mode 100644
index 00000000..ee1e0afa
--- /dev/null
+++ b/ci/templates/all-tiers/gitlab-feedback-all-tiers.yml
@@ -0,0 +1,9 @@
+# SPDX-License-Identifier: Apache-2.0
+# Save as .gitlab/skill-feedback.yml. Only trusted downstream pipelines include it.
+include:
+ - remote: https://raw.githubusercontent.com/NVIDIA/SkillEvaluator/RELEASE_WORKFLOW_SHA/ci/gitlab/feedback.yml
+ inputs:
+ tools-ref: RELEASE_WORKFLOW_SHA
+ tools-repository: NVIDIA/SkillEvaluator
+ api-url: https://GITLAB_HOST/api/v4
+ project-id: GITLAB_PROJECT_NAMESPACE/PROJECT
diff --git a/ci/templates/all-tiers/skill-checks-all-tiers.yml b/ci/templates/all-tiers/skill-checks-all-tiers.yml
new file mode 100644
index 00000000..c81072da
--- /dev/null
+++ b/ci/templates/all-tiers/skill-checks-all-tiers.yml
@@ -0,0 +1,33 @@
+# SPDX-License-Identifier: Apache-2.0
+# Opt-in candidate template. Use a capability-bearing release, replacing pins.
+# Tier 1 is required; Tier 2 and Tier 3 are advisory.
+name: Skill checks (all tiers)
+on:
+ pull_request:
+ push:
+ branches: [main]
+ workflow_dispatch:
+permissions:
+ contents: read
+ actions: read
+ pull-requests: read
+ id-token: write
+jobs:
+ skills:
+ uses: NVIDIA/SkillEvaluator/.github/workflows/evaluate-all-tiers.yml@RELEASE_WORKFLOW_SHA
+ with:
+ image: ghcr.io/nvidia/skillevaluator-tier1@sha256:RELEASE_IMAGE_DIGEST
+ tools-repository: NVIDIA/SkillEvaluator
+ tools-ref: RELEASE_WORKFLOW_SHA
+ tiers: '1,2,3'
+ paths: skills
+ min-score: 70
+ scan-mode: auto
+ env-mode: docker
+ provider: openai
+ runner: ubuntu-24.04
+ environment: skillevaluator
+ secrets:
+ OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
+ ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
+ NVIDIA_API_KEY: ${{ secrets.NVIDIA_API_KEY }}
diff --git a/ci/tier_manifest.py b/ci/tier_manifest.py
new file mode 100644
index 00000000..21824493
--- /dev/null
+++ b/ci/tier_manifest.py
@@ -0,0 +1,452 @@
+# SPDX-License-Identifier: Apache-2.0
+# ruff: noqa: INP001 -- platform-neutral CI report entrypoint.
+"""Validate and render retained multi-tier CI outcomes without reading skill paths."""
+
+from __future__ import annotations
+
+import copy
+import html
+import json
+import math
+import os
+import re
+import tempfile
+from pathlib import Path, PurePosixPath
+from urllib.parse import quote, urlsplit
+
+_STATUSES = frozenset({"passed", "failed", "incomplete", "skipped", "not_run", "needs_action", "neutral"})
+
+
+def _require(condition: bool, message: str) -> None:
+ if not condition:
+ raise ValueError(message)
+
+
+def _json(value, depth: int = 0, budget: list[int] | None = None) -> None:
+ budget = [100_000] if budget is None else budget
+ budget[0] -= 1
+ _require(budget[0] >= 0 and depth <= 24, "Manifest JSON exceeds its structural budget")
+ if value is None or type(value) in (bool, int):
+ return
+ if isinstance(value, float):
+ _require(math.isfinite(value), "Manifest contains a non-finite number")
+ elif isinstance(value, str):
+ _require(len(value) <= 1_000_000, "Manifest string is too large")
+ elif isinstance(value, list):
+ for item in value:
+ _json(item, depth + 1, budget)
+ elif isinstance(value, dict):
+ for key, item in value.items():
+ _require(isinstance(key, str) and len(key) <= 4096, "Invalid manifest JSON key")
+ _json(item, depth + 1, budget)
+ else:
+ raise ValueError("Manifest must contain JSON values only")
+
+
+def _text(value, field: str, *, limit: int = 4096, empty: bool = False) -> str:
+ _require(
+ isinstance(value, str)
+ and len(value) <= limit
+ and (empty or bool(value))
+ and not any(ord(c) < 32 or ord(c) == 127 for c in value),
+ f"Invalid {field}",
+ )
+ return value
+
+
+def _path(value, field: str, *, skill: bool = False) -> str:
+ value = _text(value, field)
+ if skill and value == ".":
+ return value
+ # Skill directories are escaped display text, never links or file paths, so
+ # they may use any legal POSIX name; only generated report paths reject
+ # backslashes and URL delimiters.
+ _require(
+ (skill or not any(c in value for c in ("\\", ":", "%", "?", "#")))
+ and not value.startswith("/")
+ and not value.endswith("/")
+ and all(part not in {"", ".", ".."} for part in value.split("/"))
+ and PurePosixPath(value).as_posix() == value,
+ f"Unsafe {field}",
+ )
+ return value
+
+
+def validate_manifest(payload: dict) -> dict:
+ """Return a copied canonical manifest; reject contradictory gate claims.
+
+ ``expected_tiers`` defaults to all three tiers. A single-tier producer can
+ explicitly declare its one expected tier. Missing expected required evidence
+ fails the gate; an explicit no-work skip satisfies it with a skipped headline.
+ Additional JSON provenance and historical declared gate policies are retained.
+ New CI producers require only Tier 1; missing paid-tier evidence is advisory.
+ """
+ _require(isinstance(payload, dict), "Manifest must be an object")
+ _json(payload)
+ _require(type(payload.get("schema_version")) is int and payload["schema_version"] == 1, "Invalid schema_version")
+ _require(payload.get("report_contract") == "skillevaluator-ci-v1", "Invalid report_contract")
+ for key in ("commit", "base_commit"):
+ value = payload.get(key)
+ if key == "base_commit" and value is None:
+ continue
+ _require(
+ isinstance(value, str) and re.fullmatch(r"[0-9a-fA-F]{40}|[0-9a-fA-F]{64}", value) is not None,
+ f"Invalid {key}",
+ )
+ repository = _path(payload.get("repository"), "repository")
+ _require("/" in repository and " " not in repository, "Invalid repository")
+ _require(payload.get("platform") in ("github", "gitlab"), "Invalid platform")
+ _require(payload.get("environment") in ("docker", "local"), "Invalid environment")
+ for key in ("run_id", "run_attempt"):
+ value = payload.get(key)
+ _require(isinstance(value, str) and re.fullmatch(r"[1-9][0-9]{0,29}", value) is not None, f"Invalid {key}")
+ tiers = payload.get("tiers")
+ _require(isinstance(tiers, list) and 0 < len(tiers) <= 3, "Manifest requires nonempty tiers")
+ expected = payload.get("expected_tiers", [1, 2, 3])
+ _require(
+ isinstance(expected, list)
+ and bool(expected)
+ and all(type(tier) is int and tier in (1, 2, 3) for tier in expected)
+ and len(expected) == len(set(expected)),
+ "Invalid expected_tiers",
+ )
+ seen = set()
+ for record in tiers:
+ _require(isinstance(record, dict), "Tier must be an object")
+ tier = record.get("tier")
+ _require(type(tier) is int and tier in {1, 2, 3} and tier not in seen, "Invalid or duplicate tier")
+ _require(tier in expected, "Unexpected tier outcome")
+ seen.add(tier)
+ _require(type(record.get("required")) is bool, "Tier required must be boolean")
+ _require(tier != 1 or record["required"], "Tier 1 must be required")
+ _require(isinstance(record.get("status"), str) and record["status"] in _STATUSES, "Invalid tier status")
+ for key in ("reason", "error"):
+ if key in record:
+ _text(record[key], f"tier.{key}", empty=True)
+ if "source_attempt" in record:
+ # A tier job that was not rerun keeps evidence from an earlier attempt of the same run.
+ attempt = record["source_attempt"]
+ _require(
+ isinstance(attempt, str)
+ and re.fullmatch(r"[1-9][0-9]{0,29}", attempt) is not None
+ and int(attempt) <= int(payload["run_attempt"]),
+ "Invalid tier source_attempt",
+ )
+ if "metrics" in record:
+ _require(isinstance(record["metrics"], dict), "Invalid tier metrics")
+ skills = record.get("skills")
+ _require(isinstance(skills, list) and len(skills) <= 1000, "Invalid skills")
+ 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)
+ _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}")
+ if skill[key] is not None:
+ _path(skill[key], key)
+ if "error" in skill:
+ _text(skill["error"], "skill error", empty=True)
+ if "metrics" in skill:
+ _require(isinstance(skill["metrics"], dict), "Invalid skill metrics")
+ if record["status"] == "passed":
+ _require(bool(skills), "Passed tier cannot have empty skills")
+ _require(all(skill["status"] == "passed" for skill in skills), "Tier status contradicts skills")
+ _require(
+ not record.get("error") and not any(skill.get("error") for skill in skills),
+ "Passed tier contains execution errors",
+ )
+ required = [record for record in tiers if record["required"]]
+ missing = set(expected) & {1} - seen
+
+ def satisfies_gate(record):
+ return record["status"] == "passed" or (
+ record["status"] == "skipped" and not record["skills"] and bool(record.get("reason"))
+ )
+
+ overall = not missing and all(satisfies_gate(record) for record in required)
+ observed = {record["status"] for record in required or tiers}
+ status = (
+ "skipped"
+ if observed == {"skipped"} and overall
+ else "passed"
+ if overall and required
+ else next(
+ (
+ candidate
+ for candidate in ("failed", "incomplete", "needs_action", "not_run", "neutral", "skipped", "passed")
+ if candidate in observed
+ ),
+ "not_run",
+ )
+ )
+ if missing:
+ status = "incomplete" if status != "failed" else status
+ if "overall_passed" in payload:
+ _require(
+ type(payload["overall_passed"]) is bool and payload["overall_passed"] == overall,
+ "Overall verdict contradicts required tiers",
+ )
+ validated = copy.deepcopy(payload)
+ if "overall_status" in payload:
+ _require(payload["overall_status"] == status, "Overall status contradicts tier outcomes")
+ validated["overall_passed"] = overall
+ validated["overall_status"] = status
+ validated["expected_tiers"] = list(expected)
+ return validated
+
+
+def tier3_execution_complete(report: dict) -> bool:
+ """Recognize complete paired execution independently of benchmark eligibility.
+
+ Callers retain the native quality verdict and benchmark publication assessment
+ separately. Inapplicable baseline dimensions do not make completed attempts
+ incomplete; missing coverage, run/source binding, or execution errors do.
+ This helper reads the canonical native ``tier3`` carrier and never modifies
+ the supplied report. Imports stay lazy for platform-neutral manifest users.
+ """
+ from skillevaluator.reporting.base import (
+ _agent_eval_attempt_coverage_complete,
+ _agent_eval_consistent_text_field,
+ _agent_eval_execution_errors_clear,
+ _agent_eval_has_publication_target_conflict,
+ _agent_eval_truth_state,
+ agent_eval_case_selection_issue,
+ agent_eval_publication_dataset_provenance,
+ agent_eval_publication_evaluated_at,
+ agent_eval_publication_run_id,
+ agent_eval_publication_target,
+ agent_eval_report_serialization_issue,
+ )
+
+ if not isinstance(report, dict) or report.get("incomplete_scans", []) != []:
+ return False
+ results = report.get("results")
+ if (
+ not isinstance(results, list)
+ or not results
+ or any(not isinstance(result, dict) or result.get("incomplete_scans", []) != [] for result in results)
+ ):
+ return False
+ payload = report.get("tier3")
+ if not isinstance(payload, dict) or agent_eval_report_serialization_issue(payload) is not None:
+ return False
+ verdict, execution_status, truth_consistent = _agent_eval_truth_state(payload)
+ target = agent_eval_publication_target(payload)
+ return bool(
+ _agent_eval_consistent_text_field(payload, "mode") == "both"
+ and truth_consistent
+ and execution_status == "succeeded"
+ and verdict in {"pass", "neutral", "fail"}
+ and _agent_eval_execution_errors_clear(payload)
+ and _agent_eval_attempt_coverage_complete(payload, require_baseline=True)
+ and agent_eval_publication_dataset_provenance(payload) is not None
+ and target is not None
+ and target.skill_name == _agent_eval_consistent_text_field(payload, "skill_name")
+ and not _agent_eval_has_publication_target_conflict(payload)
+ and not any("publication_target_conflict" in result for result in results)
+ and agent_eval_publication_run_id(payload) is not None
+ and agent_eval_publication_evaluated_at(payload) is not None
+ and agent_eval_case_selection_issue(payload) is None
+ )
+
+
+def _tiers(payload: dict) -> list[dict]:
+ by_tier = {record["tier"]: record for record in payload["tiers"]}
+ return [
+ by_tier.get(
+ tier,
+ {
+ "tier": tier,
+ "status": "not_run",
+ "required": tier == 1 and tier in payload["expected_tiers"],
+ "skills": [],
+ "reason": "No retained result" if tier in payload["expected_tiers"] else "Not requested",
+ },
+ )
+ for tier in (1, 2, 3)
+ ]
+
+
+def _md(value) -> str:
+ value = html.escape(str(value), quote=False)
+ return re.sub(r"([\\`*_{}\[\]()#!|])", r"\\\1", value).replace("\r", " ").replace("\n", " ")
+
+
+def _metrics(record: dict) -> str:
+ metrics = record.get("metrics", {})
+ return "; ".join(
+ f"{key.replace('_', ' ')}: "
+ + (
+ json.dumps(value, ensure_ascii=False, allow_nan=False, sort_keys=True)
+ if isinstance(value, list | dict)
+ else str(value)
+ )
+ for key, value in metrics.items()
+ )[:8000]
+
+
+def _evidence(payload: dict, record: dict) -> str:
+ attempt = record.get("source_attempt")
+ reused = attempt and attempt != payload["run_attempt"]
+ return "; ".join(
+ part
+ for part in (
+ record.get("reason", ""),
+ f"evidence from run attempt {attempt}" if reused else "",
+ _metrics(record),
+ )
+ if part
+ )
+
+
+def _report_base(value: str) -> str:
+ if not value:
+ return ""
+ value = _text(value, "report_url")
+ parsed = urlsplit(value)
+ _require(
+ parsed.scheme == "https"
+ and bool(parsed.hostname)
+ and not parsed.username
+ and not parsed.password
+ and "\\" not in value
+ and not parsed.query
+ and not parsed.fragment,
+ "Invalid report_url",
+ )
+ return value.rstrip("/") + "/"
+
+
+def _gate_label(payload: dict) -> str:
+ if payload["overall_status"] == "skipped" and payload["overall_passed"]:
+ return "Skipped"
+ if not any(record["required"] for record in _tiers(payload)):
+ return "Advisory only"
+ return "Passed" if payload["overall_passed"] else "Not passed"
+
+
+def _gate_policy(payload: dict) -> str:
+ records = _tiers(payload)
+ required = ", ".join(f"Tier {record['tier']}" for record in records if record["required"]) or "none"
+ advisory = ", ".join(f"Tier {record['tier']}" for record in records if not record["required"]) or "none"
+ return f"Required tiers: {required}. Advisory tiers: {advisory}."
+
+
+def render_markdown(payload: dict, report_url: str = "") -> str:
+ """Render the required gate, every tier status, and actual native evidence links."""
+ payload = validate_manifest(payload)
+ base = _report_base(report_url)
+ lines = [
+ "# SkillEvaluator CI results",
+ "",
+ f"Required gate: **{_gate_label(payload)}**",
+ "",
+ _gate_policy(payload),
+ "",
+ "| Tier | Status | Gate | Evidence |",
+ "| --- | --- | --- | --- |",
+ ]
+ for record in _tiers(payload):
+ detail = _evidence(payload, record)
+ lines.append(
+ f"| Tier {record['tier']} | {record['status']} | {'Required' if record['required'] else 'Advisory'} | {_md(detail) or 'See skill reports'} |"
+ )
+ for record in _tiers(payload):
+ if not record["skills"]:
+ continue
+ lines.extend(
+ [
+ "",
+ f"## Tier {record['tier']} skill evidence",
+ "",
+ "| Skill | Status | Reports | Findings and metrics |",
+ "| --- | --- | --- | --- |",
+ ]
+ )
+ for skill in record["skills"]:
+ links = []
+ for key, label in (("report_html", "Native HTML"), ("report_json", "JSON")):
+ if skill[key]:
+ url = base + quote(skill[key], safe="/-._~")
+ links.append(f"[{label}]({url})")
+ detail = "; ".join(part for part in (skill.get("error", ""), _metrics(skill)) if part)
+ lines.append(
+ f"| {_md(skill['path'])} | {skill['status']} | {' · '.join(links) or 'Unavailable'} | {_md(detail) or '—'} |"
+ )
+ lines.extend(["", f"Commit: `{payload['commit']}` · Environment: {payload['environment']}", ""])
+ return "\n".join(lines)
+
+
+def _render_html(payload: dict) -> str:
+ h = html.escape
+ lines = [
+ '<!doctype html><html lang="en"><head><meta charset="utf-8">',
+ '<meta name="viewport" content="width=device-width,initial-scale=1">',
+ "<meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'\">",
+ "<title>Three-tier CI results · SkillEvaluator</title>",
+ "<style>body{font:16px system-ui;max-width:1100px;margin:3rem auto;padding:0 1rem;color:#24292f}table{width:100%;border-collapse:collapse}th,td{text-align:left;padding:12px;border-bottom:1px solid #ddd;overflow-wrap:anywhere}a{color:#315b25}p{line-height:1.6}.table{overflow:auto}</style></head><body>",
+ "<h1>SkillEvaluator CI results</h1>",
+ f"<p>Required gate: <strong>{_gate_label(payload)}</strong></p>",
+ f"<p>{_gate_policy(payload)}</p>",
+ '<div class="table"><table><thead><tr><th>Tier</th><th>Status</th><th>Gate</th><th>Evidence</th></tr></thead><tbody>',
+ ]
+ for record in _tiers(payload):
+ detail = _evidence(payload, record)
+ lines.append(
+ f"<tr><td>Tier {record['tier']}</td><td>{record['status']}</td><td>{'Required' if record['required'] else 'Advisory'}</td><td>{h(detail)}</td></tr>"
+ )
+ lines.append("</tbody></table></div>")
+ for record in _tiers(payload):
+ if not record["skills"]:
+ continue
+ lines.append(
+ f'<h2>Tier {record["tier"]} skill evidence</h2><div class="table"><table><thead><tr><th>Skill</th><th>Status</th><th>Reports</th><th>Findings and metrics</th></tr></thead><tbody>'
+ )
+ for skill in record["skills"]:
+ links = []
+ for key, label in (("report_html", "Native HTML"), ("report_json", "JSON")):
+ if skill[key]:
+ links.append(f'<a href="{h(quote(skill[key], safe="/-._~"), quote=True)}">{label}</a>')
+ detail = "; ".join(part for part in (skill.get("error", ""), _metrics(skill)) if part)
+ lines.append(
+ 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>")
+ 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>'
+ )
+ return "\n".join(lines)
+
+
+def write_reports(reports: Path, payload: dict) -> None:
+ """Write manifest, Markdown and HTML without opening linked native evidence."""
+ payload = validate_manifest(payload)
+ reports = Path(reports).absolute()
+ for directory in (reports, *reports.parents):
+ _require(not directory.is_symlink(), "Report directory must not contain symlinks")
+ reports.mkdir(parents=True, exist_ok=True)
+ _require(reports.is_dir(), "Report directory is required")
+ contents = {
+ "ci-results.json": json.dumps(payload, indent=2, ensure_ascii=False, allow_nan=False) + "\n",
+ "summary.md": render_markdown(payload),
+ "index.html": _render_html(payload),
+ }
+ # Preflight every output so rejection does not leave an updated partial set.
+ for name in contents:
+ destination = reports / name
+ _require(
+ not destination.is_symlink() and (not destination.exists() or destination.is_file()),
+ "Report output must be a regular file",
+ )
+ for name, content in contents.items():
+ descriptor, temporary = tempfile.mkstemp(prefix=".ci-report-", dir=reports)
+ try:
+ with os.fdopen(descriptor, "w", encoding="utf-8") as output:
+ output.write(content)
+ Path(temporary).replace(reports / name)
+ finally:
+ if Path(temporary).exists():
+ Path(temporary).unlink()
diff --git a/ci/verify_provenance.py b/ci/verify_provenance.py
index fea90f45..b5cdd165 100644
--- a/ci/verify_provenance.py
+++ b/ci/verify_provenance.py
@@ -113,6 +113,7 @@ def verify_receipt(
run: dict,
evaluator_workflow: str,
evaluator_sha: str,
+ caller_workflow_path: str = WORKFLOW_PATH,
) -> dict:
"""Return signed identity claims only after signature and context validation."""
# This optional publisher dependency is never imported by static scans.
@@ -179,7 +180,7 @@ def verify_receipt(
or claims.get("sha") != workflow_sha
or not isinstance(ref, str)
or len(ref) > 1024
- or claims.get("workflow_ref") != f"{repository}/{WORKFLOW_PATH}@{ref}"
+ or claims.get("workflow_ref") != f"{repository}/{caller_workflow_path}@{ref}"
):
raise ProvenanceError("The execution receipt lacks a valid caller workflow identity.")
if run["event"] == "pull_request":
diff --git a/docs/agents-and-sandboxes.mdx b/docs/agents-and-sandboxes.mdx
index 054a3b60..a2f7aa74 100644
--- a/docs/agents-and-sandboxes.mdx
+++ b/docs/agents-and-sandboxes.mdx
@@ -24,7 +24,7 @@ SkillEvaluator selects the provider-native default: `opencode` for NVIDIA Build,
| --- | --- |
| `claude-code` | Anthropic's Claude Code CLI. `claude` is an accepted alias. Harbor installs Claude Code 2.1.292. Claude 5.5 and later models run with `reasoning_effort=medium`; older models keep Claude Code's default effort. |
| `codex` | OpenAI's Codex CLI. The OpenAI-provider default. Harbor installs Codex 0.161.0. Runs with `reasoning_effort=high` so scores and cost stay comparable across Harbor releases. |
-| `opencode` | The OpenCode CLI. |
+| `opencode` | The OpenCode CLI. Harbor installs OpenCode 1.19.5. |
The pinned CLI releases apply wherever Harbor installs the agent: Docker and
the remote environments. [Local mode](#local-mode) runs the CLI already on your
diff --git a/docs/ci-integration.mdx b/docs/ci-integration.mdx
index ae495a20..5afeb59f 100644
--- a/docs/ci-integration.mdx
+++ b/docs/ci-integration.mdx
@@ -12,6 +12,24 @@ For the prebuilt runtime and one-file consumer setup, see
its PR-comment step is separate from the reusable publisher's hosted-feedback
setup.
+## Managed three-tier CI
+
+For two small consumer files and automatic artifact-backed PR/MR feedback, use
+the opt-in [three-tier CLI onboarding](cli-onboarding.mdx#opt-in-to-three-tier-ci).
+This unreleased capability gates only on Tier 1 and runs advisory Tier 2 and
+paired Tier 3, defaults to Docker, and supports native local mode. Failed or
+incomplete advisory results retain their native evidence without blocking CI.
+The deprecated Tier 3 required settings are ignored. It requires an
+explicit compatible release descriptor and committed native datasets. The
+released Tier 1-only workflows and bundles continue to work unchanged.
+
+The shared evaluator retains native tier reports and an aggregate manifest,
+including incomplete outcomes. A separate trusted feedback entrypoint on the
+default branch verifies the current head and updates one comment linking the
+exact private CI artifact. Local setup and demo commands prepare the remote
+run; inspect that run's gates and reports before considering onboarding verified.
+The hand-written recipes below retain their own CLI flags and policy choices.
+
## Exit codes
`skillevaluator validate` communicates pass/fail through its exit code, so a plain `run:` step is already a gate — no output parsing required.
diff --git a/docs/cli-onboarding.mdx b/docs/cli-onboarding.mdx
index 90d507d9..29036ff8 100644
--- a/docs/cli-onboarding.mdx
+++ b/docs/cli-onboarding.mdx
@@ -1,12 +1,14 @@
---
title: "Set Up CI with the CLI"
-description: "Install SkillEvaluator, answer a few questions and bring automatic skill checks to your GitHub repository."
+description: "Prepare GitHub or GitLab checks and trusted feedback, with an explicit opt-in for three-tier CI."
---
Bring skill evaluation to your GitHub repository in one guided setup.
SkillEvaluator finds your skills, prepares the workflows and opens a setup PR.
If your repository already has skill checks, it can add reporting to that setup.
-Your CI gets **Tier 1 checks, including SkillSpector security scanning**.
+The released default setup gives your CI **Tier 1 checks, including
+SkillSpector security scanning**. The explicit all-tier path below adds
+advisory Tier 2 and paired Tier 3 on GitHub or GitLab. Only Tier 1 gates CI.
```bash title="Run inside your checked-out GitHub repository"
pip install --upgrade skillevaluator
@@ -42,10 +44,157 @@ locally. The shared container supplies the runtime; you control the configuratio
public and private repositories. Hosted feedback supports public Pages and
verified private Pages sites in eligible organization repositories. See
[private report hosting](#private-report-hosting) for the one-time prerequisite.
- This wizard supports GitHub. For GitLab, use the
+ The released Tier 1 wizard supports GitHub. For Tier 1 on GitLab, use the
[GitLab template](/skills/skillevaluator/gitlab-ci).
</Accordion>
+## Opt in to three-tier CI
+
+The new all-tier path supports **GitHub and GitLab** with two small consumer
+files. Tier 1 is the only required tier; Tier 2 and Tier 3 are advisory, including
+failed or incomplete results. `--tier3-required` is deprecated and ignored; it
+cannot make Tier 3 block CI. Docker is the default. `--env-mode local` runs native
+agent CLIs on the selected CI runner. This setup supports these two modes only.
+
+<Note>
+ This is an unreleased capability. Released 0.8.0 bundles and the default
+ `ci init` setup remain Tier 1 only. Install a reviewed candidate build that
+ includes the all-tier CLI and its bundled `ci-release-all-tiers.json`, then
+ opt in with `--tiers 1,2,3`. The CLI selects that descriptor automatically.
+ It must declare schema version 2 and `all-tiers-github` or `all-tiers-gitlab`,
+ with immutable workflow, feedback, tools and image references. A Tier 1
+ descriptor cannot enable all-tier setup.
+</Note>
+
+```bash title="Preview, then open a setup PR or MR"
+skillevaluator ci init --tiers 1,2,3 \
+ --platform github --provider openai --paths skills --mode preview --no-input --show-files
+skillevaluator ci init --tiers 1,2,3 \
+ --platform github --provider openai --paths skills --mode pr --no-input
+```
+
+To review an alternate candidate descriptor, add
+`--release ./reviewed-ci-release.json` to either command. Review its immutable
+references before using it; the option does not install the candidate CLI.
+
+For GitLab 17.0 or later, select `--platform gitlab`. GitHub uses your local
+`gh` login; GitLab uses only a process-scoped `SKILLEVALUATOR_GITLAB_TOKEN`
+for the repository's host, never a generic `GITLAB_TOKEN`. Origins other than
+github.com need `--tiers 1,2,3` or `--platform gitlab` before any API request.
+GitLab setup does not require `glab`.
+`--mode preview` lists the files it would add or change without writing
+anything; add `--show-files` to print their contents.
+`--mode save` writes the two local configuration files; `--mode pr` opens the
+setup review through the platform API. These commands prepare CI configuration;
+they do not run the evaluators on your laptop.
+
+| Local command | Result | Evidence still needed |
+| --- | --- | --- |
+| `ci init` | Prepare the evaluation and trusted feedback entrypoints | Merge the setup and configure the CI runner and secrets |
+| `ci status --tiers 1,2,3` | Read default-branch configuration and latest pipeline status | Inspect the actual CI reports and gates |
+| `ci demo --tiers 1,2,3` | Open a small skill-change PR or MR | Inspect the Tier 1 gate, advisory Tier 2/3 results, comment, and retained reports |
+
+Before the first demo, commit native datasets under each skill's `evals/`
+directory; see [Evaluation Datasets](eval-datasets.mdx). CI reuses those cases
+with full positive and negative paired coverage. It does not generate cases or
+use autopilot. Missing datasets or credentials produce actionable incomplete
+results; they do not count as a passing tier. A passing Tier 1 CI gate does not
+mean the advisory tiers completed or passed. Central dataset mappings are not
+supported by this initial workflow.
+
+The trusted PR or MR comment shows one summary table with a row per skill:
+Static and Security Validation, Deduplication, and Live Agent Evaluation each
+get a one-line status, issue count and main finding or blocker. Counts remain
+unknown for incomplete or missing evidence. Each skill has one **Report** link
+to the run's combined artifact; normal repository authentication and artifact
+expiry apply. Download and extract it, then open `index.html` for the detailed
+aggregate and native reports. Hosted HTML remains optional. See
+[Reports & Results](reports.mdx#retained-three-tier-ci-evidence) for an example.
+
+Create the `skillevaluator` execution environment and store provider secrets
+there (`OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, or `NVIDIA_API_KEY`). GitHub also
+supports the generated explicit mappings from repository CI secrets; scoped
+environment secrets are recommended. On GitHub,
+provider-backed jobs require the initiating actor to have repository write,
+maintain, or admin permission, as verified through GitHub's API. They also
+require the exact current same-repository PR head or current default-branch
+commit. These checks run again after entering the execution environment.
+Environment reviewers are optional: configure them if your repository wants
+manual approval; automatic checks do not require a paid reviewer-protection
+feature. Restrict repository and CI workflow write access to trusted maintainers.
+GitLab's protected execution and feedback prerequisites are described below.
+Choose matching chat and embedding configuration with `--provider`,
+`--embedding-provider`, `--model`, and `--embedding-model`; the default embedding
+provider follows OpenAI or NVIDIA Build; Anthropic defaults to OpenAI embeddings
+and needs that provider's key too. The shared `--model` configures chat/judging
+and the native agent provider default; agent-specific models in committed eval
+configuration keep their native override semantics. `--agents` overrides the
+native provider default: OpenAI uses Codex, Anthropic uses Claude Code, and
+NVIDIA Build uses OpenCode. CI installs Tier 2 or Tier 3 extras from the reviewed
+tools commit. Tier 3 checks the selected environment with `doctor`; local mode
+also installs pinned native CLIs into an isolated runtime directory.
+
+`--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 shorter
+duration, earlier so setup and retained evidence fit. If setup outlasts that
+reserve and GitLab stops the native job at its timeout, the job uploads no
+native evidence and the aggregate reports that tier's evidence as missing.
+GitLab receives a literal duration
+so the configuration also works on GitLab 17.8. `--runner` chooses a GitHub
+runner label or GitLab runner tag. GitHub defaults
+to `ubuntu-24.04`; GitLab defaults to a configured `docker` tag. Docker mode
+requires a working daemon, Docker CLI, Compose v2 and Buildx; GitLab's included Docker-in-Docker service requires
+a privileged runner that shares `/certs/client` for the daemon's TLS client
+certificates. Local mode needs a compatible native runner with Node/npm;
+the generated GitLab local configuration removes the Docker service. Cloud
+sandbox backends are outside this onboarding path.
+
+Merge both generated files onto the default branch **before opening the demo**.
+The first setup PR/MR can show evaluation checks, but automatic comments need
+the trusted feedback entrypoint to exist on the default branch. GitLab also
+needs a protected default branch and a project access token with `api` scope
+and 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
+version prerequisite; offline preview/save leave admission readiness unverified.
+The MR jobs receive no comment token. GitLab's feedback request uses its
+short-lived job token; the initiating user needs permission to create a pipeline
+on the protected default branch, pass pipeline variables and run the protected
+feedback environment. Without it, the request is an allowed failure: no comment
+is posted and the Tier 1 gate is unchanged. GitLab's provider-backed and
+feedback jobs record no deployments. Do not add deployment approval rules to
+their environments: depending on the GitLab version, approvals either do not
+gate these jobs or turn them into manual jobs. Restrict them with the protected
+environments' deploy access.
+See the platform pages for
+[GitHub](github-actions.mdx#three-tier-checks-and-feedback) and
+[GitLab](gitlab-ci.mdx#three-tier-checks-and-feedback) details.
+
+### Upgrade a Tier 1-only consumer
+
+Keep the existing workflow while previewing the explicit all-tier setup with a
+compatible descriptor. Review the new evaluator and feedback pins, provider,
+runner, protected environment, paths and Tier 1-only gate. Remove or disable
+the old Tier 1 caller in the setup review once the new all-tier caller covers
+the same roots, so a PR does not run two independent scans. Merge the new
+feedback entrypoint and then open a fresh demo. Existing released bundles and
+Tier 1-only callers keep their current behavior.
+
+On GitLab, the Tier 1 and all-tier configurations share the root
+`.gitlab-ci.yml`, which the CLI never replaces. `--mode preview` prints the
+rendered files and the merge steps; `--mode save` and `--mode pr` stop with an
+error while a different root file exists. First guard your other jobs with the
+`SKILL_EVAL_FEEDBACK` rule and merge those guards to the default branch: the
+setup MR's own feedback request runs the default branch's current
+configuration. Then, in your setup MR, replace the Tier 1 `skill-evaluation.yml`
+include with the two rendered includes, add the rendered variables, workflow
+rules and job overrides, keep `test` in any `stages` list, and add
+`.gitlab/skill-feedback.yml`. See
+[Merge into an existing root configuration](gitlab-ci.mdx#merge-into-an-existing-root-configuration).
+
## Run the wizard
For a new scan, the wizard discovers folders containing `SKILL.md`. Answer five
@@ -72,7 +221,9 @@ Folders [1]: 1,2
</Frame>
The score threshold does not override required security or schema checks.
-Default Tier 1 checks use no model key. Tier 2 and Tier 3 are not part of this setup.
+Default Tier 1 checks use no model key. Tier 2 and Tier 3 are not part of
+the released Tier 1 wizard described in this section; use the explicit
+[all-tier path](#opt-in-to-three-tier-ci) above for those stages.
<Note>
Already have `.github/workflows/skill-checks.yml`? The CLI recognizes a
diff --git a/docs/environment-variables.mdx b/docs/environment-variables.mdx
index 12eaa55a..14c35ff0 100644
--- a/docs/environment-variables.mdx
+++ b/docs/environment-variables.mdx
@@ -267,3 +267,16 @@ Keep credentials out of skill repositories and CI configuration files. Export pr
- [Providers & Credentials](configuration.mdx) — the setup walkthrough behind the provider variables
- [CLI Reference](cli-reference.mdx) — the per-run flags that override many of these variables
- [Gate Your CI](ci-integration.mdx) — supplying these variables as masked CI secrets
+
+
+## GitLab all-tier admission
+
+| 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_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 its
+own process. Keep that user credential local; the CI publisher uses its separate
+project-scoped credential. The [GitLab setup guide](gitlab-ci.mdx#three-tier-checks-and-feedback)
+describes version detection, variable scopes and the two-file consumer.
diff --git a/docs/github-actions.mdx b/docs/github-actions.mdx
index 6c69c501..d3cdc192 100644
--- a/docs/github-actions.mdx
+++ b/docs/github-actions.mdx
@@ -16,6 +16,78 @@ The shared image includes **Tier 1 and SkillSpector security scanning**.
</Card>
</CardGroup>
+## Three-tier checks and feedback
+
+The opt-in [CLI setup](cli-onboarding.mdx#opt-in-to-three-tier-ci) creates
+`.github/workflows/skill-checks-all-tiers.yml` and
+`.github/workflows/feedback-all-tiers.yml`. This unreleased path needs a reviewed
+candidate build and its bundled capability-bearing descriptor; the 0.8.0
+downloads below remain Tier 1 only. `--tiers 1,2,3` selects the candidate's
+bundled descriptor; `--release` can override it for an alternate reviewed candidate.
+The [candidate source templates](https://github.com/NVIDIA/SkillEvaluator/tree/main/ci/templates)
+contain placeholders and must be filled with reviewed immutable references.
+
+The shared `evaluate-all-tiers.yml` and `feedback-all-tiers.yml` files define
+reusable `workflow_call` workflows. Adding them to SkillEvaluator does not
+enable checks or comments on SkillEvaluator's own pull requests. Each repository,
+including SkillEvaluator itself, needs the generated caller pair committed
+there, with the trusted feedback caller on its default branch.
+
+The evaluation workflow calls the existing hardened Tier 1 container workflow
+at the same evaluator revision. Tier 2 and Tier 3 run independently with
+`fail-fast: false`, Python 3.12, and only their tier's installed extras. Native
+evaluator tools come from the pinned tools commit, while the candidate is
+checked out separately at the exact PR head. Provider-backed jobs require the
+current same-repository PR head or current default-branch commit, plus proven
+write, maintain, or admin repository permission for the initiating actor.
+Both actor permission and commit freshness are checked again before secrets
+are used. Environment-scoped provider secrets in `skillevaluator` are
+recommended; explicit mappings from repository CI secrets are also supported.
+Reviewers are optional: repositories can add an approval rule when they want one, while
+automatic execution does not depend on that GitHub plan feature. Protect
+repository and CI workflow write access as part of maintaining this boundary.
+Fork PRs retain keyless Tier 1 evidence. Provider-backed Tier 2/3 execution needs
+an eligible same-repository run; unavailable evidence remains advisory and visible.
+
+The aggregate job always runs, and only Tier 1 determines its required result.
+Tier 2 and Tier 3 remain advisory when they fail or are incomplete; their native
+statuses and reports remain visible. The deprecated `tier3-required` input is
+ignored, including when set to `true`; it cannot make Tier 3 block CI. Keep the
+aggregate check required in branch protection to enforce Tier 1, and review its
+actual check name in a completed run. Reports are retained for 14
+days in `skill-evaluator-results-attempt-N`, including failed and incomplete
+results, with each tier's native JSON and HTML. **Re-run failed jobs** reuses
+the latest evidence from tier jobs that were not rerun, and records each tier's
+producing attempt as `source_attempt`. Artifact download links require
+normal repository access; they do not create public report hosting.
+
+The feedback workflow starts from `workflow_run` on the default branch. It
+checks out only pinned trusted tools, validates the producer and current PR
+head, and updates one comment with a single summary table. Each skill has
+one-line results for Static and Security Validation, Deduplication, and Live
+Agent Evaluation, plus one **Report** link to the exact run's combined private
+artifact. The lines show status, recorded issue count and the main finding or
+blocker; incomplete or missing evidence shows an unknown count. Download and
+extract the artifact, then open `index.html` for the detailed aggregate and
+native reports. See the
+[comment and report contract](reports.mdx#retained-three-tier-ci-evidence).
+The workflow never checks out the candidate with a write token. Fork PR runs and
+producer attempts superseded by a re-run are skipped without a comment rather than
+failed. The workflow defers only to a report comment whose run marker names a
+newer same-repository producer run or attempt of this caller for the same pull
+request head. Otherwise it updates one existing report comment in place,
+preferring one whose marker verifies, and leaves any other report comments
+untouched. Report comments with unverifiable markers are never deferred to.
+Merge this feedback file onto the default branch before expecting the first
+automatic comment. Changes to the caller must refresh its approved Git blob in
+`trusted-caller-blobs`.
+
+A missing provider key, unavailable runtime, or missing committed native dataset
+must remain visible as an incomplete or needs-action result. Local `ci init`,
+`ci status`, and `ci demo` are setup and inspection commands; a successful setup
+is not evidence that the three tiers passed. Optional Pages hosting remains a
+separate opt-in; artifact feedback works without it.
+
## Get started
The scanner uses one **default validation policy** for public and private
diff --git a/docs/gitlab-ci.mdx b/docs/gitlab-ci.mdx
index e7c43385..56bb033f 100644
--- a/docs/gitlab-ci.mdx
+++ b/docs/gitlab-ci.mdx
@@ -1,6 +1,6 @@
---
title: "GitLab CI/CD"
-description: "Add reusable SkillEvaluator Tier 1 checks to a GitLab repository."
+description: "Add reusable skill checks to GitLab, including an opt-in three-tier pipeline with trusted feedback."
---
Bring skill evaluation to GitLab with a reusable CI job. Point it at your skills
@@ -8,6 +8,202 @@ and choose a quality threshold; merge requests evaluate changed skills
without installing scanners or adding evaluation code to your repository.
The shared container includes SkillSpector security scanning.
+## Three-tier checks and feedback
+
+This path requires **GitLab 17.0 or later** for validated include inputs.
+The unreleased [all-tier CLI path](cli-onboarding.mdx#opt-in-to-three-tier-ci)
+creates two thin files: `.gitlab-ci.yml` includes the pinned shared evaluation
+configuration, and `.gitlab/skill-feedback.yml` includes pinned trusted feedback.
+Install a reviewed candidate build; `--tiers 1,2,3` selects its bundled
+schema-version 2 descriptor declaring `all-tiers-gitlab`. Use `--release` only
+to override it with an alternate reviewed descriptor. Released 0.8.0
+configurations below remain Tier 1 only. The CLI never replaces an existing,
+different `.gitlab-ci.yml`, such as a released Tier 1 setup: `--mode preview`
+prints the rendered files and the merge steps, and `--mode save` and `--mode pr`
+stop with an error until you merge by hand.
+
+### Merge into an existing root configuration
+
+The trusted feedback job validates the root `.gitlab-ci.yml` of the MR
+pipeline, so a merged file must keep this shape:
+
+1. Make `include` exactly the two rendered entries: the pinned `all-tiers.yml`
+ remote and the `.gitlab/skill-feedback.yml` local include with its rule.
+ Remove the Tier 1 `skill-evaluation.yml` include, which defines the same
+ `skill-evaluation` job, and any other include. Feedback rejects other
+ includes and reads the root as plain YAML, so do not use `!reference` tags.
+2. Add the rendered `variables`, replacing earlier `SKILL_EVAL_*` values.
+ If the root defines `stages`, keep `test` in the list: every SkillEvaluator
+ job uses stage `test`, and GitLab rejects a job whose stage is not listed.
+3. Use the rendered `workflow: rules`. Keep your own workflow rules after the
+ two `SKILL_EVAL_FEEDBACK` rules and before the final `when: never`, and
+ only if they still allow merge-request, default-branch and web pipelines.
+4. Replace any `skill-evaluation` override with the rendered
+ `skill-evaluation` and `skill-evaluation-native` entries.
+5. Guard every other job. Trusted feedback runs as a pipeline on the protected
+ default branch, so an unguarded job, such as a deployment gated on the
+ default branch, would run again for every MR. Start each job's rules with
+ the guard. A job that has neither `rules` nor `only`/`except` gets the guard
+ followed by `- when: on_success`:
+
+ ```yaml
+ deploy:
+ script: ./deploy.sh
+ rules:
+ - if: '$SKILL_EVAL_FEEDBACK == "true"'
+ when: never
+ - if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
+ lint:
+ script: make lint
+ rules:
+ - if: '$SKILL_EVAL_FEEDBACK == "true"'
+ when: never
+ - when: on_success
+ ```
+
+ Merge these guards to the default branch before the setup MR. Its own
+ feedback request starts a pipeline from the current default-branch
+ configuration, and the guard is inert until `SKILL_EVAL_FEEDBACK` is set.
+ Write these guards as rules: `.skill-evaluation-not-feedback` is defined by
+ the all-tiers include, so until the setup MR merges,
+ `extends: .skill-evaluation-not-feedback` fails validation with
+ `unknown keys in extends`. After that, a job added later with neither
+ `rules` nor `only`/`except` can use that `extends` instead.
+6. Add `.gitlab/skill-feedback.yml` as rendered and merge both files through
+ a setup MR. After it merges, `skillevaluator ci status --tiers 1,2,3`
+ reports whether the root is recognized and warns about unguarded root jobs.
+
+The shared configuration runs the pinned Tier 1 image plus parallel native
+Tier 2 and Tier 3 jobs. Only Tier 1 is required; Tier 2 and Tier 3 are advisory,
+including failed or incomplete outcomes. The deprecated
+`SKILL_EVAL_TIER3_REQUIRED` variable is ignored, including when set to `'true'`;
+it cannot make Tier 3 block CI. Native execution jobs retain failed outcomes
+without stopping their parallel sibling. The aggregate is the required merge
+gate and follows Tier 1 only: failed, incomplete or missing Tier 1 evidence
+fails it, while advisory outcomes remain visible in retained reports.
+The always-running aggregate job
+retains `skill-evaluator-results/ci-results.json`, `index.html`, `summary.md`,
+and each tier's native reports for 14 days. Reports stay behind your normal
+GitLab artifact access controls.
+
+Trusted MR feedback uses one summary table with a row per skill. Each row has
+one-line results for Static and Security Validation, Deduplication, and Live
+Agent Evaluation, with status, recorded issue count and the main finding or
+blocker. Incomplete or missing evidence shows an unknown count. One **Report**
+link per skill downloads the combined aggregate artifact; extract it and open
+`index.html` for the detailed aggregate and native reports. Separate tier
+sections and per-tier links stay out of the comment. See the
+[comment and report contract](reports.mdx#retained-three-tier-ci-evidence).
+
+Configure a native-job runner matching `SKILL_EVAL_RUNNER` (default `docker`).
+Tier 1, aggregation and feedback jobs have no runner tags and also need a
+compatible runner that accepts untagged jobs and supports their container
+images. This remains necessary when a Linux or macOS shell runner runs the
+native jobs in local mode. Configure the protected
+`SKILL_EVAL_ENVIRONMENT` (default `skillevaluator`) and provider secrets scoped
+to that execution environment. The native jobs and the trusted feedback job
+use `environment: action: prepare`: each receives its environment's scoped
+variables and access protection but records no deployment, so GitLab's
+**Prevent outdated deployment jobs** setting cannot drop an older MR's jobs.
+Do not add deployment approval rules to these environments. Depending on the
+GitLab version and its `prevent_blocking_non_deployment_jobs` feature flag,
+approval rules either do not gate these jobs or turn them into manual jobs
+that wait to be run. Restrict who can run them with the protected
+environments' deploy access. The default Docker
+service needs a privileged runner with Docker-in-Docker enabled. The daemon accepts only TLS clients on
+port 2376 (`DOCKER_TLS_CERTDIR: /certs`), so agent containers cannot use the
+Docker API. Configure the runner with `volumes = ["/certs/client"]` so the job
+can read the generated client certificates. Docker mode also requires the Docker CLI,
+Compose v2 and Buildx; the shared job installs these clients in supported root
+Linux containers and checks readiness before evaluation. For local mode the generated caller
+removes that service; use a Linux or macOS native runner with Python 3.12,
+Git and Node/npm. Missing native tools must be installed by the runner
+administrator; system-package bootstrap is limited to root Linux containers. The
+trusted tools are installed from `SKILL_EVAL_TOOLS_REF`, an immutable commit.
+Local agent CLIs are pinned and bootstrapped before selected-mode readiness
+checks. The current same-project MR head is checked before model execution;
+fork MRs do not receive provider-backed jobs.
+
+GitLab 17.0–18.3 requires a separate project access token with **Reporter** role
+and **read_api** scope for current-MR admission. Store it as masked
+`SKILLEVALUATOR_GITLAB_READ_TOKEN`, scoped only to the configured execution
+environment (`skillevaluator` by default). Protect that environment to approved CI maintainers. For ordinary
+unprotected MR branches, the variable must be available on those refs; enabling
+GitLab's protected-variable restriction would withhold it. The admission helper
+uses this read credential once, refuses HTTP redirects, and the job removes it
+before 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.
+Offline preview/save keep the version unverified. These local commands report
+the prerequisite and do not claim to validate a stored CI secret's privileges.
+The setup still consists of two consumer files.
+
+Protect the default branch and create a project access token with `api` scope
+and the Maintainer role. The publisher reads source-pipeline variables to verify
+provenance as well as reading artifacts and updating MR notes; GitLab 17.8
+rejects the variables request for a Developer token. Store the token as masked, protected
+`SKILLEVALUATOR_GITLAB_TOKEN`, scoped only to the protected
+`skillevaluator-feedback` environment. The MR pipeline never receives that
+token. After aggregation, a small job uses its short-lived `CI_JOB_TOKEN` with
+GitLab's pipeline trigger API to request a separate pipeline on the protected
+default branch. It sends only `SKILL_EVAL_FEEDBACK=true` and the source pipeline
+ID, without forwarding repository variables or caller-supplied pipeline overrides.
+GitLab also adds its own `TRIGGER_PAYLOAD` file variable. The publisher accepts
+that bounded file entry alongside the two selectors and treats its contents as
+opaque; additional caller variables remain disallowed.
+The API supports same-project pipelines; GitLab's declarative multi-project
+bridge rejects a target in the same project. That trusted pipeline uses validated include inputs for fixed evaluator pins,
+API host and project, so forwarded MR variables cannot replace its privileged
+bootstrap. It fetches only pinned evaluator tools and authenticates the server's
+upstream pipeline and source job relationship, then validates the source
+configuration, aggregate artifact, MR and current commit before updating one
+comment. The publisher needs access to the instance's REST and GraphQL APIs;
+the pipeline's persisted MR association supports GitLab 17.x as well.
+The initiating pipeline user must be allowed to create a pipeline on
+the protected default branch, pass the two pipeline variables and run the
+protected feedback environment. Configure these permissions for authorized CI
+maintainers; a job token does not bypass protected-branch or protected-environment permissions.
+The feedback request is advisory. When GitLab refuses it, for example because
+the MR pipeline user cannot run pipelines on the protected default branch or
+may not pass pipeline variables, the request job fails as an allowed failure:
+the pipeline shows a warning, no comment is posted or updated, and the aggregate
+continues to enforce Tier 1. Server and network errors fail the job the same
+way; its log says whether to fix permissions or retry. Before the setup MR
+installs feedback on the default branch, no comment is posted and the aggregate
+still enforces Tier 1.
+
+For a rejected publisher, open its job log. The check location refers to the
+pinned `ci/feedback.py` revision, and the category distinguishes validation,
+authentication and transport failures.
+
+Install both configuration files on the default branch before the first demo
+MR. GitLab must permit the downstream pipeline and the protected feedback job;
+a setup MR alone cannot establish trusted automatic feedback. On instances
+that restrict protected variables in MR pipelines, approve an eligible protected
+execution path according to your project policy; missing provider credentials
+remain actionable evidence rather than a pass. Review the pipeline's actual
+aggregate check before enabling merge restrictions; it gates Tier 1 only.
+
+The CLI's `--timeout-minutes` option writes a literal native-job duration and
+a shorter evaluator budget. The default is 300 minutes. The budget ends 20
+minutes, or a quarter of a shorter duration, before the job timeout, leaving
+time for setup and for retaining evidence: 300 minutes gives 16800 seconds.
+On GitLab 17.8, CI variables are not expanded in a job's `timeout` field. For
+a manual consumer, set the literal directly:
+
+```yaml
+variables:
+ SKILL_EVAL_TIMEOUT_SECONDS: '2040'
+skill-evaluation-native:
+ timeout: 45 minutes
+```
+
+Keep a manual tier selection quoted, for example `SKILL_EVAL_TIERS: '1,2,3'`.
+GitLab's YAML parser reads the unquoted value as the number `123`. The CLI
+quotes generated variable values automatically.
+
## Get started
The shared image applies one default validation policy to public and private
diff --git a/docs/reports.mdx b/docs/reports.mdx
index 1af30fef..13f1cdcf 100644
--- a/docs/reports.mdx
+++ b/docs/reports.mdx
@@ -16,6 +16,92 @@ lift data that `view` and `compare` read back later.
evaluation framework that runs those Tier 3 trials. SkillEvaluator collects its
job artifacts into the results tree described on this page.
+## Retained three-tier CI evidence
+
+The opt-in all-tier workflows retain one aggregate artifact for 14 days. GitHub
+names it `skill-evaluator-results-attempt-N`; GitLab retains the aggregate job's
+`skill-evaluator-results/` directory. The trusted feedback comment links the
+actual artifact download for that run. Authentication and artifact expiry still
+apply; this link does not imply publicly hosted HTML.
+
+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 available
+finding or blocker for **Tier 1 — Static and Security Validation**,
+**Tier 2 — Deduplication** and **Tier 3 — Live Agent Evaluation**. A single
+**Report** link per skill opens the combined report artifact for that run;
+download and extract it, then open `index.html` to inspect the detailed aggregate
+and native reports. The comment keeps tier details in those reports rather
+than adding separate tier sections or report links.
+
+This schematic shows the information in a row; real results supply the statuses,
+counts, findings and authenticated **Report** link:
+
+| Skill | Tier 1 — Static and Security Validation | Tier 2 — Deduplication | Tier 3 — Live Agent Evaluation | Combined report |
+| --- | --- | --- | --- | --- |
+| `skills/example` | Passed · 0 issues | Failed · 1 issue · duplicate content found | Incomplete · issues unknown · paired evidence missing | Report |
+
+Issue counts summarize unique actionable findings plus independent validation
+errors and warnings from retained native evidence; informational notes and
+configuration-only scope notices are excluded. Incomplete or missing evidence
+shows an unknown count; it cannot imply zero findings or a completed check.
+The Tier 1 gate and each advisory tier's status stay separate, so this example
+can pass the required CI gate while still needing review of Tier 2 and Tier 3.
+Every tier selects the same skills: the changed skills, or every skill when
+the pull request changes CI setup under `.github/`, `.gitlab/`,
+`.skillevaluator/ci` or `.gitlab-ci.yml` (on GitHub, also when it changes more
+files than the API can list). A cell for a skill that its tier did not select
+reads `Skipped · issues unknown · Not selected for this tier`.
+
+```text
+ci-results.json
+index.html
+source-attempts.json # GitHub: run attempt whose artifact supplied each tier
+summary.md
+tier1/ # hardened scanner reports, including summary.json
+tier2/ci-tier.json
+tier2/skill-001/ # native retained JSON and HTML
+tier3/ci-tier.json
+tier3/skill-001/ # native retained JSON and HTML
+ diagnostics/ # redacted worker logs when execution failed or is incomplete
+```
+
+`ci-results.json` uses report contract `skillevaluator-ci-v1` and records the
+repository, exact commit, platform, run ID, attempt, environment, and each
+tier's required/advisory policy: Tier 1 has `required: true`, while Tier 2 and
+Tier 3 have `required: false`. On GitHub, each tier with retained evidence
+records `source_attempt`, the run attempt that produced it; after **Re-run
+failed jobs** it can be earlier than the aggregate's own attempt. A tier can be
+`passed`, `failed`, `incomplete`, `skipped`, `not_run`, `needs_action`, or
+`neutral`. `neutral` means Tier 3 paired execution completed with a neutral
+dimension-based verdict; Skill Lift has its own independent diagnostic band.
+Like every Tier 3 status, it is advisory. Failed,
+incomplete or missing Tier 1 evidence fails the aggregate. Tier 2/3 failures and
+incomplete results remain advisory and retain their native status; a passing CI
+gate does not mean those tiers passed. A check that never executed cannot become an empty success.
+The deprecated Tier 3 required settings are ignored in CI. Standalone validation
+and benchmark publication retain their separate policies.
+
+Tier 2 reports retain deduplication and catalog-similarity findings;
+Tier 3 reports retain paired scores and coverage, Skill Lift, attempts,
+latency/resource metrics and available trial links. Download and extract the
+artifact, then open `index.html` to inspect the aggregate and native reports.
+Detailed files remain available even when a tier fails or needs configuration.
+When a native skill's execution fails or is incomplete, or its worker exits
+abnormally, the skill retains bounded, redacted worker, Docker and
+agent-installation diagnostics under `diagnostics/`, even if no canonical report
+was produced or its verdict is failed. A complete run with a failed or neutral
+verdict retains none. The worker's `command.log` comes first, then logs from
+one trial of each Harbor job (a failing trial when there is one), at most four
+trials per skill, with failing trials chosen before passing ones. All
+skills of one tier share a limit of 1000 diagnostic files and 16 MiB. Each
+`index.json` records retained, omitted and truncated files, including those
+omitted at a limit.
+Catalog failures retain diagnostics under `tier2/catalog/diagnostics/`.
+Agent trajectories, credentials and runtime configuration are excluded.
+The publisher renders validated retained JSON; it does not execute artifacts
+or trust candidate-provided HTML in its privileged feedback job. Optional
+report hosting is independent from these private artifact links.
+
## Report formats
Every Tier 1 and Tier 2 command accepts `-r`/`--report` and `-o`/`--output-dir`.
diff --git a/docs/tier1-validation.mdx b/docs/tier1-validation.mdx
index 3d35ab7d..d5439ee8 100644
--- a/docs/tier1-validation.mdx
+++ b/docs/tier1-validation.mdx
@@ -22,6 +22,20 @@ The two-variable [provider setup](configuration.mdx) is enough to configure the
LLM stages for NVIDIA Build or OpenAI. Calling `skillevaluator tier1` without a
path shows help; expert subcommands remain available below.
+## Tier 1 in automatic CI
+
+The [all-tier CI setup](cli-onboarding.mdx#opt-in-to-three-tier-ci) keeps Tier 1
+as a required gate. GitHub calls the hardened legacy scanner workflow at the
+same evaluator commit; GitLab runs the same digest-pinned scanner image.
+Static CI checks receive no model key. Tier 2 and Tier 3 execute independently
+and retain their own native evidence, so one tier's failure does not erase the
+other reports. Changes to onboarding configuration trigger a full Tier 1 scan
+so the setup review exercises actual skills.
+
+Existing released Tier 1-only consumers keep their current workflow and
+bundled image pins. See [GitHub Actions](github-actions.mdx) or
+[GitLab CI/CD](gitlab-ci.mdx) to choose either path.
+
## What Tier 1 checks
The direct `tier1 PATH` workflow runs Tier 1 only, as does
diff --git a/docs/tier2-deduplication.mdx b/docs/tier2-deduplication.mdx
index c2bb502e..8aca0be6 100644
--- a/docs/tier2-deduplication.mdx
+++ b/docs/tier2-deduplication.mdx
@@ -15,6 +15,21 @@ must not leave your machine.
Both checks read local files only.
No external vector database or catalog service is required.
+## Tier 2 in automatic CI
+
+The [all-tier onboarding path](cli-onboarding.mdx#opt-in-to-three-tier-ci)
+runs Tier 2 as an advisory check, independently from the Tier 1 image and paired
+Tier 3 evaluation. Configure chat and embedding provider credentials as CI
+secrets. Tier 2 does not read `evals/`; committed native datasets are needed
+only for [Tier 3](tier3-live-evaluation.mdx). Missing credentials or a central
+dataset mapping produce an actionable incomplete result before paid work.
+
+The aggregate artifact preserves native Tier 2 JSON and HTML, including
+deduplication and catalog-similarity findings. Failed, missing or incomplete
+Tier 2 results stay advisory and do not block a passing Tier 1 CI gate; they are
+never relabeled as completed passes. See
+[retained CI evidence](reports.mdx#retained-three-tier-ci-evidence).
+
## Run Tier 2
```bash title="Check one skill"
diff --git a/docs/tier3-live-evaluation.mdx b/docs/tier3-live-evaluation.mdx
index a0f74fdd..01da045b 100644
--- a/docs/tier3-live-evaluation.mdx
+++ b/docs/tier3-live-evaluation.mdx
@@ -11,6 +11,25 @@ Docker or another sandbox. NVIDIA Build in Docker, Kata, or local mode uses one
for both roles; OpenAI with Codex can also share its key. This guide takes you from a skill directory to a
finished with-skill vs. without-skill comparison.
+## Paired Tier 3 in automatic CI
+
+The [all-tier CI setup](cli-onboarding.mdx#opt-in-to-three-tier-ci) consumes
+committed native `evals/` datasets with full coverage. It runs each selected
+case both with and without the skill; it does not use autopilot, generate new
+cases, or skip the baseline. Docker is the default, with native local mode as
+the other supported CI environment. Cloud backends remain available through
+the expert CLI but are outside this onboarding path.
+
+Tier 3 and Tier 2 are advisory; only Tier 1 gates CI. Onboarding's
+`--tier3-required`, GitHub's `tier3-required` input and GitLab's
+`SKILL_EVAL_TIER3_REQUIRED` variable are deprecated and ignored, even when true;
+they cannot make Tier 3 block CI. CI preserves native
+reports for missing credentials, readiness failures and partial runs as well
+as completed scores. Native reports include coverage and paired arm evidence,
+Skill Lift, attempts, available latency/resource metrics and trial links. An
+incomplete advisory result is visible and never described as a completed pass.
+See [retained CI evidence](reports.mdx#retained-three-tier-ci-evidence).
+
## What a live eval measures
SkillEvaluator runs a real agent (`codex`, `claude-code`, or `opencode` —
@@ -88,10 +107,11 @@ using Harbor 0.24:
`tier3 evaluate` fail the prerequisite check until you reinstall the extra.
- Codex runs with `reasoning_effort=high`, the effort Harbor 0.22 used by
default, so results stay comparable across Harbor upgrades.
-- Harbor installs Codex 0.161.0 and Claude Code 2.1.292 rather than the latest
- release, so a new CLI release does not change results. Claude Code runs
- Claude 5.5 and later models with `reasoning_effort=medium`. Local mode uses
- your installed CLIs and checks that they are new enough for the model.
+- Harbor installs Codex 0.161.0, Claude Code 2.1.292 and OpenCode 1.19.5
+ rather than the latest release, so a new CLI release does not change
+ results. Claude Code runs Claude 5.5 and later models with
+ `reasoning_effort=medium`. Local mode uses your installed CLIs and checks
+ that they are new enough for the model.
- Installed Codex adapters merge existing user and MCP configuration before the
selected runtime provider and endpoint take precedence over conflicting route
keys.
diff --git a/pyproject.toml b/pyproject.toml
index 291ef28c..c287d16b 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -122,7 +122,7 @@ where = ["src"]
include = ["skillevaluator*"]
[tool.setuptools.package-data]
-"skillevaluator" = ["ci-release.json"]
+"skillevaluator" = ["ci-release.json", "ci-release-all-tiers.json"]
"skillevaluator.config" = ["*.yaml", "profiles/*.yaml"]
"skillevaluator.reporting" = ["templates/*.j2", "assets/*.js", "assets/*.md"]
"skillevaluator.tier3.harbor" = [
diff --git a/src/skillevaluator/_ci_onboarding_all_tiers.py b/src/skillevaluator/_ci_onboarding_all_tiers.py
new file mode 100644
index 00000000..c1e040d2
--- /dev/null
+++ b/src/skillevaluator/_ci_onboarding_all_tiers.py
@@ -0,0 +1,996 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Opt-in all-tier callers and host-aware, API-only consumer setup."""
+
+from __future__ import annotations
+
+import base64
+import json
+import os
+import re
+from pathlib import Path, PurePosixPath
+from urllib.error import HTTPError, URLError
+from urllib.parse import quote, urlencode, urlsplit
+from urllib.request import Request
+
+import click
+import yaml
+
+from skillevaluator import _ci_onboarding_git as git
+
+SCAN = ".github/workflows/skill-checks-all-tiers.yml"
+FEEDBACK = ".github/workflows/feedback-all-tiers.yml"
+GL_SCAN = ".gitlab-ci.yml"
+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}")
+# 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"
+_GL_GUARD_IF = re.compile(r"""\s*\$SKILL_EVAL_FEEDBACK\s*==\s*(["'])true\1\s*""")
+_GL_GLOBAL_KEYS = {
+ "after_script",
+ "before_script",
+ "cache",
+ "default",
+ "image",
+ "include",
+ "services",
+ "stages",
+ "variables",
+ "workflow",
+}
+_GL_EVALUATOR_JOBS = {
+ "skill-evaluation",
+ "skill-evaluation-native",
+ "skill-evaluation-aggregate",
+ "skill-evaluation-request-feedback",
+ "skill-evaluation-feedback",
+}
+
+
+def evaluator_timeout_seconds(minutes: int) -> int:
+ """End the evaluator before the CI job limit so setup and evidence retention fit."""
+ return (minutes - min(20, minutes // 4)) * 60
+
+
+class _GitLabVariable(str):
+ """Force GitLab's YAML parser to preserve a CI variable's string value."""
+
+ __slots__ = ()
+
+
+class _GitLabDumper(git.WorkflowDumper):
+ pass
+
+
+def _represent_gitlab_variable(dumper, value):
+ return dumper.represent_scalar("tag:yaml.org,2002:str", value, style='"')
+
+
+_GitLabDumper.add_representer(_GitLabVariable, _represent_gitlab_variable)
+
+
+def _gitlab_yaml_text(document):
+ # GitLab's Ruby parser reads an unquoted 1,2,3 as integer 123. Quote CI
+ # variable scalars without changing typed include inputs or job settings.
+ rendered = dict(document)
+ if "variables" in rendered:
+ rendered["variables"] = {
+ key: _GitLabVariable(value) if isinstance(value, str) else value
+ for key, value in rendered["variables"].items()
+ }
+ return yaml.dump(rendered, Dumper=_GitLabDumper, sort_keys=False, allow_unicode=True, width=1000)
+
+
+def validate_release(data: dict) -> dict:
+ if (
+ not isinstance(data, dict)
+ or data.get("schema_version") != 2
+ or data.get("repository") != "NVIDIA/SkillEvaluator"
+ ):
+ 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):
+ 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, ""))):
+ raise git.SetupError(f"{key} must be an immutable full commit SHA in the all-tier release.")
+ if not re.fullmatch(r"ghcr\.io/nvidia/skillevaluator-tier1@sha256:[0-9a-f]{64}", str(data.get("image", ""))):
+ raise git.SetupError("The Tier 1 image must use the official immutable digest.")
+ return data
+
+
+def validate_tiers(value: str) -> str:
+ values = [part.strip() for part in value.split(",")]
+ if values != ["1", "2", "3"]:
+ raise git.SetupError("All-tier onboarding requires --tiers 1,2,3; omit --tiers for the released Tier 1 setup.")
+ return "1,2,3"
+
+
+def remote(repo: Path, platform: str = "auto") -> tuple[str, str, str]:
+ host, origin, name = git.parse_origin(repo, _parse_origin)
+ detected = "github" if host == "github.com" else "gitlab"
+ selected = detected if platform == "auto" else platform
+ if selected == "github" and host != "github.com":
+ raise git.SetupError("GitHub onboarding currently supports github.com origins.")
+ if selected == "gitlab" and host == "github.com":
+ raise git.SetupError("The selected platform does not match the repository origin.")
+ return selected, origin, name
+
+
+def _parse_origin(value: str) -> tuple[str, str, str]:
+ match = re.fullmatch(r"git@([A-Za-z0-9.-]+):(.+)", value)
+ if match:
+ host, name = match.groups()
+ origin = "https://" + host
+ else:
+ parts = urlsplit(value)
+ if (
+ parts.scheme != "https"
+ or not parts.hostname
+ or parts.username
+ or parts.password
+ or parts.query
+ or parts.fragment
+ ):
+ raise git.SetupError("Use a credential-free HTTPS or git@host SSH repository origin.")
+ host = parts.hostname
+ origin = f"https://{parts.netloc}"
+ name = parts.path.lstrip("/")
+ name = name.removesuffix(".git")
+ if not re.fullmatch(r"[A-Za-z0-9_.-]+(?:/[A-Za-z0-9_.-]+)+", name) or any(
+ p in {".", ".."} for p in name.split("/")
+ ):
+ raise git.SetupError("The origin does not identify a supported project path.")
+ return host, origin, name
+
+
+def gitlab_api(origin: str, method: str, endpoint: str, payload=None, *, missing_ok=False):
+ """Use a process-scoped token and the origin host; never mutate glab auth."""
+ api = os.environ.get("SKILLEVALUATOR_GITLAB_API_URL", origin + "/api/v4").rstrip("/")
+ parsed, expected = urlsplit(api), urlsplit(origin)
+ if (
+ parsed.scheme != "https"
+ or parsed.netloc != expected.netloc
+ or parsed.username
+ or parsed.password
+ or parsed.query
+ or parsed.fragment
+ ):
+ raise git.SetupError("The GitLab API URL must use the HTTPS origin host without credentials.")
+ # Generic GITLAB_TOKEN values are often issued for a different instance than
+ # this origin; only the tool-scoped variable is sent to the origin host.
+ token = os.environ.get("SKILLEVALUATOR_GITLAB_TOKEN")
+ if not token:
+ raise git.SetupError(
+ "Set SKILLEVALUATOR_GITLAB_TOKEN for this GitLab host before using PR/MR or live status commands."
+ )
+ request = Request(
+ api + "/" + endpoint.lstrip("/"),
+ method=method,
+ data=json.dumps(payload).encode() if payload is not None else None,
+ headers={"PRIVATE-TOKEN": token, "Content-Type": "application/json"},
+ )
+ # Disallow redirects so a different host never receives the scoped credential.
+ from urllib.request import HTTPRedirectHandler, build_opener
+
+ class NoRedirect(HTTPRedirectHandler):
+ def redirect_request(self, _req, _fp, _code, _msg, _headers, _newurl):
+ return None
+
+ try:
+ with build_opener(NoRedirect).open(request, timeout=60) as response:
+ body = response.read(8 * 1024 * 1024 + 1)
+ if len(body) > 8 * 1024 * 1024:
+ raise git.SetupError("The GitLab API response exceeded the size limit.")
+ return json.loads(body)
+ except HTTPError as exc:
+ if missing_ok and exc.code == 404:
+ return None
+ raise git.SetupError(
+ f"GitLab API request failed (HTTP {exc.code}); check host, token scope and project access."
+ ) from None
+ except (URLError, ValueError) as exc:
+ raise git.SetupError("GitLab API request failed; check host, authentication and connectivity.") from exc
+
+
+def gitlab_admission_prerequisite(origin, *, online):
+ requirement = {"server_version": None, "read_token_required": None, "verified": False}
+ if not online:
+ return requirement
+ try:
+ result = gitlab_api(origin, "GET", "version")
+ except git.SetupError:
+ return requirement
+ version = result.get("version") if isinstance(result, dict) else None
+ if not isinstance(version, str):
+ return requirement
+ match = re.match(r"^(\d{1,3})\.(\d{1,3})(?:\.|-|$)", version)
+ if match:
+ major, minor = map(int, match.groups())
+ requirement.update(
+ server_version=f"{major}.{minor}", read_token_required=(major, minor) < (18, 4), verified=True
+ )
+ return requirement
+
+
+def _print_gitlab_admission_prerequisite(wizard, requirement):
+ if not requirement["verified"]:
+ wizard.console.print("GitLab server version unverified; admission readiness is unverified.")
+ wizard.console.print(
+ "GitLab before 18.4 needs SKILLEVALUATOR_GITLAB_READ_TOKEN (project Reporter/read_api); configure it until the server version is verified."
+ )
+ elif requirement["read_token_required"]:
+ wizard.console.print(
+ f"GitLab {requirement['server_version']} requires SKILLEVALUATOR_GITLAB_READ_TOKEN (project Reporter/read_api) for current-MR admission."
+ )
+ else:
+ wizard.console.print(f"GitLab {requirement['server_version']} supports CI_JOB_TOKEN for current-MR admission.")
+ wizard.console.print(
+ "Admission credential validity is not verified by local setup/status; inspect the actual CI run."
+ )
+
+
+class Client:
+ def __init__(self, wizard, platform, origin, name):
+ self.wizard, self.platform, self.origin, self.name = wizard, platform, origin, name
+ self.project = f"projects/{quote(name, safe='')}" if platform == "gitlab" else f"repos/{name}"
+
+ def api(self, method, suffix="", payload=None, *, missing_ok=False):
+ if self.platform == "github":
+ return self.wizard.github_api(method, self.project + suffix, payload, missing_ok=missing_ok)
+ return gitlab_api(self.origin, method, self.project + suffix, payload, missing_ok=missing_ok)
+
+ def info(self):
+ info = self.api("GET")
+ if info.get("archived"):
+ raise git.SetupError("Archived repositories cannot be onboarded.")
+ return info
+
+ def file(self, path, ref):
+ suffix = (
+ f"/contents/{path}?ref={quote(ref, safe='')}"
+ if self.platform == "github"
+ else f"/repository/files/{quote(path, safe='')}?ref={quote(ref, safe='')}"
+ )
+ value = self.api("GET", suffix, missing_ok=True)
+ if value is None:
+ return None
+ if value.get("encoding") != "base64":
+ raise git.SetupError("The remote CI configuration is not a supported text file.")
+ try:
+ return base64.b64decode(value["content"], validate=False).decode("utf-8")
+ except (KeyError, ValueError, UnicodeError) as exc:
+ raise git.SetupError("The remote CI configuration could not be decoded.") from exc
+
+ def reviews(self, branch):
+ query = (
+ urlencode({"state": "open", "head": self.name.split("/")[0] + ":" + branch})
+ if self.platform == "github"
+ else urlencode({"state": "opened", "source_branch": branch})
+ )
+ return self.api("GET", ("/pulls?" if self.platform == "github" else "/merge_requests?") + query)
+
+ def create(self, branch, base, files, title, body, *, setup=False):
+ existing = self.reviews(branch)
+ branch_suffix = "/git/ref/heads/" if self.platform == "github" else "/repository/branches/"
+ ref = self.api("GET", branch_suffix + quote(branch, safe=""), missing_ok=True)
+ if ref is not None:
+ if self.platform == "github":
+ comparison = self.api("GET", "/compare/" + quote(base, safe="") + "..." + quote(branch, safe=""))
+ changed_paths = [item["filename"] for item in comparison.get("files", [])]
+ complete = len(changed_paths) < 300
+ else:
+ comparison = self.api("GET", "/repository/compare?" + urlencode({"from": base, "to": branch}))
+ changed_paths = [item["new_path"] for item in comparison.get("diffs", [])]
+ complete = not comparison.get("compare_timeout") and not comparison.get("overflow")
+ if not complete or sorted(changed_paths) != sorted(files):
+ raise git.SetupError("The existing onboarding branch has other changes; it will not be reused.")
+ if any(self.file(path, branch) != content for path, content in files.items()):
+ raise git.SetupError("The existing onboarding branch has different content; it will not be replaced.")
+ if existing:
+ return existing[0].get("html_url") or existing[0]["web_url"]
+ raise git.SetupError("An onboarding branch already exists without an open PR/MR; inspect it manually.")
+ if existing:
+ raise git.SetupError("An open PR/MR exists without its expected branch; inspect it manually.")
+ if self.platform == "gitlab":
+ actions = [
+ {"action": "create" if setup else "update", "file_path": p, "content": c} for p, c in files.items()
+ ]
+ self.api(
+ "POST",
+ "/repository/commits",
+ {"branch": branch, "start_branch": base, "commit_message": title, "actions": actions},
+ )
+ review = self.api(
+ "POST",
+ "/merge_requests",
+ {
+ "source_branch": branch,
+ "target_branch": base,
+ "title": title,
+ "description": body,
+ "remove_source_branch": True,
+ },
+ )
+ else:
+ base_ref = self.api("GET", "/git/ref/heads/" + quote(base, safe=""))
+ parent = base_ref["object"]["sha"]
+ commit = self.api("GET", "/git/commits/" + parent)
+ tree = self.api(
+ "POST",
+ "/git/trees",
+ {
+ "base_tree": commit["tree"]["sha"],
+ "tree": [{"path": p, "mode": "100644", "type": "blob", "content": c} for p, c in files.items()],
+ },
+ )
+ created = self.api("POST", "/git/commits", {"message": title, "tree": tree["sha"], "parents": [parent]})
+ self.api("POST", "/git/refs", {"ref": "refs/heads/" + branch, "sha": created["sha"]})
+ review = self.api("POST", "/pulls", {"base": base, "head": branch, "title": title, "body": body})
+ url = review.get("html_url") or review.get("web_url")
+ parsed = urlsplit(url or "")
+ if (
+ parsed.scheme != "https"
+ or parsed.netloc != urlsplit(self.origin).netloc
+ or not parsed.path.startswith("/" + self.name + "/")
+ ):
+ raise git.SetupError("The branch was created, but its PR/MR URL needs manual inspection.")
+ return url
+
+
+def render(wizard, repo, release, platform, branch, roots, options):
+ common = {
+ "tiers": "1,2,3",
+ "paths": "\n".join(roots),
+ "min-score": options["min_score"],
+ "scan-mode": options["scan_mode"],
+ "env-mode": options["env_mode"],
+ "provider": options["provider"],
+ "embedding-provider": options["embedding_provider"],
+ "model": options["model"] or "",
+ "embedding-model": options["embedding_model"] or "",
+ "agents": options["agents"] or "",
+ "runner": options["runner"],
+ "tools-repository": release["repository"],
+ "tools-ref": release["tools_ref"],
+ "image": release["image"],
+ "n-attempts": options["n_attempts"],
+ "n-concurrent": options["n_concurrent"],
+ "timeout-minutes": options["timeout_minutes"],
+ "environment": options["environment"],
+ }
+ header = "# Generated by SkillEvaluator all-tier CI onboarding.\n"
+ if platform == "github":
+ scan = {
+ "name": "Skill checks (all tiers)",
+ "on": {"pull_request": None, "push": {"branches": [branch]}, "workflow_dispatch": None},
+ "permissions": {"contents": "read", "id-token": "write", "pull-requests": "read", "actions": "read"},
+ "jobs": {
+ "skills": {
+ "uses": f"{release['repository']}/.github/workflows/evaluate-all-tiers.yml@{release['workflow_ref']}",
+ "with": common,
+ "secrets": {
+ key: "${{ secrets." + key + " }}"
+ for key in ("OPENAI_API_KEY", "ANTHROPIC_API_KEY", "NVIDIA_API_KEY")
+ },
+ }
+ },
+ }
+ scan_text = header + wizard.yaml_text(scan)
+ feedback = {
+ "name": "Skill feedback (all tiers)",
+ "on": {"workflow_run": {"workflows": ["Skill checks (all tiers)"], "types": ["completed"]}},
+ "permissions": {"actions": "read", "contents": "read", "pull-requests": "write"},
+ "jobs": {
+ "feedback": {
+ "uses": f"{release['repository']}/.github/workflows/feedback-all-tiers.yml@{release['feedback_ref']}",
+ "with": {
+ "tools-repository": release["repository"],
+ "tools-ref": release["tools_ref"],
+ "trusted-workflow-ref": f"{release['repository']}/.github/workflows/evaluate-all-tiers.yml@{release['workflow_ref']}",
+ "trusted-caller-blobs": wizard.committed_blob(repo, SCAN, scan_text),
+ },
+ }
+ },
+ }
+ return {SCAN: scan_text, FEEDBACK: header + wizard.yaml_text(feedback)}
+ variables = {
+ "SKILL_EVAL_" + key.upper().replace("-", "_"): str(value).lower() if isinstance(value, bool) else str(value)
+ for key, value in common.items()
+ if key not in {"paths", "image", "tools-repository", "tools-ref", "environment", "runner", "timeout-minutes"}
+ }
+ variables.update(
+ {
+ "SKILL_EVAL_PATHS": "\n".join(roots),
+ "SKILL_EVAL_IMAGE": release["image"],
+ "SKILL_EVAL_TIMEOUT_SECONDS": str(evaluator_timeout_seconds(options["timeout_minutes"])),
+ "SKILL_EVAL_TOOLS_REPOSITORY": release["repository"],
+ "SKILL_EVAL_TOOLS_REF": release["tools_ref"],
+ "SKILL_EVAL_ENVIRONMENT": options["environment"],
+ "SKILL_EVAL_RUNNER": options["runner"],
+ }
+ )
+ upstream = f"https://raw.githubusercontent.com/{release['repository']}/{release['gitlab_ref']}/ci/gitlab/"
+ scan = {
+ "include": [
+ {"remote": upstream + "all-tiers.yml"},
+ {
+ "local": GL_FEEDBACK,
+ "rules": [
+ {
+ "if": '$CI_PIPELINE_SOURCE == "pipeline" && $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH && $SKILL_EVAL_FEEDBACK == "true"'
+ }
+ ],
+ },
+ ],
+ "variables": variables,
+ "workflow": {
+ "rules": [
+ {
+ "if": '$CI_PIPELINE_SOURCE == "pipeline" && $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH && $SKILL_EVAL_FEEDBACK == "true"'
+ },
+ {"if": '$SKILL_EVAL_FEEDBACK == "true"', "when": "never"},
+ {"if": '$CI_PIPELINE_SOURCE == "merge_request_event"'},
+ {"if": "$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH"},
+ {"if": '$CI_PIPELINE_SOURCE == "web"'},
+ {"when": "never"},
+ ]
+ },
+ "skill-evaluation": {
+ "rules": [
+ {"if": '$SKILL_EVAL_FEEDBACK == "true"', "when": "never"},
+ {"if": '$CI_PIPELINE_SOURCE == "merge_request_event"'},
+ {"if": "$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH"},
+ {"if": '$CI_PIPELINE_SOURCE == "web"'},
+ ]
+ },
+ }
+ # GitLab 17.8 validates job timeout before expanding CI variables.
+ scan["skill-evaluation-native"] = {"timeout": str(options["timeout_minutes"]) + " minutes"}
+ if options["env_mode"] == "local":
+ scan["skill-evaluation-native"]["services"] = []
+ _, origin, project = remote(repo, "gitlab")
+ feedback_include = {
+ "remote": upstream + "feedback.yml",
+ "inputs": {
+ "tools-ref": release["tools_ref"],
+ "tools-repository": release["repository"],
+ "api-url": origin + "/api/v4",
+ "project-id": project,
+ },
+ }
+ return {
+ GL_SCAN: header + _gitlab_yaml_text(scan),
+ GL_FEEDBACK: header + _gitlab_yaml_text({"include": [feedback_include]}),
+ }
+
+
+def _gitlab_root_needs_merge(repo, platform, files) -> bool:
+ """A different existing root .gitlab-ci.yml is merged by hand, never replaced."""
+ target = repo / GL_SCAN
+ return (
+ platform == "gitlab"
+ and not target.is_symlink()
+ and target.is_file()
+ and target.read_bytes() != files[GL_SCAN].encode()
+ )
+
+
+def _refuse_gitlab_root_replacement(mode):
+ if mode in {"save", "pr"}:
+ raise git.SetupError(
+ f"{GL_SCAN} already exists with different content; it will not be replaced. "
+ "Run --mode preview to print the rendered configuration and the manual merge steps, "
+ "then merge and commit it yourself."
+ )
+
+
+def _print_gitlab_root_merge_steps(wizard, existing):
+ unguarded = gitlab_unguarded_jobs(existing)
+ steps = [
+ f"{GL_SCAN} already exists; it will not be replaced. Merge the rendered files below by hand:",
+ f"1. Make the root include list exactly the two rendered entries: the pinned all-tiers.yml remote and "
+ f"the {GL_FEEDBACK} local include with its rule. Remove the Tier 1 skill-evaluation.yml include and any "
+ "other include; trusted feedback rejects other includes. Keep the root plain YAML (no !reference tags).",
+ "2. Add the rendered variables, replacing earlier SKILL_EVAL_* values. If the root defines stages, "
+ "keep test in the list; every SkillEvaluator job uses stage test.",
+ "3. Use the rendered workflow rules. Keep any of your own workflow rules after the two SKILL_EVAL_FEEDBACK "
+ "rules and before the final when: never, and only if they still allow merge-request, default-branch "
+ "and web pipelines.",
+ "4. Replace any skill-evaluation job override with the rendered skill-evaluation and "
+ "skill-evaluation-native entries.",
+ "5. Feedback pipelines run on the default branch. Start the rules of every other job with this "
+ "guard; give a job without rules, only or except the guard followed by - when: on_success:"
+ "\n - if: '$SKILL_EVAL_FEEDBACK == \"true\"'\n when: never",
+ (f" Jobs to guard: {', '.join(unguarded)}. " if unguarded else " ")
+ + "Merge the guards to the default branch first: the setup MR's own feedback request runs that "
+ f"branch's current configuration. Write those guards as rules: extends: {GL_NOT_FEEDBACK} works only "
+ "after the all-tiers include is on the default branch, for example for a job added later.",
+ f"6. Create {GL_FEEDBACK} with the rendered content.",
+ "7. Commit both through a merge request; after it merges, ci status --tiers 1,2,3 reports whether "
+ "the root is recognized.",
+ ]
+ for line in steps:
+ wizard.console.print(line, markup=False)
+
+
+def initialize(
+ wizard,
+ *,
+ repo,
+ release_path,
+ paths,
+ min_score,
+ scan_mode,
+ default_branch,
+ full,
+ custom_url,
+ mode,
+ no_input,
+ show_files,
+ output,
+ tiers,
+ platform,
+ **options,
+):
+ validate_tiers(tiers)
+ repo = git.repository_root(repo)
+ if no_input and mode is None:
+ raise git.SetupError("--no-input requires an explicit --mode.")
+ if custom_url:
+ raise git.SetupError(
+ "All-tier onboarding currently links private CI artifacts; --report-url applies to the legacy Tier 1 setup."
+ )
+ if full is False:
+ raise git.SetupError("All-tier onboarding includes trusted PR/MR feedback. Omit --checks-only.")
+ descriptor = release_path or Path(wizard.__file__).with_name("ci-release-all-tiers.json")
+ if not descriptor.is_file():
+ raise git.SetupError(
+ "This installation has no packaged all-tier release descriptor; supply a reviewed candidate using --release."
+ )
+ release = validate_release(json.loads(descriptor.read_text()))
+ 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.")
+ branch = git.infer_branch(repo, default_branch)
+ roots = git.discover(repo)
+ for index, item in enumerate(roots, 1):
+ wizard.console.print(f"{index}. {item['root']} ({item['count']} skills)", markup=False)
+ selected = wizard.select_roots(roots, paths, no_input)
+ options.update(
+ min_score=70 if min_score is None else min_score, scan_mode=scan_mode or "auto", tier3_required=False
+ )
+ options["embedding_provider"] = options["embedding_provider"] or (
+ "openai" if options["provider"] == "anthropic" else options["provider"]
+ )
+ options["runner"] = options["runner"] or ("ubuntu-24.04" if platform == "github" else "docker")
+ files = render(wizard, repo, release, platform, branch, selected, options)
+ merge_root = _gitlab_root_needs_merge(repo, platform, files)
+ if merge_root:
+ _refuse_gitlab_root_replacement(mode)
+ changed = wizard.check_files(repo, {p: c for p, c in files.items() if not (merge_root and p == GL_SCAN)})
+ if merge_root:
+ changed.insert(0, GL_SCAN)
+ if output:
+ output = output.resolve()
+ if output.exists() or output.is_relative_to(repo):
+ raise git.SetupError("Choose a new receipt path outside the consumer checkout.")
+ # Fail before saving files or opening a PR/MR, never after.
+ output.parent.mkdir(parents=True, exist_ok=True)
+ wizard.console.print(
+ f"{platform.title()} | Tier 1 required; Tiers 2 and 3 advisory",
+ markup=False,
+ )
+ wizard.console.print(
+ f"Environment: {options['env_mode']} | provider: {options['provider']} | runner: {options['runner']}",
+ markup=False,
+ )
+ wizard.console.print(
+ "Tier 2 needs chat and embedding credentials. Tier 3 needs committed native eval datasets and runs paired coverage."
+ )
+ wizard.console.print(
+ "Store provider keys in CI secrets and authorize the protected "
+ + options["environment"]
+ + " environment before model execution.",
+ markup=False,
+ )
+ if platform == "gitlab":
+ wizard.console.print(
+ "GitLab: protect the default branch and add a scoped protected SKILLEVALUATOR_GITLAB_TOKEN for trusted feedback. Permit job-token pipeline triggers; the initiating user needs permission to run protected-default-branch pipelines, pass pipeline variables and run the feedback environment."
+ )
+ mode = mode or click.prompt("Next", default="preview", type=click.Choice(["preview", "save", "pr"]))
+ if merge_root:
+ _refuse_gitlab_root_replacement(mode)
+ admission = None
+ if platform == "gitlab":
+ admission = gitlab_admission_prerequisite(origin, online=mode == "pr")
+ _print_gitlab_admission_prerequisite(wizard, admission)
+ plan = {
+ "repository": name,
+ "platform": platform,
+ "default_branch": branch,
+ "selected_roots": selected,
+ "tiers": [1, 2, 3],
+ "release": release,
+ "options": options,
+ "changed_files": changed,
+ "requested_action": mode,
+ }
+ if admission is not None:
+ plan["gitlab_admission"] = admission
+ if mode == "preview":
+ plan["action"] = "preview"
+ if merge_root:
+ _print_gitlab_root_merge_steps(wizard, (repo / GL_SCAN).read_text(errors="replace"))
+ show_files = True
+ if changed:
+ wizard.console.print(
+ "Proposed files:" if show_files else "Proposed files (add --show-files to print them):"
+ )
+ for path in changed:
+ wizard.console.print(" " + path, markup=False)
+ else:
+ wizard.console.print("The all-tier files already match this checkout.")
+ wizard.console.print(
+ "No changes applied. These are candidate pinned workflows; configuration is not a verified evaluation."
+ )
+ elif not no_input and not click.confirm(
+ "Save files?" if mode == "save" else "Open the setup PR/MR?", default=False
+ ):
+ plan["action"] = "cancelled"
+ wizard.console.print("Cancelled. No changes applied.")
+ elif mode == "save":
+ wizard.save_files(repo, files)
+ plan["action"] = "saved" if changed else "unchanged"
+ wizard.console.print("Files saved. Remote settings were not changed.")
+ else:
+ git.require_clean(repo)
+ if platform == "github":
+ # Git API commits bypass local clean filters; approve the uploaded bytes.
+ feedback = yaml.safe_load(files[FEEDBACK])
+ feedback["jobs"]["feedback"]["with"]["trusted-caller-blobs"] = wizard.blob_id(files[SCAN])
+ files[FEEDBACK] = "# Generated by SkillEvaluator all-tier CI onboarding.\n" + wizard.yaml_text(feedback)
+ client = Client(wizard, platform, origin, name)
+ info = client.info()
+ if info.get("default_branch") != branch:
+ raise git.SetupError("The live default branch differs; rerun with --default-branch.")
+ pending = {}
+ for path, content in files.items():
+ current = client.file(path, branch)
+ if current is not None and current != content:
+ raise git.SetupError(
+ f"{path} differs on the default branch; it will not be replaced."
+ + (
+ " Update your checkout to the default branch, then run --mode preview to print the"
+ " manual merge steps."
+ if path == GL_SCAN
+ else ""
+ )
+ )
+ if current is None:
+ pending[path] = content
+ if pending:
+ url = client.create(
+ SETUP_BRANCH,
+ branch,
+ pending,
+ "Set up SkillEvaluator all-tier checks and feedback",
+ "Add pinned Tier 1 required checks, Tier 2 and Tier 3 advisory evaluation, and trusted feedback linking retained private CI artifacts.\n\nMerge this setup, configure provider credentials and the protected execution environment, then run `skillevaluator ci demo --tiers 1,2,3`. This setup is not an evaluation pass.",
+ setup=True,
+ )
+ plan.update(action="created-pr", pr_url=url)
+ wizard.console.print("Setup PR/MR ready. Merge it, then run skillevaluator ci demo --tiers 1,2,3.")
+ wizard.print_link(url)
+ else:
+ plan["action"] = "configured"
+ wizard.console.print("All-tier files already match the default branch.")
+ if show_files:
+ for path, text in files.items():
+ wizard.console.print(path, markup=False)
+ wizard.console.print(text, markup=False, soft_wrap=True)
+ if output:
+ with output.open("x") as stream:
+ json.dump(plan, stream, indent=2)
+ stream.write("\n")
+ return plan
+
+
+def is_all_tier(repo, platform="auto", tiers=None):
+ selected, _, _ = remote(repo, platform)
+ if tiers is not None or platform == "gitlab" or (repo / SCAN).exists():
+ return True
+ if selected == "gitlab":
+ if (repo / GL_FEEDBACK).exists():
+ return True
+ # Never contact an unrecognized origin host without an explicit opt-in.
+ raise git.SetupError("This origin is not github.com. For GitLab all-tier onboarding, add --tiers 1,2,3.")
+ return False
+
+
+def trusted_blobs(raw) -> list[str] | None:
+ """Parse approved caller blobs exactly like the trusted feedback job."""
+ pins = [part.strip() for part in re.split(r"[,\n]", str(raw or ""))]
+ return pins if 0 < len(pins) <= 32 and all(SHA.fullmatch(pin) for pin in pins) else None
+
+
+def _github_workflow_inputs(text: str, job_name: str, workflow: str) -> tuple[dict, str | None]:
+ """Recognize pinned all-tier callers without treating arbitrary YAML as setup."""
+ try:
+ document = yaml.safe_load(text)
+ except yaml.YAMLError:
+ return {}, "invalid YAML"
+ jobs = document.get("jobs") if isinstance(document, dict) else None
+ job = jobs.get(job_name) if isinstance(jobs, dict) else None
+ expected = rf"NVIDIA/SkillEvaluator/\.github/workflows/{re.escape(workflow)}@[0-9a-f]{{40}}"
+ if not isinstance(job, dict) or not re.fullmatch(expected, str(job.get("uses", ""))):
+ return {}, "missing the immutable reusable workflow"
+ inputs = job.get("with")
+ if not isinstance(inputs, dict):
+ return {}, "missing reusable workflow inputs"
+ if job_name == "skills" and inputs.get("tiers", "1,2,3") != "1,2,3":
+ return {}, "not all three tiers are selected"
+ if not SHA.fullmatch(str(inputs.get("tools-ref", ""))):
+ return {}, "missing an immutable tools-ref"
+ if job_name == "skills":
+ if not re.fullmatch(r"ghcr\.io/nvidia/skillevaluator-tier1@sha256:[0-9a-f]{64}", str(inputs.get("image", ""))):
+ return {}, "missing the immutable Tier 1 image"
+ else:
+ producer = r"NVIDIA/SkillEvaluator/\.github/workflows/evaluate-all-tiers\.yml@[0-9a-f]{40}"
+ if not re.fullmatch(producer, str(inputs.get("trusted-workflow-ref", ""))):
+ return {}, "missing the immutable trusted-workflow-ref"
+ blobs = inputs.get("trusted-caller-blobs")
+ if not isinstance(blobs, str) or not blobs.strip():
+ return {}, "missing trusted-caller-blobs"
+ return inputs, None
+
+
+def gitlab_config_problem(text: str) -> str | None:
+ """Mirror ci/feedback.py validate_gitlab_config for the default-branch root config."""
+ try:
+ document = yaml.safe_load(text)
+ except yaml.YAMLError:
+ return "invalid YAML"
+ includes = document.get("include") if isinstance(document, dict) else None
+ if not isinstance(includes, list) or len(includes) != 2:
+ return "missing the pinned evaluator and trusted feedback includes"
+ expected_rule = (
+ '$CI_PIPELINE_SOURCE == "pipeline" && $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH && $SKILL_EVAL_FEEDBACK == "true"'
+ )
+ pinned = re.compile(
+ r"https://raw\.githubusercontent\.com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+/[0-9a-f]{40}/ci/gitlab/all-tiers\.yml"
+ )
+ remotes = [i for i in includes if isinstance(i, dict) and set(i) == {"remote"}]
+ locals_ = [i for i in includes if i == {"local": GL_FEEDBACK, "rules": [{"if": expected_rule}]}]
+ if len(remotes) != 1 or not isinstance(remotes[0]["remote"], str) or not pinned.fullmatch(remotes[0]["remote"]):
+ return "missing an immutable evaluator include"
+ if len(locals_) != 1:
+ return "missing the trusted downstream feedback include"
+ return None
+
+
+def _gitlab_rules(document, job, depth=0):
+ if "rules" in job or depth > 10:
+ return job.get("rules")
+ extends = job.get("extends")
+ for parent in reversed([extends] if isinstance(extends, str) else extends if isinstance(extends, list) else []):
+ if parent == GL_NOT_FEEDBACK:
+ return [GL_FEEDBACK_GUARD]
+ base = document.get(parent)
+ rules = _gitlab_rules(document, base, depth + 1) if isinstance(base, dict) else None
+ if rules is not None:
+ return rules
+ return None
+
+
+_GL_UNSET = object()
+
+
+def _gitlab_inherited(document, job, key, depth=0):
+ """Resolve key as extends does: the job's own value, even null, wins, then the last parent defining it."""
+ if not isinstance(job, dict) or depth > 10:
+ return _GL_UNSET
+ if key in job:
+ return job[key]
+ extends = job.get("extends")
+ for parent in reversed([extends] if isinstance(extends, str) else extends if isinstance(extends, list) else []):
+ value = (
+ _gitlab_inherited(document, document.get(parent), key, depth + 1) if isinstance(parent, str) else _GL_UNSET
+ )
+ if value is not _GL_UNSET:
+ return value
+ return _GL_UNSET
+
+
+def _gitlab_only_except(document, job) -> bool:
+ """GitLab rejects only/except beside rules, including inherited ones; a null value drops an inherited key."""
+ values = [_gitlab_inherited(document, job, key) for key in ("only", "except")]
+ return any(value is not None and value is not _GL_UNSET for value in values)
+
+
+def gitlab_unguarded_jobs(text: str) -> list[str]:
+ """Name root jobs that a trusted default-branch feedback pipeline would also run."""
+ try:
+ document = yaml.safe_load(text)
+ except yaml.YAMLError:
+ return []
+ if not isinstance(document, dict):
+ return []
+ unguarded = []
+ for name, job in document.items():
+ if (
+ not isinstance(name, str)
+ or not isinstance(job, dict)
+ or name.startswith(".")
+ or name in _GL_GLOBAL_KEYS
+ or name in _GL_EVALUATOR_JOBS
+ ):
+ continue
+ rules = _gitlab_rules(document, job)
+ first = rules[0] if isinstance(rules, list) and rules else None
+ # A job keeping only/except cannot also carry the guard rules.
+ if _gitlab_only_except(document, job) or not (
+ isinstance(first, dict)
+ and set(first) == {"if", "when"}
+ and first["when"] == "never"
+ and isinstance(first["if"], str)
+ and _GL_GUARD_IF.fullmatch(first["if"])
+ ):
+ unguarded.append(name)
+ return unguarded
+
+
+def inspect(wizard, repo, platform="auto", tiers=None):
+ if tiers is not None:
+ validate_tiers(tiers)
+ platform, origin, name = remote(repo, platform)
+ client = Client(wizard, platform, origin, name)
+ info = client.info()
+ branch = info["default_branch"]
+ scan_path, feedback_path = (SCAN, FEEDBACK) if platform == "github" else (GL_SCAN, GL_FEEDBACK)
+ scan, feedback = client.file(scan_path, branch), client.file(feedback_path, branch)
+ problem, feedback_problem, feedback_inputs = None, None, {}
+ if platform == "github":
+ if scan is not None:
+ _, problem = _github_workflow_inputs(scan, "skills", "evaluate-all-tiers.yml")
+ if feedback is not None:
+ feedback_inputs, feedback_problem = _github_workflow_inputs(feedback, "feedback", "feedback-all-tiers.yml")
+ elif scan is not None:
+ problem = gitlab_config_problem(scan)
+ wizard.console.print(f"{platform.title()} {name} | default branch: {branch}", markup=False)
+ wizard.console.print(
+ "All-tier checks: "
+ + (
+ "awaiting setup PR/MR merge"
+ if scan is None
+ else f"{scan_path} is present but not an all-tier configuration ({problem})"
+ if problem
+ else "configured"
+ ),
+ markup=False,
+ )
+ wizard.console.print(
+ "Trusted feedback: "
+ + (
+ "missing"
+ if feedback is None
+ else f"{feedback_path} is present but not a trusted feedback configuration ({feedback_problem})"
+ if feedback_problem
+ else "configured"
+ ),
+ markup=False,
+ )
+ # Advisory only; the trusted include check above keeps parity with feedback.
+ unguarded = gitlab_unguarded_jobs(scan) if scan and platform == "gitlab" and not problem else []
+ if unguarded:
+ wizard.console.print(
+ "Warning: trusted feedback pipelines on the default branch also run "
+ + ", ".join(unguarded)
+ + ". Start their rules with if: '$SKILL_EVAL_FEEDBACK == \"true\"' and when: never; a job without "
+ + "rules, only or except can extend "
+ + GL_NOT_FEEDBACK
+ + ".",
+ markup=False,
+ )
+ if platform == "gitlab":
+ _print_gitlab_admission_prerequisite(wizard, gitlab_admission_prerequisite(origin, online=True))
+ if scan is not None and feedback is not None and platform == "github" and not problem and not feedback_problem:
+ pins = trusted_blobs(feedback_inputs.get("trusted-caller-blobs"))
+ wizard.console.print(
+ "Scan approval: "
+ + (
+ "Malformed approval list; feedback will reject it"
+ if pins is None
+ else "matches exact workflow"
+ if wizard.blob_id(scan) in pins
+ else "Needs refresh; feedback will reject it"
+ )
+ )
+ suffix = (
+ "/actions/workflows/skill-checks-all-tiers.yml/runs?per_page=1"
+ if platform == "github"
+ else "/pipelines?" + urlencode({"ref": branch, "per_page": 1})
+ )
+ if problem:
+ suffix = ""
+ runs = client.api("GET", suffix, missing_ok=True) if suffix else None
+ records = runs.get("workflow_runs", []) if isinstance(runs, dict) else runs or []
+ if records:
+ latest = records[0]
+ wizard.console.print("Latest pipeline: " + str(latest.get("conclusion") or latest.get("status")))
+ wizard.print_link(latest.get("html_url") or latest.get("web_url"))
+ wizard.console.print(
+ "Configuration alone is not a verified scan. Inspect the demo check, comment and artifact reports."
+ )
+
+
+def demo(wizard, repo, platform="auto", tiers=None, no_input=False):
+ if tiers is not None:
+ validate_tiers(tiers)
+ git.require_clean(repo)
+ platform, origin, name = remote(repo, platform)
+ client = Client(wizard, platform, origin, name)
+ info = client.info()
+ branch = info["default_branch"]
+ scan_path = SCAN if platform == "github" else GL_SCAN
+ scan = client.file(scan_path, branch)
+ if scan is None:
+ raise git.SetupError("Merge the setup PR/MR first. The all-tier scan is not on the default branch yet.")
+ data = yaml.safe_load(scan)
+ try:
+ paths = (
+ data["jobs"]["skills"]["with"]["paths"] if platform == "github" else data["variables"]["SKILL_EVAL_PATHS"]
+ )
+ roots = [git.safe_relative(value.strip()) for value in paths.splitlines() if value.strip()]
+ except (KeyError, TypeError, AttributeError) as exc:
+ raise git.SetupError("The all-tier scan is missing configured skill paths.") from exc
+ if not roots:
+ raise git.SetupError("No skill roots are configured.")
+ reviews = client.reviews(DEMO_BRANCH)
+ if reviews:
+ wizard.console.print("Demo PR/MR already exists.")
+ wizard.print_link(reviews[0].get("html_url") or reviews[0]["web_url"])
+ return
+ # Enumerate the live default branch, avoiding any local branch drift.
+ if platform == "github":
+ tree = client.api("GET", "/git/trees/" + quote(branch, safe="") + "?recursive=1")
+ if tree.get("truncated"):
+ raise git.SetupError("The remote tree is truncated; create a demo skill change manually.")
+ manifests = [i["path"] for i in tree.get("tree", []) if i.get("type") == "blob"]
+ else:
+ manifests = []
+ for page in range(1, 101):
+ items = client.api(
+ "GET",
+ "/repository/tree?" + urlencode({"ref": branch, "recursive": "true", "per_page": 100, "page": page}),
+ )
+ manifests.extend(i["path"] for i in items if i.get("type") == "blob")
+ if len(items) < 100:
+ break
+ else:
+ raise git.SetupError("Remote discovery exceeded its size limit.")
+ candidates = sorted(
+ p
+ for p in manifests
+ if PurePosixPath(p).name == "SKILL.md" and any(r == "." or p.startswith(r + "/") for r in roots)
+ )
+ if not candidates:
+ raise git.SetupError("No tracked skill manifest matches the configured roots.")
+ target = git.safe_relative(candidates[0])
+ content = client.file(target, branch)
+ if content is None:
+ raise git.SetupError("The demonstration manifest is missing.")
+ if not no_input and not click.confirm("Open a small skill-change demo PR/MR?", default=False):
+ wizard.console.print("Cancelled. No changes applied.")
+ return
+ # GitLab commits need update actions for existing files.
+ url = client.create(
+ DEMO_BRANCH,
+ branch,
+ {target: content + "\n<!-- SkillEvaluator onboarding demo: exercise automatic feedback. -->\n"},
+ "Try automatic SkillEvaluator all-tier feedback",
+ "Exercise the configured required Tier 1, advisory Tier 2 and paired Tier 3 evaluation. Inspect the CI checks, updated comment and retained artifact reports. Close this demo without merging.",
+ )
+ wizard.console.print("Demo PR/MR created. Close it when finished; no merge needed.")
+ wizard.print_link(url)
diff --git a/src/skillevaluator/_ci_onboarding_git.py b/src/skillevaluator/_ci_onboarding_git.py
index 7f02bb60..871572c0 100644
--- a/src/skillevaluator/_ci_onboarding_git.py
+++ b/src/skillevaluator/_ci_onboarding_git.py
@@ -7,6 +7,7 @@ import os
import re
import subprocess
from collections import Counter
+from collections.abc import Callable
from pathlib import Path, PurePosixPath
from urllib.parse import urlsplit
@@ -80,6 +81,24 @@ def repository_root(path: Path) -> Path:
return repo
+def parse_origin[T](repo: Path, parse: Callable[[str], T]) -> T:
+ """Parse origin as configured, then as rewritten by Git's url.<base>.insteadOf rules.
+
+ `git remote get-url` applies insteadOf rewrites, so a user-level rule such as
+ https://github.com/ -> ssh://[email protected]/ would hide a supported origin, while
+ an alias origin such as gh:owner/repo only parses after the rewrite.
+ """
+ configured = git(repo, "config", "--get", "remote.origin.url", optional=True).strip()
+ rewritten = git(repo, "remote", "get-url", "origin").strip()
+ first_error: SetupError | None = None
+ for value in dict.fromkeys(v for v in (configured, rewritten) if v):
+ try:
+ return parse(value)
+ except SetupError as exc:
+ first_error = first_error or exc
+ raise first_error or SetupError("The repository has no origin remote.")
+
+
def parse_remote(value: str) -> str:
if value.startswith("[email protected]:"):
name = value.removeprefix("[email protected]:")
diff --git a/src/skillevaluator/ci-release-all-tiers.json b/src/skillevaluator/ci-release-all-tiers.json
new file mode 100644
index 00000000..8be6b3c3
--- /dev/null
+++ b/src/skillevaluator/ci-release-all-tiers.json
@@ -0,0 +1,17 @@
+{
+ "repository": "NVIDIA/SkillEvaluator",
+ "workflow_ref": "472e8becc289a2dc1131e550ebd335c08249918d",
+ "publisher_ref": "8096c6966a498f35f6f7dc1a596d1cc4da85cf11",
+ "image": "ghcr.io/nvidia/skillevaluator-tier1@sha256:a3baec51f48145cdf9de05a5ab054d9576f62f1de0f5276b788410f5c17747d4",
+ "schema_version": 2,
+ "capabilities": [
+ "all-tiers-github",
+ "all-tiers-gitlab"
+ ],
+ "feedback_ref": "472e8becc289a2dc1131e550ebd335c08249918d",
+ "gitlab_ref": "472e8becc289a2dc1131e550ebd335c08249918d",
+ "tools_ref": "472e8becc289a2dc1131e550ebd335c08249918d",
+ "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.py
index b4b98dd3..f5112396 100644
--- a/src/skillevaluator/ci_onboarding.py
+++ b/src/skillevaluator/ci_onboarding.py
@@ -22,6 +22,7 @@ from rich.panel import Panel
from rich.table import Table
from rich.text import Text
+from skillevaluator import _ci_onboarding_all_tiers as all_tier_helpers
from skillevaluator import _ci_onboarding_git as git_helpers
from skillevaluator import _ci_onboarding_pages as pages_helpers
from skillevaluator import _ci_onboarding_workflows as workflow_helpers
@@ -125,6 +126,8 @@ def show_test_pr(name: str, url: str, *, existing: bool = False, full: bool = Tr
def load_release(path: Path) -> dict:
data = json.loads(path.read_text())
+ if isinstance(data, dict) and data.get("schema_version") == 2:
+ return all_tier_helpers.validate_release(data)
if not isinstance(data, dict) or data.get("schema_version") != 1:
raise SetupError("The CI release descriptor must use schema_version 1.")
if data.get("repository") != "NVIDIA/SkillEvaluator":
@@ -843,7 +846,40 @@ def ci():
"""Set up checks, HTML reports and PR comments."""
+ALL_TIER_ONLY_OPTIONS = (
+ "platform",
+ "env_mode",
+ "provider",
+ "embedding_provider",
+ "model",
+ "embedding_model",
+ "agents",
+ "runner",
+ "n_attempts",
+ "n_concurrent",
+ "timeout_minutes",
+ "environment",
+)
+
+
@ci.command("init")
[email protected]("--tiers", default=None, help="Opt in with 1,2,3; requires a compatible candidate/release descriptor.")
[email protected]("--platform", type=click.Choice(["auto", "github", "gitlab"]), default="auto")
[email protected]("--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)
[email protected]("--model", default=None)
[email protected]("--embedding-model", default=None)
[email protected]("--agents", default=None)
[email protected]("--runner", default=None, help="GitHub runner label or GitLab runner tag.")
+ "--tier3-required", is_flag=True, help="Deprecated and ignored; Tier 2 and Tier 3 CI results are advisory."
+)
[email protected]("--n-attempts", type=click.IntRange(1, 10), default=1)
[email protected]("--n-concurrent", type=click.IntRange(1, 16), default=1)
+# Ten minutes keeps a reserve of at least two between the evaluator budget and the job timeout.
[email protected]("--timeout-minutes", type=click.IntRange(10, 360), default=300)
[email protected]("--environment", default="skillevaluator")
@click.option("--repo", type=click.Path(path_type=Path, exists=True, file_okay=False), default=Path.cwd)
@click.option(
"--release",
@@ -870,6 +906,20 @@ def ci():
help="Optional new receipt outside the consumer checkout.",
)
def init(
+ tiers,
+ platform,
+ env_mode,
+ provider,
+ embedding_provider,
+ model,
+ embedding_model,
+ agents,
+ runner,
+ tier3_required,
+ n_attempts,
+ n_concurrent,
+ timeout_minutes,
+ environment,
repo,
release_path,
paths,
@@ -884,7 +934,50 @@ def init(
output,
):
plan = None
+ if tier3_required:
+ console.print(
+ "Warning: --tier3-required is deprecated and ignored; Tier 1 is the only blocking CI tier.",
+ style="yellow",
+ )
try:
+ if tiers is not None:
+ return all_tier_helpers.initialize(
+ sys.modules[__name__],
+ repo=repo,
+ release_path=release_path,
+ paths=paths,
+ min_score=min_score,
+ scan_mode=scan_mode,
+ default_branch=default_branch,
+ full=full,
+ custom_url=custom_url,
+ mode=mode,
+ no_input=no_input,
+ show_files=show_files,
+ output=output,
+ tiers=tiers,
+ platform=platform,
+ env_mode=env_mode,
+ provider=provider,
+ embedding_provider=embedding_provider,
+ model=model,
+ embedding_model=embedding_model,
+ agents=agents,
+ runner=runner,
+ tier3_required=False,
+ n_attempts=n_attempts,
+ n_concurrent=n_concurrent,
+ timeout_minutes=timeout_minutes,
+ environment=environment,
+ )
+ context = click.get_current_context()
+ ignored = [
+ "--" + parameter.replace("_", "-")
+ for parameter in ALL_TIER_ONLY_OPTIONS
+ if context.get_parameter_source(parameter) not in (None, click.core.ParameterSource.DEFAULT)
+ ]
+ if ignored:
+ raise SetupError(f"{', '.join(ignored)} applies only to all-tier onboarding; add --tiers 1,2,3.")
repo = git_helpers.repository_root(repo)
if output:
output = output.resolve()
@@ -893,7 +986,9 @@ def init(
if no_input and mode is None:
raise SetupError("--no-input requires an explicit --mode.")
release = load_release(release_path or Path(__file__).with_name("ci-release.json"))
- name = git_helpers.parse_remote(git_helpers.git(repo, "remote", "get-url", "origin").strip())
+ if release["schema_version"] == 2:
+ raise SetupError("Use --tiers 1,2,3 with an all-tier release descriptor.")
+ name = git_helpers.parse_origin(repo, git_helpers.parse_remote)
branch = git_helpers.infer_branch(repo, default_branch)
roots = git_helpers.discover(repo)
git_helpers.no_symlinks(repo, SCAN)
@@ -1036,7 +1131,7 @@ def init(
if not no_input and not click.confirm("Configure GitHub and open the setup PR?", default=False):
plan["action"] = "cancelled"
console.print("Cancelled. No changes applied.")
- return
+ return None
console.print("Checking GitHub access…")
state = remote_preflight(repo, name, branch, full)
if full:
@@ -1082,12 +1177,16 @@ def init(
@ci.command("status")
[email protected]("--platform", type=click.Choice(["auto", "github", "gitlab"]), default="auto")
[email protected]("--tiers", default=None)
@click.option("--repo", type=click.Path(path_type=Path, exists=True, file_okay=False), default=Path.cwd)
-def status(repo):
+def status(repo, platform, tiers):
"""Read the live setup state without changing settings or starting scans."""
try:
repo = git_helpers.repository_root(repo)
- name = git_helpers.parse_remote(git_helpers.git(repo, "remote", "get-url", "origin").strip())
+ if all_tier_helpers.is_all_tier(repo, platform, tiers):
+ return all_tier_helpers.inspect(sys.modules[__name__], repo, platform, tiers)
+ name = git_helpers.parse_origin(repo, git_helpers.parse_remote)
info = github_api("GET", f"repos/{name}")
branch = info["default_branch"]
pages = github_api("GET", f"repos/{name}/pages", missing_ok=True)
@@ -1126,15 +1225,19 @@ def status(repo):
@ci.command("demo")
[email protected]("--platform", type=click.Choice(["auto", "github", "gitlab"]), default="auto")
[email protected]("--tiers", default=None)
@click.option("--repo", type=click.Path(path_type=Path, exists=True, file_okay=False), default=Path.cwd)
@click.option("--no-input", is_flag=True, help="Authorize opening one small skill-change PR.")
-def demo(repo, no_input):
+def demo(repo, no_input, platform, tiers):
"""After merging setup, open a small skill PR to see automatic feedback."""
try:
console.print("Try your first skill check", style="bold green")
repo = git_helpers.repository_root(repo)
git_helpers.require_clean(repo)
- name = git_helpers.parse_remote(git_helpers.git(repo, "remote", "get-url", "origin").strip())
+ if all_tier_helpers.is_all_tier(repo, platform, tiers):
+ return all_tier_helpers.demo(sys.modules[__name__], repo, platform, tiers, no_input)
+ name = git_helpers.parse_origin(repo, git_helpers.parse_remote)
info = github_api("GET", f"repos/{name}")
permissions = info.get("permissions", {})
if info.get("archived") or not (permissions.get("push") or permissions.get("admin")):
@@ -1163,7 +1266,7 @@ def demo(repo, no_input):
)
if existing:
show_test_pr(name, existing[0]["url"], existing=True, full=full)
- return
+ return None
canonical = f"https://github.com/{name}.git"
if git_helpers.git(repo, "ls-remote", "--heads", canonical, f"refs/heads/{demo_branch}", network=True).strip():
raise SetupError(
@@ -1182,7 +1285,7 @@ def demo(repo, no_input):
)
if not no_input and not click.confirm("Create test PR?", default=False):
console.print("Cancelled. No changes applied.")
- return
+ return None
git_helpers.require_identity(repo)
git_helpers.git(
repo, "fetch", "--no-tags", canonical, f"refs/heads/{branch}:refs/remotes/origin/{branch}", network=True
diff --git a/src/skillevaluator/embedding/registry.py b/src/skillevaluator/embedding/registry.py
index 85d1dd76..ccf2cb11 100644
--- a/src/skillevaluator/embedding/registry.py
+++ b/src/skillevaluator/embedding/registry.py
@@ -222,6 +222,45 @@ class EmbeddingRegistry:
Number of entries successfully indexed.
"""
content_entries = discover_and_extract(root, content_type, max_entries=self._max_entries)
+ return self._build_entries(root, content_entries, minimum_entries, for_pairwise_scan)
+
+ def build_from_paths(self, root: Path, skills: list[Path]) -> int:
+ """Index explicit skills across multiple roots under one trusted checkout.
+
+ Paths retain their checkout-relative identity, avoiding collisions when
+ separate skill roots contain folders with the same name. Validate every
+ input before the first credential-bearing embedding call.
+ """
+ root = root.resolve(strict=True)
+ unique = sorted(set(skills))
+ if not unique or len(unique) > self._max_entries:
+ raise ValueError("Explicit skill collection exceeds its supported entry count")
+ entries = []
+ for path in unique:
+ try:
+ relative = path.absolute().relative_to(root)
+ except ValueError as exc:
+ raise ValueError("An explicit skill is outside the checkout root") from exc
+ current = root
+ for part in relative.parts:
+ current /= part
+ if part == ".." or is_link_or_reparse(current):
+ raise ValueError("Explicit skill paths must not contain links or parent traversal")
+ if not current.resolve(strict=True).is_relative_to(root):
+ raise ValueError("An explicit skill is outside the checkout root")
+ entry = extract_from_skill(current)
+ if entry is None:
+ raise ValueError("Each explicit path must contain a valid SKILL.md")
+ entries.append(entry)
+ return self._build_entries(root, entries, 1, False)
+
+ def _build_entries(
+ self,
+ root: Path,
+ content_entries: list[ContentEntry],
+ minimum_entries: int,
+ for_pairwise_scan: bool,
+ ) -> int:
if not content_entries:
logger.debug("No content entries found in %s", safe_path_label(root))
return 0
diff --git a/src/skillevaluator/reporting/retained.py b/src/skillevaluator/reporting/retained.py
index 0038f86c..37d73510 100644
--- a/src/skillevaluator/reporting/retained.py
+++ b/src/skillevaluator/reporting/retained.py
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
-"""Render retained Tier 1 JSON with trusted templates, without reading skill paths.
+"""Render retained public JSON with trusted templates, without reading skill paths.
The caller must bound the incoming JSON byte size. This adapter additionally
bounds its shape and rejects malformed typed evidence instead of inventing it.
@@ -66,7 +66,7 @@ def _strings(value: Any, field: str) -> list[str]:
def _typed_metadata(metadata: dict) -> None:
- """Validate nested containers dereferenced by the native Tier 1 template."""
+ """Validate nested containers dereferenced by native report templates."""
workflow = metadata.get("workflow")
if workflow is not None:
stages = workflow.get("stages", {})
@@ -110,13 +110,63 @@ def _typed_metadata(metadata: dict) -> None:
and all(isinstance(value, str) for value in policy["severity_overrides"].values()),
"Invalid severity overrides",
)
+ agent_eval = metadata.get("agent_eval")
+ if agent_eval is not None:
+ for key in (
+ "summary",
+ "agents",
+ "dataset_summary",
+ "attempt_policy",
+ "evaluators",
+ "insights",
+ "metric_labels",
+ "verdict_policy",
+ "provenance",
+ ):
+ if key in agent_eval:
+ _require(isinstance(agent_eval[key], dict), f"Invalid tier3.{key}")
+ for key in (
+ "dimensions",
+ "dataset",
+ "trials",
+ "cases",
+ "evaluator_cards",
+ "timing",
+ "agents_run",
+ "execution_errors",
+ "suggestions",
+ "suggestions_v2",
+ "metric_ids",
+ ):
+ if key in agent_eval:
+ _require(isinstance(agent_eval[key], list), f"Invalid tier3.{key}")
+ for key in ("verdict", "execution_status", "skill_name"):
+ if key in agent_eval:
+ _text(agent_eval[key], f"tier3.{key}")
+ for agent in agent_eval.get("agents", {}).values():
+ _require(isinstance(agent, dict), "Invalid tier3 agent")
+ if "conditions" in agent:
+ _require(isinstance(agent["conditions"], dict), "Invalid tier3 agent.conditions")
+ for key in ("with_skill", "without_skill"):
+ if agent.get(key) is not None:
+ _require(type(agent[key]) in (int, float) and 0 <= agent[key] <= 1, f"Invalid tier3 agent.{key}")
+ for record in (agent_eval, agent_eval.get("summary", {})):
+ for key in ("expected_attempts", "scored_attempts"):
+ if key in record:
+ _require(type(record[key]) is int and record[key] >= 0, f"Invalid tier3.{key}")
+ for key in ("overall_score", "overall_lift", "composite_lift"):
+ if record.get(key) is not None:
+ minimum = 0 if key == "overall_score" else -1
+ _require(type(record[key]) in (int, float) and minimum <= record[key] <= 1, f"Invalid tier3.{key}")
benchmark = metadata.get("benchmark_policy")
if benchmark is not None:
_require(all(type(value) is bool for value in benchmark.values()), "Invalid benchmark policy")
-def retained_results(payload: dict, *, copy_metadata: bool = True) -> list[ValidationResult]:
- """Rehydrate the JSONReporter's Tier 1 contract using explicit field maps.
+def retained_results(
+ payload: dict, *, copy_metadata: bool = True, allowed_tiers: set[int] | None = None
+) -> list[ValidationResult]:
+ """Rehydrate the JSONReporter's public contract using explicit field maps.
Results own deep copies of the payload's metadata by default. A caller that
only validates and discards the results can pass copy_metadata=False; the
@@ -139,6 +189,10 @@ def retained_results(payload: dict, *, copy_metadata: bool = True) -> list[Valid
"publication_target": "publication_target",
"publication_evidence": "publication_evidence",
"llm_analysis": "llm_analysis",
+ "work_limit": "work_limit",
+ "tier3": "agent_eval",
+ "skillspector_applicability": "skillspector_applicability",
+ "skillspector_baseline": "skillspector_baseline",
}
for row in rows:
_require(isinstance(row, dict), "Result must be an object")
@@ -231,6 +285,8 @@ def retained_results(payload: dict, *, copy_metadata: bool = True) -> list[Valid
metadata["confirmed_failure"] = row["confirmed_failure"]
if row.get("skip_reason") is not None:
metadata["skip_reason"] = _text(row["skip_reason"], "skip_reason")
+ if "agent_eval" in metadata and payload.get("tier3_applicability") is not None:
+ metadata["tier3_applicability"] = mapping(payload["tier3_applicability"], "tier3_applicability")
_typed_metadata(metadata)
result = ValidationResult(
validator_name=name,
@@ -247,16 +303,17 @@ def retained_results(payload: dict, *, copy_metadata: bool = True) -> list[Valid
not result.passed and result.summary.errors > 0 and bool(result.errors),
"Confirmed failure requires failing diagnostics",
)
+ tier = 3 if is_tier3_result(result) else 2 if is_tier2_result(result) else 1
_require(
- not is_tier2_result(result) and not is_tier3_result(result) and "tier3" not in row,
- "Only retained Tier 1 reports are supported",
+ allowed_tiers is None or tier in allowed_tiers,
+ "Only retained Tier 1 reports are supported" if allowed_tiers == {1} else "Result tier is not allowed",
)
if "gating" in metadata:
_require(
type(metadata["gating"].get("tier")) is int
- and metadata["gating"]["tier"] == 1
+ and metadata["gating"]["tier"] == tier
and type(metadata["gating"].get("blocking")) is bool,
- "Invalid Tier 1 gating",
+ f"Invalid Tier {tier} gating",
)
if "quality_scores" in metadata:
quality = metadata["quality_scores"]
@@ -271,6 +328,15 @@ def retained_results(payload: dict, *, copy_metadata: bool = True) -> list[Valid
if expected_status == "skipped"
else result.passed == (expected_status == "passed")
)
+ if tier == 3 and result.passed:
+ # Native Tier 3's boolean records completed execution; quality can
+ # still fail or be inconclusive after both arms produced scores.
+ agent = metadata.get("agent_eval") or {}
+ quality_verdict = agent.get("verdict") or (agent.get("summary") or {}).get("verdict")
+ verdict_consistent = verdict_consistent or (
+ agent.get("execution_status") == "succeeded"
+ and (expected_status, quality_verdict) in {("failed", "fail"), ("incomplete", "inconclusive")}
+ )
_require(verdict_consistent, "Result verdict contradicts evidence")
results.append(result)
if "overall_passed" in payload:
diff --git a/src/skillevaluator/tier3/harbor/adapter.py b/src/skillevaluator/tier3/harbor/adapter.py
index aab8e5aa..61d170ac 100644
--- a/src/skillevaluator/tier3/harbor/adapter.py
+++ b/src/skillevaluator/tier3/harbor/adapter.py
@@ -74,6 +74,10 @@ TEMPLATES_DIR = Path(__file__).parent / "templates"
_EVAL_CORE_DIR = Path(__file__).resolve().parent.parent / "eval_core"
_EVALUATOR_TESTS_SUBDIR = "skill_evaluator"
_BASE_IMAGE_PREFIX = "skillevaluator-base"
+# Compose 2 treats HEALTHCHECK NONE as a configured check, then fails its
+# readiness wait because Docker supplies no health state. Replace authored
+# checks with this constant exec-form probe; do not run authored healthcheck commands.
+_MAIN_CONTAINER_READINESS_HEALTHCHECK = 'HEALTHCHECK --interval=1s --timeout=5s --retries=3 CMD ["/bin/true"]'
_MAX_REPO_CONTEXT_FILE_BYTES = 10 * 1024 * 1024
_MAX_REPO_CONTEXT_TOTAL_BYTES = 200 * 1024 * 1024
_MAX_EVALUATOR_FILE_BYTES = 64 * 1024 * 1024
@@ -3861,6 +3865,7 @@ def _append_task_input_projection(
_RUNTIME_POLICY_ENV_RESET,
"ENTRYPOINT []",
"HEALTHCHECK NONE",
+ _MAIN_CONTAINER_READINESS_HEALTHCHECK,
]
)
if restore_user is not None and restore_user.casefold() != "root":
@@ -3890,6 +3895,7 @@ def _extend_task_input_projection(lines: list[str], *, include_input: bool, agen
_RUNTIME_POLICY_ENV_RESET,
"ENTRYPOINT []",
"HEALTHCHECK NONE",
+ _MAIN_CONTAINER_READINESS_HEALTHCHECK,
]
)
diff --git a/src/skillevaluator/tier3/harbor/runner.py b/src/skillevaluator/tier3/harbor/runner.py
index d8c081f1..e6528546 100644
--- a/src/skillevaluator/tier3/harbor/runner.py
+++ b/src/skillevaluator/tier3/harbor/runner.py
@@ -1362,6 +1362,9 @@ _HARBOR_LAUNCH_ENV = MappingProxyType({"HARBOR_TELEMETRY": "0", "PYTHON_DOTENV_D
# wrappers check a minimum version for the selected model.
_CODEX_VERSION = PINNED_RUNTIME_VERSIONS["codex"]
_CLAUDE_CODE_VERSION = PINNED_RUNTIME_VERSIONS["claude-code"]
+# Harbor would otherwise install ``opencode-ai@latest``. CI's managed local
+# bootstrap installs this same release, so every CI mode shares one pin.
+OPENCODE_VERSION = "1.19.5"
# Harbor 0.22's Codex agent ran with ``model_reasoning_effort=high``; later
# releases defer to Codex's own default. Pin the effort SkillEvaluator was
# validated with so scores and cost stay comparable across Harbor upgrades.
@@ -1369,6 +1372,7 @@ _HARBOR_AGENT_KWARGS: Mapping[str, Mapping[str, str]] = MappingProxyType(
{
"codex": MappingProxyType({"reasoning_effort": "high", "version": _CODEX_VERSION}),
"claude-code": MappingProxyType({"version": _CLAUDE_CODE_VERSION}),
+ "opencode": MappingProxyType({"version": OPENCODE_VERSION}),
}
)
# Claude Code's default effort depends on the model, and Claude Opus 5 ran at
diff --git a/tests/ci/test_all_tier_preflight.py b/tests/ci/test_all_tier_preflight.py
new file mode 100644
index 00000000..9c1d8d85
--- /dev/null
+++ b/tests/ci/test_all_tier_preflight.py
@@ -0,0 +1,217 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Exercise native bootstrap and GitLab admission without paid execution."""
+
+import importlib.util
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).parents[2]
+
+
+def module(name):
+ spec = importlib.util.spec_from_file_location(name, ROOT / "ci" / f"{name}.py")
+ result = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(result)
+ return result
+
+
+def test_docker_bootstrap_uses_selected_mode_without_host_agent_install(monkeypatch):
+ bootstrap = module("bootstrap_tiers")
+ calls = []
+ monkeypatch.setenv("SKILL_EVAL_ENV_MODE", "docker")
+ monkeypatch.setenv("SKILL_EVAL_PROVIDER", "openai")
+ monkeypatch.setenv("SKILL_EVAL_AGENTS", "codex")
+ monkeypatch.setattr(
+ bootstrap.subprocess, "run", lambda args, **_kwargs: calls.append(args) or subprocess.CompletedProcess(args, 0)
+ )
+ assert bootstrap.main() == 0
+ assert calls == [
+ [sys.executable, "-I", "-m", "skillevaluator.cli", "doctor", "--env-mode", "docker", "--agents", "codex"]
+ ]
+
+
+def test_bootstrap_rejects_cloud_before_install(monkeypatch):
+ bootstrap = module("bootstrap_tiers")
+ monkeypatch.setenv("SKILL_EVAL_ENV_MODE", "gke")
+ monkeypatch.setattr(
+ bootstrap.subprocess, "run", lambda *_args, **_kwargs: pytest.fail("cloud mode must not install or run")
+ )
+ assert bootstrap.main() == 2
+
+
+def test_local_bootstrap_installs_only_the_selected_native_runtime(monkeypatch):
+ bootstrap = module("bootstrap_tiers")
+ calls = []
+ monkeypatch.setenv("SKILL_EVAL_ENV_MODE", "local")
+ monkeypatch.setenv("SKILL_EVAL_PROVIDER", "anthropic")
+ monkeypatch.delenv("SKILL_EVAL_AGENTS", raising=False)
+ monkeypatch.setattr(bootstrap, "install_agent", calls.append)
+ monkeypatch.setattr(
+ bootstrap.subprocess, "run", lambda args, **_kwargs: calls.append(args) or subprocess.CompletedProcess(args, 0)
+ )
+ assert bootstrap.main() == 0
+ assert calls == [
+ "claude-code",
+ [sys.executable, "-I", "-m", "skillevaluator.cli", "doctor", "--env-mode", "local", "--agents", "claude-code"],
+ ]
+
+
+def test_local_bootstrap_installs_the_opencode_release_docker_runs_pin(monkeypatch):
+ from skillevaluator.tier3.harbor import runner
+
+ bootstrap = module("bootstrap_tiers")
+ calls = []
+ monkeypatch.setattr(
+ bootstrap.subprocess, "run", lambda args, **_kwargs: calls.append(args) or subprocess.CompletedProcess(args, 0)
+ )
+ bootstrap.install_agent("opencode")
+ assert calls[0][-1] == f"opencode-ai@{runner.OPENCODE_VERSION}"
+ assert runner._harbor_agent_kwargs("opencode", None, "docker") == {"version": runner.OPENCODE_VERSION}
+
+
+def test_gitlab_admission_rejects_forks_and_stale_heads():
+ gate = module("eligible_gitlab")
+ env = {
+ "CI_PROJECT_ID": "42",
+ "CI_COMMIT_SHA": "a" * 40,
+ "CI_PIPELINE_SOURCE": "merge_request_event",
+ "CI_MERGE_REQUEST_IID": "1",
+ "CI_MERGE_REQUEST_SOURCE_PROJECT_ID": "42",
+ }
+ current = {"source_project_id": 42, "target_project_id": 42, "state": "opened", "sha": "a" * 40}
+ assert gate.eligible(env, current)
+ assert not gate.eligible(env, {**current, "sha": "b" * 40})
+ assert not gate.eligible(env, {**current, "source_project_id": 43})
+ assert not gate.eligible(env, {**current, "state": "closed"})
+
+
+def test_gitlab_admission_allows_only_protected_default_branch_without_mr():
+ gate = module("eligible_gitlab")
+ env = {
+ "CI_PIPELINE_SOURCE": "web",
+ "CI_COMMIT_BRANCH": "main",
+ "CI_DEFAULT_BRANCH": "main",
+ "CI_COMMIT_REF_PROTECTED": "true",
+ }
+ assert gate.eligible(env, None)
+ assert not gate.eligible({**env, "CI_COMMIT_REF_PROTECTED": "false"}, None)
+
+
+def test_actual_workflow_bootstrap_ignores_consumer_pythonpath(tmp_path):
+ import os
+ import shlex
+
+ import yaml
+
+ package = tmp_path / "skillevaluator"
+ package.mkdir()
+ marker = tmp_path / "consumer-imported"
+ (package / "__init__.py").write_text(
+ f"from pathlib import Path\nPath({str(marker)!r}).write_text('imported')\nraise SystemExit(91)\n"
+ )
+ environment = {
+ "PATH": os.environ.get("PATH", ""),
+ "PYTHONPATH": str(tmp_path),
+ "SKILL_EVAL_ENV_MODE": "gke",
+ }
+ workflow = yaml.load((ROOT / ".github/workflows/evaluate-all-tiers.yml").read_text(), Loader=yaml.BaseLoader)
+ step = next(s for s in workflow["jobs"]["paid-tiers"]["steps"] if s.get("name", "").startswith("Bootstrap native"))
+ argv = shlex.split(step["run"])
+ argv[0] = sys.executable
+ argv[-1] = str(ROOT / argv[-1].removeprefix("evaluator/"))
+ # Establish that this consumer package exploits the old unisolated command.
+ vulnerable = [arg for arg in argv if arg != "-I"]
+ before = subprocess.run(vulnerable, cwd=tmp_path, env=environment, capture_output=True, text=True, timeout=30)
+ assert before.returncode == 91
+ assert marker.is_file()
+ marker.unlink()
+ after = subprocess.run(argv, cwd=tmp_path, env=environment, capture_output=True, text=True, timeout=30)
+ assert after.returncode == 2 # Unsupported mode is handled by trusted code.
+ assert "supports docker and local" in after.stdout
+ assert not marker.exists()
+
+
+def test_bootstrap_doctor_receives_the_configured_ci_provider_and_model(monkeypatch):
+ bootstrap = module("bootstrap_tiers")
+ calls = []
+ monkeypatch.setenv("SKILL_EVAL_ENV_MODE", "docker")
+ monkeypatch.setenv("SKILL_EVAL_PROVIDER", "nv_build")
+ monkeypatch.setenv("SKILL_EVAL_MODEL", "nvidia/example-model")
+
+ def capture(args, **kwargs):
+ calls.append(kwargs)
+ return subprocess.CompletedProcess(args, 0)
+
+ monkeypatch.setattr(bootstrap.subprocess, "run", capture)
+ assert bootstrap.main() == 0
+ assert calls[0]["env"]["SKILL_EVAL_LLM_PROVIDER"] == "nv_build"
+ assert calls[0]["env"]["SKILL_EVAL_LLM_MODEL"] == "nvidia/example-model"
+ assert calls[0]["env"]["PYTHON_DOTENV_DISABLED"] == "1"
+
+
+def test_failed_docker_doctor_prevents_native_provider_execution(tmp_path, monkeypatch):
+ import json
+ import os
+
+ from ci import run_tiers
+
+ workspace = tmp_path / "candidate"
+ skill = workspace / "skills/example"
+ skill.mkdir(parents=True)
+ (skill / "SKILL.md").write_text("---\nname: example\ndescription: Use for test examples.\n---\nInstructions.\n")
+ subprocess.run(["git", "init", "-b", "main", str(workspace)], check=True, capture_output=True)
+ git = ["git", "-C", str(workspace), "-c", "user.name=CI tests", "-c", "[email protected]"]
+ subprocess.run([*git, "add", "."], check=True)
+ subprocess.run([*git, "commit", "-m", "fixture"], check=True, capture_output=True)
+ commit = subprocess.check_output([*git, "rev-parse", "HEAD"], text=True).strip()
+ commands = []
+
+ def unavailable_doctor(args, **_kwargs):
+ commands.append(args)
+ assert "doctor" in args, "No provider or native evaluation may run after failed Docker readiness"
+ return 1
+
+ monkeypatch.setattr(run_tiers, "dataset_preflight", lambda _skill: {})
+ monkeypatch.setattr(run_tiers, "run_command", unavailable_doctor)
+ reports = tmp_path / "reports"
+ code = run_tiers.evaluate(
+ 3,
+ workspace,
+ reports,
+ {
+ "PATH": os.environ["PATH"],
+ "SKILL_EVAL_PATHS": "skills",
+ "SKILL_EVAL_ENV_MODE": "docker",
+ "SKILL_EVAL_PROVIDER": "nv_build",
+ "NVIDIA_API_KEY": "test-key-value-123456789",
+ "REPORT_COMMIT": commit,
+ "REPORT_REPOSITORY": "example/consumer",
+ "GITHUB_ACTIONS": "true",
+ "GITHUB_RUN_ID": "123",
+ "GITHUB_RUN_ATTEMPT": "1",
+ },
+ )
+ assert code == 0 # Advisory failures retain evidence, while spending no provider calls.
+ assert len(commands) == 1
+ assert commands[0][commands[0].index("--env-mode") + 1] == "docker"
+ result = json.loads((reports / "tier3/ci-tier.json").read_text())
+ assert result["tiers"][0]["status"] == "incomplete"
+
+
+def test_provider_child_excludes_both_gitlab_read_and_feedback_credentials():
+ from ci import run_tiers
+
+ child = run_tiers.child_environment(
+ {
+ "SKILL_EVAL_PROVIDER": "nv_build",
+ "SKILLEVALUATOR_GITLAB_READ_TOKEN": "read-only-test-token",
+ "SKILLEVALUATOR_GITLAB_TOKEN": "feedback-test-token",
+ "CI_JOB_TOKEN": "job-test-token",
+ }
+ )
+ assert not any(
+ key in child for key in ("SKILLEVALUATOR_GITLAB_READ_TOKEN", "SKILLEVALUATOR_GITLAB_TOKEN", "CI_JOB_TOKEN")
+ )
diff --git a/tests/ci/test_all_tier_workflows.py b/tests/ci/test_all_tier_workflows.py
new file mode 100644
index 00000000..2bf43819
--- /dev/null
+++ b/tests/ci/test_all_tier_workflows.py
@@ -0,0 +1,566 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Validate the security boundaries of the opt-in three-tier pipeline."""
+
+from pathlib import Path
+
+import yaml
+
+ROOT = Path(__file__).parents[2]
+
+
+def load(path):
+ return list(yaml.load_all((ROOT / path).read_text(), Loader=yaml.BaseLoader))[-1]
+
+
+def test_required_tier1_reuses_hardened_workflow_and_parallel_paid_tiers():
+ workflow = load(".github/workflows/evaluate-all-tiers.yml")
+ inputs = workflow["on"]["workflow_call"]["inputs"]
+ assert inputs["env-mode"]["default"] == "docker"
+ assert inputs["tier3-required"]["default"] == "false"
+ assert workflow["jobs"]["tier1"]["uses"] == "./.github/workflows/evaluate-skills.yml"
+ paid = workflow["jobs"]["paid-tiers"]
+ assert paid["strategy"]["fail-fast"] == "false"
+ assert paid["strategy"]["matrix"]["tier"] == ["2", "3"]
+ assert paid["environment"] == "${{ inputs.environment }}"
+ assert "eligibility" in paid["needs"]
+ assert "needs.eligibility.outputs.allowed" in paid["if"]
+ checkouts = [s for s in paid["steps"] if s.get("uses", "").startswith("actions/checkout@")]
+ assert {s["with"]["path"] for s in checkouts} == {"candidate", "evaluator"}
+ tools = next(s for s in checkouts if s["with"]["path"] == "evaluator")
+ assert tools["with"]["ref"] == "${{ inputs.tools-ref }}"
+ assert tools["with"]["persist-credentials"] == "false"
+ assert all("secrets." not in str(s) for s in workflow["jobs"]["eligibility"]["steps"])
+
+
+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"}
+ 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"
+ upload = next(s for s in aggregate["steps"] if s.get("uses", "").startswith("actions/upload-artifact@"))
+ assert upload["if"] == "${{ always() }}"
+ assert upload["with"]["retention-days"] == "14"
+ assert upload["with"]["name"] == "skill-evaluator-results-attempt-${{ github.run_attempt }}"
+
+
+def test_aggregate_reuses_tier_evidence_from_jobs_not_rerun():
+ import fnmatch
+
+ workflow = load(".github/workflows/evaluate-all-tiers.yml")
+ steps = workflow["jobs"]["aggregate"]["steps"]
+ download = next(s for s in steps if s.get("uses", "").startswith("actions/download-artifact@"))
+ # "Re-run failed jobs" leaves passing tier jobs' artifacts under their own earlier attempt.
+ assert "github.run_attempt" not in str(download["with"])
+ assert "name" not in download["with"]
+ assert download["with"].get("merge-multiple", "false") == "false"
+ 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"])
+ for s in tier1
+ if s.get("uses", "").startswith("actions/upload-artifact@")
+ ]
+ produced += [
+ s["with"]["name"].replace("${{ matrix.tier }}", tier)
+ for s in workflow["jobs"]["paid-tiers"]["steps"]
+ if s.get("uses", "").startswith("actions/upload-artifact@")
+ for tier in workflow["jobs"]["paid-tiers"]["strategy"]["matrix"]["tier"]
+ ]
+ produced += [s["with"]["name"] for s in steps if s.get("uses", "").startswith("actions/upload-artifact@")]
+ for attempt in ("1", "2", "12"):
+ names = [name.replace("${{ github.run_attempt }}", attempt) for name in produced]
+ matched = sorted(name for name in names if fnmatch.fnmatchcase(name, pattern))
+ assert matched == [f"skill-evaluator-tier{tier}-attempt-{attempt}" for tier in (1, 2, 3)]
+ run = [s.get("run", "") for s in steps]
+ select = next(i for i, script in enumerate(run) if "run_tiers.py select-attempts" in script)
+ assert (
+ steps.index(download) < select < next(i for i, script in enumerate(run) if "run_tiers.py aggregate" in script)
+ )
+ assert '--artifacts "$RUNNER_TEMP/skill-artifacts" --reports "$RUNNER_TEMP/skill-reports"' in run[select]
+ assert "continue-on-error" not in steps[select]
+
+
+def test_paid_tier_evaluation_stops_before_the_job_timeout():
+ import subprocess
+
+ paid = load(".github/workflows/evaluate-all-tiers.yml")["jobs"]["paid-tiers"]
+ assert paid["timeout-minutes"] == "${{ inputs.timeout-minutes }}"
+ assert paid["env"]["SKILL_EVAL_TIMEOUT_MINUTES"] == "${{ inputs.timeout-minutes }}"
+ step = next(s for s in paid["steps"] if s.get("name") == "Evaluate selected tier and retain native evidence")
+ setup = step["run"].split("python -I", 1)[0]
+ for minutes, expected in ((300, 280), (60, 45), (10, 8), (1, 1)):
+ result = subprocess.run(
+ ["bash", "-eo", "pipefail", "-c", setup + 'printf %s "$SKILL_EVAL_TIMEOUT_SECONDS"'],
+ env={"PATH": "/usr/bin:/bin", "SKILL_EVAL_TIMEOUT_MINUTES": str(minutes)},
+ capture_output=True,
+ text=True,
+ check=True,
+ )
+ assert int(result.stdout) == expected * 60
+
+
+def test_paid_tiers_leave_the_embedding_default_to_the_runner():
+ paid = load(".github/workflows/evaluate-all-tiers.yml")["jobs"]["paid-tiers"]
+ # An Anthropic chat provider defaults to OpenAI embeddings inside run_tiers.
+ assert paid["env"]["SKILL_EVAL_EMBEDDING_PROVIDER"] == "${{ inputs.embedding-provider }}"
+
+
+def test_feedback_checks_out_only_pinned_tools_and_uses_scoped_token():
+ workflow = load(".github/workflows/feedback-all-tiers.yml")
+ job = workflow["jobs"]["feedback"]
+ assert job["permissions"]["pull-requests"] == "write"
+ checkouts = [s for s in job["steps"] if s.get("uses", "").startswith("actions/checkout@")]
+ assert len(checkouts) == 1
+ assert checkouts[0]["with"]["ref"] == "${{ inputs.tools-ref }}"
+ assert "pull_request.head" not in str(checkouts)
+ assert any("ci/feedback.py" in s.get("run", "") for s in job["steps"])
+
+
+def test_gitlab_feedback_token_is_confined_to_trusted_default_branch_job():
+ evaluation = load("ci/gitlab/all-tiers.yml")
+ assert "SKILLEVALUATOR_GITLAB_TOKEN" not in str(evaluation)
+ paid = evaluation["skill-evaluation-native"]
+ assert paid["parallel"]["matrix"] == [{"SKILL_EVAL_TIER": ["2", "3"]}]
+ assert paid["environment"]["name"] == "$SKILL_EVAL_ENVIRONMENT"
+ assert evaluation["skill-evaluation-aggregate"]["when"] == "always"
+ feedback = load("ci/gitlab/feedback.yml")["skill-evaluation-feedback"]
+ assert all("CI_DEFAULT_BRANCH" in r["if"] and "SKILL_EVAL_FEEDBACK" in r["if"] for r in feedback["rules"])
+ assert "SKILLEVALUATOR_GITLAB_TOKEN" in str(feedback)
+
+
+def test_gitlab_tier1_runs_only_digest_pinned_legacy_image():
+ job = load("ci/gitlab/all-tiers.yml")["skill-evaluation"]
+ assert job["image"]["name"] == "$SKILL_EVAL_IMAGE"
+ assert job["image"]["entrypoint"] == [""]
+ assert "/opt/skillevaluator/ci/run_tier1.py" in str(job["script"])
+ assert "python -m pip install" not in str(job["script"])
+
+
+def test_both_paid_tiers_are_advisory_even_for_legacy_required_callers():
+ workflow = load(".github/workflows/evaluate-all-tiers.yml")
+ legacy = workflow["on"]["workflow_call"]["inputs"]["tier3-required"]
+ assert legacy["type"] == "boolean"
+ assert legacy["default"] == "false"
+ assert "deprecated" in legacy["description"].lower()
+ for name in ("paid-tiers", "aggregate"):
+ job = workflow["jobs"][name]
+ assert job["env"]["SKILL_EVAL_TIER3_REQUIRED"] == "false"
+ assert "inputs.tier3-required" not in str(job)
+ assert workflow["jobs"]["paid-tiers"]["continue-on-error"] == "true"
+
+
+def test_new_candidate_callers_do_not_expose_a_paid_tier_requirement():
+ github = load("ci/templates/all-tiers/skill-checks-all-tiers.yml")
+ assert "tier3-required" not in github["jobs"]["skills"]["with"]
+ for path in ("ci/templates/all-tiers/gitlab-all-tiers.yml", "ci/gitlab/all-tiers.yml"):
+ assert "SKILL_EVAL_TIER3_REQUIRED" not in load(path)["variables"]
+
+
+def test_trusted_aggregate_receipt_is_captured_before_untrusted_artifact_read():
+ job = load(".github/workflows/evaluate-all-tiers.yml")["jobs"]["aggregate"]
+ assert job["permissions"]["id-token"] == "write"
+ first = job["steps"][0]
+ assert first["id"] == "provenance"
+ assert "ACTIONS_ID_TOKEN_REQUEST_URL" in first["run"]
+ assert "skill-evaluator-results-provenance-attempt-" in str(job["steps"])
+
+
+def test_setup_configuration_changes_force_a_real_tier1_scan():
+ jobs = load(".github/workflows/evaluate-all-tiers.yml")["jobs"]
+ assert jobs["tier1"]["needs"] == "eligibility"
+ assert "needs.eligibility.outputs.scan-mode" in jobs["tier1"]["with"]["scan-mode"]
+ gate = str(jobs["eligibility"]["steps"])
+ assert "/files?per_page=100&page=" in gate
+ assert ".github/" in gate and ".gitlab-ci.yml" in gate
+ gitlab = str(load("ci/gitlab/all-tiers.yml")["skill-evaluation"]["script"])
+ assert "from select_changed_skills import _git" in gitlab and 'print("all" if setup else "changed")' in gitlab
+
+
+def test_gitlab_native_reports_are_outside_candidate_until_evaluation_completes():
+ script = str(load("ci/gitlab/all-tiers.yml")["skill-evaluation-native"]["script"])
+ assert "mktemp -d /tmp/skillevaluator-reports." in script
+ assert '--reports "$reports_dir"' in script
+ assert 'cp -R "$reports_dir/."' in script
+
+
+def test_github_head_is_rechecked_after_environment_approval_before_provider_secrets():
+ steps = load(".github/workflows/evaluate-all-tiers.yml")["jobs"]["paid-tiers"]["steps"]
+ check = next(s for s in steps if s.get("name") == "Recheck current head after environment approval")
+ assert "secrets." not in str(check)
+ assert "current.get('head', {}).get('sha')" in check["run"]
+ assert "pulls/" in check["run"]
+ first_secret = next(i for i, s in enumerate(steps) if "secrets." in str(s))
+ assert steps.index(check) < first_secret
+
+
+def test_provider_steps_cannot_run_when_post_approval_head_check_failed():
+ steps = load(".github/workflows/evaluate-all-tiers.yml")["jobs"]["paid-tiers"]["steps"]
+ for step in steps:
+ if "secrets." in str(step):
+ assert "steps.current-head.outputs.allowed == 'true'" in step["if"]
+
+
+def test_candidate_templates_do_not_change_legacy_bundle_generation():
+ candidates = ROOT / "ci/templates/all-tiers"
+ assert (candidates / "skill-checks-all-tiers.yml").is_file()
+ assert not list((ROOT / "ci/templates").glob("*all-tiers.yml"))
+
+
+def test_gitlab_privileged_bootstrap_uses_fixed_include_inputs():
+ source = (ROOT / "ci/gitlab/feedback.yml").read_text()
+ header = next(yaml.load_all(source, Loader=yaml.BaseLoader))
+ assert set(header["spec"]["inputs"]) == {"tools-ref", "tools-repository", "api-url", "project-id"}
+ job = load("ci/gitlab/feedback.yml")["skill-evaluation-feedback"]
+ script = str(job["script"])
+ assert "$SKILL_EVAL_TOOLS_REF" not in script
+ assert "$SKILL_EVAL_TOOLS_REPOSITORY" not in script
+ assert "$CI_API_V4_URL" not in script
+ assert "$[[ inputs.tools-ref ]]" in script
+ assert job["id_tokens"]["SKILL_EVAL_GITLAB_ID_TOKEN"]["aud"] == "urn:skillevaluator:feedback:v1"
+
+
+def test_gitlab_feedback_request_uses_job_token_api_without_candidate_checkout():
+ job = load("ci/gitlab/all-tiers.yml")["skill-evaluation-request-feedback"]
+ assert "trigger" not in job
+ assert "environment" not in job
+ assert job["variables"] == {"GIT_STRATEGY": "none"}
+ assert job["extends"] == ".skill-evaluation-tools"
+ assert job["needs"] == [{"job": "skill-evaluation-aggregate", "artifacts": "false"}]
+ assert job["when"] == "always"
+ assert job["allow_failure"] == "true"
+ script = "\n".join(job["script"])
+ assert 'python -I "$SKILL_EVAL_TOOLS_DIR/ci/request_gitlab_feedback.py"' in script
+ assert "uv" not in script and "bootstrap" not in script
+
+
+def test_gitlab_bridge_rules_do_not_disable_their_own_feedback_flag():
+ bridge = load("ci/gitlab/all-tiers.yml")["skill-evaluation-request-feedback"]
+ assert all("SKILL_EVAL_FEEDBACK" not in rule["if"] for rule in bridge["rules"])
+
+
+def test_gitlab_feedback_bootstrap_isolates_process_configuration():
+ script = "\n".join(load("ci/gitlab/feedback.yml")["skill-evaluation-feedback"]["script"])
+ assert "export PATH=/usr/local/bin:/usr/bin:/bin" in script
+ assert "GIT_CONFIG_COUNT" in script and "GIT_EXEC_PATH" in script
+ assert "python -I -m pip --isolated install" in script
+ assert "env -i" in script
+
+
+def test_gitlab_aggregate_enforces_required_gates_for_all_matrix_outcomes():
+ jobs = load("ci/gitlab/all-tiers.yml")
+ assert jobs["skill-evaluation-native"]["allow_failure"] == "true"
+ assert jobs["skill-evaluation-aggregate"].get("allow_failure", "false") == "false"
+ assert jobs["skill-evaluation-aggregate"]["when"] == "always"
+
+
+def test_trusted_native_workflow_entrypoints_and_pip_ignore_consumer_import_paths():
+ for file in (
+ ".github/workflows/evaluate-all-tiers.yml",
+ ".github/workflows/feedback-all-tiers.yml",
+ "ci/gitlab/all-tiers.yml",
+ ):
+ document = load(file)
+ jobs = document.get("jobs", document)
+ for job in jobs.values():
+ if not isinstance(job, dict):
+ continue
+ scripts = job.get("script", []) + [step["run"] for step in job.get("steps", []) if "run" in step]
+ for script in scripts:
+ for line in script.splitlines():
+ if "python " in line and "/opt/skillevaluator/ci/run_tier1.py" not in line:
+ assert "python -I " in line, (file, line)
+ if "-m pip" in line:
+ assert "-m pip --isolated install" in line, (file, line)
+
+
+def test_candidate_caller_propagates_reusable_read_permissions():
+ candidate = load("ci/templates/all-tiers/skill-checks-all-tiers.yml")
+ assert candidate["permissions"]["actions"] == "read"
+ assert candidate["permissions"]["pull-requests"] == "read"
+
+
+def test_all_tier_runtimes_sync_the_reviewed_lock_with_pinned_uv():
+ evaluation = load(".github/workflows/evaluate-all-tiers.yml")
+ paid_install = next(
+ s for s in evaluation["jobs"]["paid-tiers"]["steps"] if s.get("name", "").startswith("Install only")
+ )["run"]
+ assert "uv==0.11.27" in paid_install
+ assert "sync --locked --no-dev" in paid_install
+ assert '--extra "tier${TIER}"' in paid_install
+ assert 'evaluator/.venv/bin" >> "$GITHUB_PATH"' in paid_install
+ aggregate = "\n".join(s["run"] for s in evaluation["jobs"]["aggregate"]["steps"] if "run" in s)
+ assert "sync --locked --no-dev" in aggregate
+ assert "--default-index https://pypi.org/simple" in aggregate
+ feedback = "\n".join(
+ s["run"] for s in load(".github/workflows/feedback-all-tiers.yml")["jobs"]["feedback"]["steps"] if "run" in s
+ )
+ assert "--extra publisher" in feedback
+ for name in ("skill-evaluation-native", "skill-evaluation-aggregate"):
+ script = "\n".join(load("ci/gitlab/all-tiers.yml")[name]["script"])
+ assert "uv==0.11.27" in script
+ assert "sync --locked --no-dev" in script
+ assert '--project "$SKILL_EVAL_TOOLS_DIR"' in script
+ assert 'export PATH="$SKILL_EVAL_TOOLS_DIR/.venv/bin:$PATH"' in script
+ privileged = "\n".join(load("ci/gitlab/feedback.yml")["skill-evaluation-feedback"]["script"])
+ assert "env -i" in privileged and "--no-config" in privileged
+ assert "sync --locked --no-dev --extra publisher" in privileged
+ assert '"$tools_dir/.venv/bin/python" -I - ' in privileged
+
+
+def test_github_native_and_aggregate_record_the_exact_tools_revision():
+ jobs = load(".github/workflows/evaluate-all-tiers.yml")["jobs"]
+ for name in ("paid-tiers", "aggregate"):
+ assert jobs[name]["env"]["SKILLEVALUATOR_TOOLS_REF"] == "${{ inputs.tools-ref }}"
+
+
+def test_feedback_mutation_jobs_are_serialized_per_pr_source_without_dropping_pending_runs():
+ import re
+
+ github = load(".github/workflows/feedback-all-tiers.yml")["jobs"]["feedback"]
+ concurrency = github["concurrency"]
+ # The default `queue: single` cancels an already pending run whenever another joins the group.
+ assert concurrency["cancel-in-progress"] == "false"
+ assert concurrency["queue"] == "max"
+ assert set(concurrency) == {"group", "cancel-in-progress", "queue"}
+ assert "github.event.workflow_run.head_repository.full_name == github.repository" in github["if"]
+
+ def rendered(repository, head_repository, head_branch, run_id, head_sha):
+ # Unknown expressions raise KeyError; `workflow_run.pull_requests` is empty for fork PRs.
+ event = {
+ "github.repository": repository,
+ "github.event.workflow_run.head_repository.full_name": head_repository,
+ "github.event.workflow_run.head_branch": head_branch,
+ "github.event.workflow_run.id": run_id,
+ "github.event.workflow_run.head_sha": head_sha,
+ }
+ return re.sub(r"\$\{\{ ([^}]+) \}\}", lambda match: event[match.group(1)], concurrency["group"])
+
+ first = rendered("acme/skills", "acme/skills", "feature-a", "101", "a" * 40)
+ # Later producer runs for the same PR source serialize behind the comment update in progress.
+ assert rendered("acme/skills", "acme/skills", "feature-a", "102", "b" * 40) == first
+ # Other PRs, repositories and head repositories never compete for one pending slot.
+ assert rendered("acme/skills", "acme/skills", "feature-b", "103", "c" * 40) != first
+ assert rendered("acme/other", "acme/other", "feature-a", "104", "a" * 40) != first
+ assert rendered("acme/skills", "fork/skills", "feature-a", "105", "a" * 40) != first
+ assert load("ci/gitlab/feedback.yml")["skill-evaluation-feedback"]["resource_group"] == "skillevaluator-feedback"
+
+
+def test_gitlab_dind_bootstrap_installs_client_compose_and_buildx_without_a_second_daemon():
+ script = "\n".join(load("ci/gitlab/all-tiers.yml")["skill-evaluation-native"]["script"])
+ assert "apt-get install -y --no-install-recommends docker-cli docker-compose docker-buildx" in script
+ assert "--no-install-recommends docker.io" not in script
+ assert "docker compose version" in script
+ assert "docker buildx version" in script
+ assert script.index("bootstrap_tiers.py") < script.index('run_tiers.py" evaluate')
+
+
+def test_gitlab_shared_native_timeout_is_a_literal_duration():
+ config = load("ci/gitlab/all-tiers.yml")
+ assert config["skill-evaluation-native"]["timeout"] == "5 hours"
+ assert "SKILL_EVAL_JOB_TIMEOUT" not in config["variables"]
+ candidate = load("ci/templates/all-tiers/gitlab-all-tiers.yml")
+ assert candidate["skill-evaluation-native"]["timeout"] == "5 hours"
+
+
+def test_gitlab_setup_selector_uses_pinned_safe_git_reader():
+ script = "\n".join(load("ci/gitlab/all-tiers.yml")["skill-evaluation"]["script"])
+ assert 'ci_changed="$(git diff' not in script
+ assert 'sys.path.insert(0, "/opt/skillevaluator/ci")' in script
+ assert "from select_changed_skills import _git" in script
+ assert "--name-only" in script and '"-z"' in script and "--no-renames" in script
+ assert 're.fullmatch(r"[0-9a-f]{40}", value)' in script
+
+
+def test_gitlab_read_token_is_removed_before_provider_bootstrap_and_feedback_is_advisory():
+ config = load("ci/gitlab/all-tiers.yml")
+ script = "\n".join(config["skill-evaluation-native"]["script"])
+ assert (
+ script.index("eligible_gitlab.py")
+ < script.index("unset SKILLEVALUATOR_GITLAB_READ_TOKEN")
+ < script.index("-m pip")
+ )
+ assert config["skill-evaluation-request-feedback"]["allow_failure"] == "true"
+
+
+def _gitlab_minutes(duration):
+ import re
+
+ match = re.fullmatch(r"(\d+) (minutes|hours)", duration)
+ assert match, duration
+ return int(match[1]) * (60 if match[2] == "hours" else 1)
+
+
+def test_gitlab_evaluator_budget_ends_before_the_native_job_timeout():
+ for path in ("ci/gitlab/all-tiers.yml", "ci/templates/all-tiers/gitlab-all-tiers.yml"):
+ config = load(path)
+ minutes = _gitlab_minutes(config["skill-evaluation-native"]["timeout"])
+ assert "$" not in config["skill-evaluation-native"]["timeout"]
+ reserve = min(20, minutes // 4)
+ assert config["variables"]["SKILL_EVAL_TIMEOUT_SECONDS"] == str((minutes - reserve) * 60) == "16800", path
+
+
+def test_gitlab_dind_daemon_requires_tls_client_certificates():
+ job = load("ci/gitlab/all-tiers.yml")["skill-evaluation-native"]
+ variables = job["variables"]
+ assert variables["DOCKER_HOST"] == "tcp://docker:2376"
+ assert variables["DOCKER_TLS_CERTDIR"] == "/certs"
+ assert variables["DOCKER_TLS_VERIFY"] == "1"
+ assert variables["DOCKER_CERT_PATH"] == "/certs/client"
+ assert "2375" not in str(job)
+ docs = " ".join((ROOT / "docs/gitlab-ci.mdx").read_text().split())
+ assert 'volumes = ["/certs/client"]' in docs
+
+
+def test_gitlab_native_jobs_use_environment_without_recording_deployments():
+ job = load("ci/gitlab/all-tiers.yml")["skill-evaluation-native"]
+ assert job["environment"] == {"name": "$SKILL_EVAL_ENVIRONMENT", "action": "prepare"}
+ docs = " ".join((ROOT / "docs/gitlab-ci.mdx").read_text().split())
+ assert "`environment: action: prepare`" in docs and "Prevent outdated deployment jobs" in docs
+
+
+def test_gitlab_feedback_job_uses_its_protected_environment_without_recording_deployments():
+ # Scoped publisher token and deploy access still apply; no deployment means
+ # "Prevent outdated deployment jobs" cannot drop an older MR's feedback.
+ job = load("ci/gitlab/feedback.yml")["skill-evaluation-feedback"]
+ assert job["environment"] == {"name": "skillevaluator-feedback", "action": "prepare"}
+ # The publisher authenticates its job, pipeline and branch, never a deployment record.
+ assert "/deployments" not in (ROOT / "ci/feedback.py").read_text()
+ docs = " ".join((ROOT / "docs/gitlab-ci.mdx").read_text().split())
+ assert "The native jobs and the trusted feedback job use `environment: action: prepare`" in docs
+ # Some GitLab versions turn prepare jobs on an environment with approval
+ # rules into manual jobs, so deploy access is the only safe restriction.
+ assert "Deployment approval rules apply only to jobs that create deployments" not in docs
+ assert "Do not add deployment approval rules to these environments" in docs
+ assert "turn them into manual jobs" in docs and "`prevent_blocking_non_deployment_jobs`" in docs
+ assert "Restrict who can run them with the protected environments' deploy access" in docs
+ onboarding = " ".join((ROOT / "docs/cli-onboarding.mdx").read_text().split())
+ assert "so deployment approvals do not gate them" not in onboarding
+ assert "Do not add deployment approval rules to their environments" in onboarding
+ assert "turn them into manual jobs" in onboarding
+
+
+def test_gitlab_feedback_pipeline_guard_is_offered_and_documented():
+ guard = {"if": '$SKILL_EVAL_FEEDBACK == "true"', "when": "never"}
+ hidden = load("ci/gitlab/all-tiers.yml")[".skill-evaluation-not-feedback"]
+ assert hidden["rules"][0] == guard
+ assert hidden["rules"][1] == {"when": "on_success"}
+ for path in ("docs/gitlab-ci.mdx", "ci/templates/README.md", "ci/templates/all-tiers/gitlab-all-tiers.yml"):
+ text = (ROOT / path).read_text()
+ assert "- if: '$SKILL_EVAL_FEEDBACK == \"true\"'" in text, path
+ docs = " ".join((ROOT / "docs/gitlab-ci.mdx").read_text().split())
+ assert "extends: .skill-evaluation-not-feedback" in docs
+ assert "no comment is posted or updated" in docs
+ assert "Merge these guards to the default branch before the setup MR" in docs
+ # Included jobs use stage test, so a merged root's stages must keep it.
+ assert "If the root defines `stages`, keep `test` in the list" in docs
+ assert "neither `rules` nor `only`/`except`" in docs
+ # Guards merge before the setup MR, while only all-tiers.yml defines the
+ # hidden job, so they use rules; a job without rules needs a fallback rule.
+ assert "gets the guard followed by `- when: on_success`" in docs
+ assert "- when: on_success" in (ROOT / "docs/gitlab-ci.mdx").read_text()
+ assert "Write these guards as rules" in docs
+ assert "until the setup MR merges, `extends: .skill-evaluation-not-feedback` fails validation" in docs
+ assert ".skill-evaluation-not-feedback" not in (ROOT / "ci/gitlab/skill-evaluation.yml").read_text()
+ template = " ".join((ROOT / "ci/templates/all-tiers/gitlab-all-tiers.yml").read_text().split())
+ assert "If the root defines stages, keep test" in template
+ assert "gets the guard followed by `- when: on_success`" in template
+ assert "Write the guards as rules" in template
+ assert "added after this file is on the default branch" in template
+ # The upgrade path must order the guards before the setup MR as well.
+ onboarding = " ".join((ROOT / "docs/cli-onboarding.mdx").read_text().split())
+ guards = onboarding.index("merge those guards to the default branch")
+ assert guards < onboarding.index("Then, in your setup MR")
+ assert "keep `test` in any `stages` list" in onboarding
+
+
+def _heredoc(script, marker):
+ return script.split(f"<<'{marker}'\n", 1)[1].split(f"\n{marker}\n", 1)[0] + "\n"
+
+
+def _setup_literals(source):
+ """Return the prefixes and exact paths that an inline setup predicate checks."""
+ import ast
+
+ prefixes, files = set(), set()
+ for node in ast.walk(ast.parse(source)):
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr == "startswith":
+ prefixes.update(ast.literal_eval(node.args[0]))
+ elif isinstance(node, ast.Compare) and isinstance(node.left, ast.Name) and node.left.id == "path":
+ assert all(isinstance(op, ast.Eq) for op in node.ops)
+ files.update(ast.literal_eval(value) for value in node.comparators)
+ text = {value.decode() if isinstance(value, bytes) else value for value in prefixes}
+ return text, {value.decode() if isinstance(value, bytes) else value for value in files}
+
+
+def test_tier1_setup_predicates_equal_the_shared_native_predicate():
+ from ci.select_changed_skills import SETUP_FILES, SETUP_PREFIXES
+
+ jobs = load(".github/workflows/evaluate-all-tiers.yml")["jobs"]
+ github = _heredoc(jobs["eligibility"]["steps"][0]["run"], "PY")
+ gitlab = _heredoc("\n".join(load("ci/gitlab/all-tiers.yml")["skill-evaluation"]["script"]), "PYTHON")
+ for source in (github, gitlab):
+ assert _setup_literals(source) == (set(SETUP_PREFIXES), set(SETUP_FILES))
+ # GitHub also widens when the PR file listing is too long to certify; the
+ # paid tiers take that decision instead of recomputing a different one.
+ paid = jobs["paid-tiers"]
+ assert paid["env"]["SKILL_EVAL_SCAN_MODE"] == jobs["tier1"]["with"]["scan-mode"]
+ assert "needs.eligibility.outputs.scan-mode" in paid["env"]["SKILL_EVAL_SCAN_MODE"]
+
+
+def test_gitlab_tier1_and_native_tiers_select_the_same_skills(tmp_path):
+ import os
+ import subprocess
+ import sys
+
+ from ci import run_tiers
+
+ heredoc = _heredoc("\n".join(load("ci/gitlab/all-tiers.yml")["skill-evaluation"]["script"]), "PYTHON")
+ heredoc = heredoc.replace('"/opt/skillevaluator/ci"', repr(str(ROOT / "ci")))
+ cases = {
+ "skill only": ([("skills/alpha/SKILL.md", "# alpha v2\n")], []),
+ "consumer ci script": ([("ci/build.sh", "echo build\n"), ("skills/alpha/SKILL.md", "# alpha v3\n")], []),
+ "workflow": ([(".github/workflows/skills.yml", "name: skills\n")], []),
+ "root pipeline": ([(".gitlab-ci.yml", "include: []\n")], []),
+ "renamed feedback include": ([], [(".gitlab/skill-feedback.yml", "docs/skill-feedback.yml")]),
+ }
+ for name, (writes, renames) in cases.items():
+ repo = tmp_path / name.replace(" ", "-")
+ repo.mkdir()
+ git = ["git", "-C", str(repo), "-c", "user.name=CI", "-c", "[email protected]"]
+ subprocess.run([*git, "init", "-q", "-b", "main"], check=True)
+ for skill in ("alpha", "beta"):
+ (repo / "skills" / skill).mkdir(parents=True)
+ (repo / "skills" / skill / "SKILL.md").write_text(f"# {skill}\n")
+ (repo / ".gitlab").mkdir()
+ (repo / ".gitlab/skill-feedback.yml").write_text("include: []\n" * 20)
+ subprocess.run([*git, "add", "-A"], check=True)
+ subprocess.run([*git, "commit", "-qm", "base"], check=True)
+ base = subprocess.check_output([*git, "rev-parse", "HEAD"], text=True).strip()
+ for relative, text in writes:
+ (repo / relative).parent.mkdir(parents=True, exist_ok=True)
+ (repo / relative).write_text(text)
+ for source, target in renames:
+ (repo / target).parent.mkdir(parents=True, exist_ok=True)
+ subprocess.run([*git, "mv", source, target], check=True)
+ subprocess.run([*git, "add", "-A"], check=True)
+ subprocess.run([*git, "commit", "-qm", "head"], check=True)
+ head = subprocess.check_output([*git, "rev-parse", "HEAD"], text=True).strip()
+ tier1 = subprocess.run(
+ [sys.executable, "-I", "-"],
+ input=heredoc,
+ env={"PATH": os.environ["PATH"], "DIFF_BASE_SHA": base, "DIFF_HEAD_SHA": head, "CI_PROJECT_DIR": str(repo)},
+ capture_output=True,
+ text=True,
+ check=True,
+ ).stdout.strip()
+ selected, selection = run_tiers.select_skills(
+ repo, {"SKILL_EVAL_PATHS": "skills", "DIFF_BASE_SHA": base, "REPORT_COMMIT": head}
+ )
+ native = "all" if selection.get("reason") == "ci_configuration_changed" else "changed"
+ assert tier1 == native, name
+ assert (native == "all") == (name not in {"skill only", "consumer ci script"}), name
+ if native == "changed":
+ assert [p.name for p in selected] == ["alpha"], name
diff --git a/tests/ci/test_ci_worker_diagnostics.py b/tests/ci/test_ci_worker_diagnostics.py
new file mode 100644
index 00000000..1e6c4d27
--- /dev/null
+++ b/tests/ci/test_ci_worker_diagnostics.py
@@ -0,0 +1,317 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Retain useful startup diagnostics without exporting unrelated worker state."""
+
+import json
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+from ci import diagnostics
+
+
+def test_retains_compose_stderr_and_redacts_literals_and_credential_shapes(tmp_path):
+ raw = tmp_path / "raw"
+ trial = raw / "harbor/job/trial"
+ trial.mkdir(parents=True)
+ supplied = "fixture-model-secret-12345678"
+ shaped = "nvapi-" + "x" * 48
+ (trial / "exception.txt").write_text(
+ "compose command "
+ + "arg " * 400
+ + "\nstderr: image pull denied\n"
+ + supplied
+ + "\n"
+ + shaped
+ + "\nAuthorization: Bearer fixture-unknown-token\npassword=fixture-password\n"
+ )
+ (trial / "failure.json").write_text(json.dumps({"error": {"message": supplied}, "api_key": "fixture-key"}))
+ output = tmp_path / "reports/skill-001"
+ result = diagnostics.retain_diagnostics(raw, output, {supplied})
+ assert result["index"] == "diagnostics/index.json"
+ assert json.loads((output / result["index"]).read_text()) == result
+ text = (output / "diagnostics/harbor/job/trial/exception.txt").read_text()
+ assert "stderr: image pull denied" in text
+ assert all(value not in text for value in (supplied, shaped, "fixture-unknown-token", "fixture-password"))
+ assert "[REDACTED]" in text
+ failure = json.loads((output / "diagnostics/harbor/job/trial/failure.json").read_text())
+ assert failure["error"]["message"] == "[REDACTED]" and failure["api_key"] == "[REDACTED]"
+ assert str(raw) not in json.dumps(result)
+
+
+def test_whitelist_excludes_agent_state_configs_payloads_and_binary_files(tmp_path):
+ raw = tmp_path / "raw"
+ raw.mkdir()
+ for relative in (
+ ".env",
+ "config.json",
+ "trajectory.json",
+ "agent/stdout.log",
+ "artifacts/exception.txt",
+ "workspace/stderr.log",
+ ):
+ path = raw / relative
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text("unrelated private state")
+ (raw / "stderr.log").write_bytes(b"binary\x00payload")
+ output = tmp_path / "output"
+ result = diagnostics.retain_diagnostics(raw, output, set())
+ assert result["retained"] == []
+ assert {item["reason"] for item in result["omitted"]} >= {"not_allowed", "binary_or_encoding"}
+ assert not list((output / "diagnostics").rglob("*.log"))
+
+
+def test_symlink_and_special_file_are_rejected_without_following_them(tmp_path):
+ raw = tmp_path / "raw"
+ raw.mkdir()
+ external = tmp_path / "outside"
+ external.mkdir()
+ (external / "exception.txt").write_text("outside evidence")
+ (raw / "linked-directory").symlink_to(external, target_is_directory=True)
+ (raw / "exception.txt").symlink_to(external / "exception.txt")
+ os.mkfifo(raw / "trial.log")
+ output = tmp_path / "output"
+ result = diagnostics.retain_diagnostics(raw, output, set())
+ assert result["retained"] == []
+ assert {item["reason"] for item in result["errors"]} >= {"unsafe_link", "special_file"}
+ assert not (output / "diagnostics/linked-directory").exists()
+ with pytest.raises(ValueError):
+ diagnostics.retain_diagnostics(raw / "linked-directory", tmp_path / "another", set())
+
+
+def test_large_text_is_bounded_and_preserves_terminal_stderr(tmp_path, monkeypatch):
+ monkeypatch.setattr(diagnostics, "MAX_FILE_BYTES", 256)
+ raw = tmp_path / "raw"
+ raw.mkdir()
+ (raw / "exception.txt").write_text("begin\n" + "long-command " * 100 + "\nstderr: daemon unavailable\n")
+ output = tmp_path / "output"
+ result = diagnostics.retain_diagnostics(raw, output, set())
+ target = output / "diagnostics/exception.txt"
+ assert target.stat().st_size <= 256
+ assert "stderr: daemon unavailable" in target.read_text()
+ assert result["truncated"] == ["exception.txt"]
+
+
+def test_file_count_and_total_bytes_are_bounded(tmp_path, monkeypatch):
+ monkeypatch.setattr(diagnostics, "MAX_TRIALS_PER_JOB", 10)
+ monkeypatch.setattr(diagnostics, "MAX_TRIALS", 10)
+ monkeypatch.setattr(diagnostics, "MAX_FILES", 2)
+ monkeypatch.setattr(diagnostics, "MAX_TOTAL_BYTES", 70)
+ raw = tmp_path / "raw"
+ for n in range(5):
+ path = raw / str(n) / "trial.log"
+ path.parent.mkdir(parents=True)
+ path.write_text("x" * 30)
+ output = tmp_path / "output"
+ result = diagnostics.retain_diagnostics(raw, output, set())
+ assert len(result["retained"]) <= 2
+ assert sum(item["bytes"] for item in result["retained"]) <= 70
+ assert result["omitted"]
+
+
+def test_optional_command_log_is_explicit_and_destination_cannot_escape(tmp_path):
+ raw = tmp_path / "raw"
+ raw.mkdir()
+ command = tmp_path / "worker.log"
+ command.write_text("worker startup failed\n")
+ output = tmp_path / "output"
+ result = diagnostics.retain_diagnostics(raw, output, set(), command_log=command)
+ assert (output / "diagnostics/command.log").read_text() == command.read_text()
+ assert result["retained"][0]["path"] == "command.log"
+ with pytest.raises(ValueError):
+ diagnostics.retain_diagnostics(raw, raw / "nested", set())
+ linked = tmp_path / "linked-output"
+ linked.symlink_to(output, target_is_directory=True)
+ with pytest.raises(ValueError):
+ diagnostics.retain_diagnostics(raw, linked, set())
+
+
+def test_only_known_harbor_install_setup_logs_are_retained_from_agent_directory(tmp_path):
+ raw = tmp_path / "raw"
+ setup = raw / "trial/agent/setup"
+ setup.mkdir(parents=True)
+ (setup / "install-agent-runtime.attempt-2.failed.log").write_text("stderr: install failed\n")
+ (setup / "arbitrary-session.log").write_text("agent state")
+ (setup.parent / "stdout.log").write_text("agent output")
+ output = tmp_path / "output"
+ result = diagnostics.retain_diagnostics(raw, output, set())
+ assert [item["path"] for item in result["retained"]] == [
+ "trial/agent/setup/install-agent-runtime.attempt-2.failed.log"
+ ]
+ assert not (output / "diagnostics/trial/agent/stdout.log").exists()
+
+
+ "credential",
+ [
+ "Authorization: Basic dXNlcjpzZWNyZXQ=",
+ 'password="secret with spaces"',
+ "password='secret with spaces'",
+ ],
+)
+def test_text_credentials_are_redacted_as_complete_values(tmp_path, credential):
+ raw = tmp_path / "raw"
+ raw.mkdir()
+ (raw / "exception.txt").write_text(credential + "\nstderr: startup failed\n")
+ output = tmp_path / "output"
+ diagnostics.retain_diagnostics(raw, output, set())
+ retained = (output / "diagnostics/exception.txt").read_text()
+ assert "[REDACTED]" in retained
+ assert "dXNlcjpzZWNyZXQ=" not in retained
+ assert "secret" not in retained and "with spaces" not in retained
+ assert "stderr: startup failed" in retained
+
+
+def test_agent_setup_uses_the_shared_discovery_budget(tmp_path, monkeypatch):
+ monkeypatch.setattr(diagnostics, "MAX_ENTRIES", 8)
+ raw = tmp_path / "raw"
+ for trial in ("trial-a", "trial-b"):
+ setup = raw / trial / "agent/setup"
+ setup.mkdir(parents=True)
+ for attempt in range(1, 6):
+ (setup / f"install-agent-runtime.attempt-{attempt}.log").write_text("startup failed\n")
+ (raw / "stderr.log").write_text("worker failed\n")
+ output = tmp_path / "output"
+ result = diagnostics.retain_diagnostics(raw, output, set())
+ # Two trial directories, the root log and the first agent/setup directories
+ # consume five entries, leaving room for three setup logs across the tree.
+ assert len(result["retained"]) == 4
+ assert len(list((output / "diagnostics").rglob("*.log"))) == 4
+ assert any(item["reason"] == "discovery_limit" for item in result["omitted"])
+
+
+def test_long_token_free_log_lines_finish_without_quadratic_key_scanning():
+ program = """
+from ci.diagnostics import _mask_text
+from skillevaluator.utils.secret_redaction import Redactor
+redactor = Redactor(set())
+for text in ('a' * 100_000, 'a-' * 50_000):
+ assert _mask_text(text, redactor) == text
+print('unchanged')
+"""
+ completed = subprocess.run(
+ [sys.executable, "-B", "-c", program],
+ cwd=Path(__file__).resolve().parents[2],
+ capture_output=True,
+ text=True,
+ timeout=5,
+ check=True,
+ )
+ assert completed.stdout == "unchanged\n"
+
+
+def test_only_the_first_failing_trial_of_each_job_and_four_per_skill_are_kept(tmp_path):
+ jobs = tmp_path / "raw/harbor/run/_harbor-jobs"
+ trials = {
+ "skill-claude-with/case-1": True,
+ "skill-claude-without/case-1": True,
+ "skill-codex-with/case-1": False,
+ "skill-codex-with/case-2": True,
+ "skill-codex-with/case-3": True,
+ "skill-codex-without/case-1": False,
+ "skill-codex-without/case-2": False,
+ "skill-opencode-with/case-1": True,
+ }
+ for name, failed in trials.items():
+ trial = jobs / name
+ (trial / "agent/setup").mkdir(parents=True)
+ (trial / "trial.log").write_text(f"{name} started\n")
+ (trial / "agent/setup/install-agent-runtime.failed.log").write_text("install failed\n")
+ if failed:
+ (trial / "exception.txt").write_text(f"{name} failed\n")
+ output = tmp_path / "output"
+ result = diagnostics.retain_diagnostics(tmp_path / "raw", output, set())
+ kept = {item["path"].split("/")[3] + "/" + item["path"].split("/")[4] for item in result["retained"]}
+ # Failing trials of every job come before the passing-only job that sorts earlier.
+ assert kept == {
+ "skill-claude-with/case-1",
+ "skill-claude-without/case-1",
+ "skill-codex-with/case-2",
+ "skill-opencode-with/case-1",
+ }
+ assert len(result["retained"]) == 4 * 3 # trial.log, setup log and exception.txt each
+ limited = {item["path"] for item in result["omitted"] if item["reason"] == "trial_limit"}
+ assert limited == {
+ "harbor/run/_harbor-jobs/skill-codex-with/case-1",
+ "harbor/run/_harbor-jobs/skill-codex-with/case-3",
+ "harbor/run/_harbor-jobs/skill-codex-without/case-1",
+ "harbor/run/_harbor-jobs/skill-codex-without/case-2",
+ }
+
+
+def test_failing_jobs_that_sort_last_keep_their_trials_before_passing_jobs(tmp_path):
+ jobs = tmp_path / "raw/harbor/run/_harbor-jobs"
+ # Three agents with two arms each; only the agent that sorts last failed.
+ for agent in ("claude-code", "codex", "opencode"):
+ for arm in ("with", "without"):
+ trial = jobs / f"skill-{agent}-{arm}/case-1"
+ trial.mkdir(parents=True)
+ (trial / "trial.log").write_text(f"{agent} {arm} started\n")
+ if agent == "opencode":
+ (trial / "exception.txt").write_text("opencode: agent installation failed\n")
+ command = tmp_path / "skill-001.log"
+ command.write_text("worker output\n")
+ result = diagnostics.retain_diagnostics(tmp_path / "raw", tmp_path / "output", set(), command_log=command)
+ assert [item["path"] for item in result["retained"]] == [
+ "command.log",
+ "harbor/run/_harbor-jobs/skill-claude-code-with/case-1/trial.log",
+ "harbor/run/_harbor-jobs/skill-claude-code-without/case-1/trial.log",
+ "harbor/run/_harbor-jobs/skill-opencode-with/case-1/exception.txt",
+ "harbor/run/_harbor-jobs/skill-opencode-with/case-1/trial.log",
+ "harbor/run/_harbor-jobs/skill-opencode-without/case-1/exception.txt",
+ "harbor/run/_harbor-jobs/skill-opencode-without/case-1/trial.log",
+ ]
+ assert [item["path"] for item in result["omitted"] if item["reason"] == "trial_limit"] == [
+ "harbor/run/_harbor-jobs/skill-codex-with/case-1",
+ "harbor/run/_harbor-jobs/skill-codex-without/case-1",
+ ]
+
+
+def test_tier_budget_is_shared_across_skills_and_keeps_command_logs_first(tmp_path, monkeypatch):
+ monkeypatch.setattr(diagnostics, "MAX_TIER_FILES", 3)
+ budget = diagnostics.TierBudget()
+ results = []
+ for index in (1, 2):
+ raw = tmp_path / f"raw-{index}"
+ trial = raw / "harbor/job/trial"
+ trial.mkdir(parents=True)
+ (trial / "trial.log").write_text("trial started\n")
+ (trial / "exception.txt").write_text("startup failed\n")
+ command = tmp_path / f"skill-{index}.log"
+ command.write_text("worker failed\n")
+ results.append(
+ diagnostics.retain_diagnostics(raw, tmp_path / f"out-{index}", set(), command_log=command, budget=budget)
+ )
+ assert results[0]["retained"][0]["path"] == "command.log"
+ assert len(results[0]["retained"]) == 3 and budget.files == 0
+ assert results[1]["retained"] == []
+ assert {item["reason"] for item in results[1]["omitted"]} == {"tier_limit"}
+ assert (tmp_path / "out-2/diagnostics/index.json").is_file()
+
+ monkeypatch.setattr(diagnostics, "MAX_TIER_BYTES", 20)
+ budget = diagnostics.TierBudget()
+ raw = tmp_path / "raw-3"
+ raw.mkdir()
+ (raw / "stderr.log").write_text("x" * 15 + "\n")
+ (raw / "stdout.log").write_text("y" * 15 + "\n")
+ result = diagnostics.retain_diagnostics(raw, tmp_path / "out-3", set(), budget=budget)
+ assert [item["path"] for item in result["retained"]] == ["stderr.log"]
+ assert result["omitted"] == [{"path": "stdout.log", "reason": "tier_limit"}]
+
+
+def test_tier_caps_stay_within_what_the_feedback_reader_accepts():
+ from ci import feedback
+
+ # Each tier has at most one index.json per skill plus the Tier 2 catalog root.
+ roots = feedback.MAX_SKILLS + 1
+ files = diagnostics.MAX_TIER_FILES + roots
+ # A GitLab archive also lists every directory of a retained path: diagnostics/,
+ # up to MAX_DEPTH walked levels, and an agent/setup pair below the deepest one.
+ members = 2 * files * (1 + 1 + diagnostics.MAX_DEPTH + 2)
+ assert members <= feedback.MAX_DIAGNOSTIC_MEMBERS
+ # Logs share the tier byte budget; an index.json stays below one file's size.
+ assert 2 * (diagnostics.MAX_TIER_BYTES + roots * diagnostics.MAX_FILE_BYTES) <= feedback.MAX_DIAGNOSTIC_BYTES
+ # Even incompressible logs from both native tiers leave half of the archive for reports.
+ assert 2 * diagnostics.MAX_TIER_BYTES <= feedback.MAX_BYTES // 2
diff --git a/tests/ci/test_comment_summary.py b/tests/ci/test_comment_summary.py
new file mode 100644
index 00000000..3a2e514d
--- /dev/null
+++ b/tests/ci/test_comment_summary.py
@@ -0,0 +1,340 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Compact PR/MR comments retain truthful, skill-scoped native evidence."""
+
+import copy
+import html
+import re
+
+import pytest
+
+ARTIFACT_URL = "https://github.com/acme/skills/actions/runs/123/artifacts/456"
+
+
+def manifest():
+ return {
+ "schema_version": 1,
+ "report_contract": "skillevaluator-ci-v1",
+ "commit": "a" * 40,
+ "repository": "acme/skills",
+ "platform": "github",
+ "run_id": "123",
+ "run_attempt": "1",
+ "environment": "docker",
+ "tiers": [
+ {
+ "tier": tier,
+ "required": tier == 1,
+ "status": "passed",
+ "skills": [
+ {
+ "path": "skills/demo",
+ "status": "passed",
+ "report_json": f"tier{tier}/skill-001/skillevaluator-tier{tier}.json",
+ "report_html": f"tier{tier}/skill-001/skillevaluator-tier{tier}.html",
+ "metrics": {
+ "issue_count": 0,
+ "issue_count_known": True,
+ "critical_count": 0,
+ "high_count": 0,
+ "top_issue": None,
+ },
+ }
+ ],
+ }
+ for tier in (1, 2, 3)
+ ],
+ }
+
+
+def render(payload):
+ from ci.comment_summary import render_comment_summary
+
+ return render_comment_summary(payload, ARTIFACT_URL)
+
+
+def data_rows(body):
+ return [line for line in body.splitlines() if line.startswith("| ")][2:]
+
+
+def test_one_skill_row_combines_all_three_tiers_and_one_download_link():
+ payload = manifest()
+ payload["tiers"][1]["status"] = "failed"
+ skill = payload["tiers"][1]["skills"][0]
+ skill.update(
+ status="failed",
+ metrics={
+ "issue_count": 3,
+ "issue_count_known": True,
+ "critical_count": 1,
+ "high_count": 1,
+ "top_issue": "Repeated deployment instructions",
+ "private_metric": "must not appear",
+ },
+ )
+ before = copy.deepcopy(payload)
+
+ body = render(payload)
+
+ assert "Required gate: **Passed**" in body
+ assert "Only Tier 1 blocks CI; Tier 2 and Tier 3 are advisory." in body
+ assert "| Skill | Tier 1: Static and Security Validation | Tier 2: Deduplication |" in body
+ assert "Tier 3: Live Agent Evaluation | Report |" in body
+ assert len(data_rows(body)) == 1
+ assert data_rows(body)[0].count("PASSED") == 2
+ assert "FAILED · 3 issues (1 critical, 1 high) · Repeated deployment instructions" in body
+ assert body.count(f"[Report]({ARTIFACT_URL})") == 1
+ assert "Native HTML" not in body and "## Tier" not in body and "must not appear" not in body
+ assert ".html" not in body and ".json" not in body
+ assert payload == before
+
+
+def test_missing_native_metrics_cannot_become_zero_issues():
+ payload = manifest()
+ skill = payload["tiers"][2]["skills"][0]
+ skill.update(status="incomplete", report_json=None, report_html=None, error="Configure the live agent key")
+ skill.pop("metrics")
+ payload["tiers"][2]["status"] = "incomplete"
+
+ tier3_cell = data_rows(render(payload))[0].split("|")[4]
+
+ assert "INCOMPLETE" in tier3_cell and "issues unknown" in tier3_cell
+ assert "Configure the live agent key" in tier3_cell and "0 issues" not in tier3_cell
+
+
+ "count,critical,high,expected",
+ [
+ (0, 0, 0, "PASSED · 0 issues"),
+ (2, 0, 1, "PASSED · 2 issues (1 high)"),
+ (2, 1, 0, "PASSED · 2 issues (1 critical)"),
+ ],
+)
+def test_zero_severity_counts_do_not_distract_from_the_issue_summary(count, critical, high, expected):
+ payload = manifest()
+ payload["tiers"][0]["skills"][0]["metrics"].update(issue_count=count, critical_count=critical, high_count=high)
+
+ cell = data_rows(render(payload))[0].split("|")[2].strip()
+
+ assert cell == expected
+
+
+def test_unknown_skill_evidence_uses_tier_provider_action_when_no_own_detail_exists():
+ payload = manifest()
+ tier = payload["tiers"][2]
+ tier.update(status="needs_action", reason="Missing provider credential: configure the live agent key")
+ skill = tier["skills"][0]
+ skill.update(status="needs_action", report_json=None, report_html=None)
+ skill.pop("metrics")
+
+ cell = data_rows(render(payload))[0].split("|")[4]
+
+ assert "NEEDS_ACTION · issues unknown · Missing provider credential: configure the live agent key" in cell
+ assert "Native evidence unavailable" not in cell
+
+
+def test_complete_clean_skill_does_not_borrow_a_tier_reason():
+ payload = manifest()
+ payload["tiers"][0]["reason"] = "Missing provider credential for another selected skill"
+
+ cell = data_rows(render(payload))[0].split("|")[2].strip()
+
+ assert cell == "PASSED · 0 issues"
+
+
+def test_highest_native_finding_takes_priority_over_a_generic_execution_error():
+ payload = manifest()
+ tier = payload["tiers"][0]
+ tier["status"] = "failed"
+ skill = tier["skills"][0]
+ skill.update(status="failed", error="Validation process exited with code 1")
+ skill["metrics"].update(issue_count=1, critical_count=1, top_issue="Critical command injection in deploy.sh")
+
+ cell = data_rows(render(payload))[0].split("|")[2]
+
+ assert "Critical command injection in deploy.sh" in cell
+ assert "Validation process exited" not in cell
+
+
+def test_incomplete_native_evidence_reports_observed_findings_as_a_lower_bound():
+ payload = manifest()
+ payload["tiers"][0]["status"] = "incomplete"
+ skill = payload["tiers"][0]["skills"][0]
+ skill.update(status="incomplete")
+ skill["metrics"].update(issue_count=2, issue_count_known=False, critical_count=1, top_issue="Unsafe shell")
+
+ body = render(payload)
+
+ assert "Required gate: **Not passed**" in body
+ assert "INCOMPLETE · at least 2 issues" in body and "Unsafe shell" in body
+
+
+def test_missing_skill_does_not_reuse_sibling_finding_or_counts():
+ payload = manifest()
+ sibling = payload["tiers"][1]["skills"][0]
+ sibling.update(path="skills/other", status="failed")
+ sibling["metrics"].update(issue_count=9, critical_count=9, top_issue="Sibling only issue")
+ payload["tiers"][1]["status"] = "failed"
+
+ rows = data_rows(render(payload))
+ demo = next(row for row in rows if row.startswith("| skills/demo |"))
+ other = next(row for row in rows if row.startswith("| skills/other |"))
+
+ assert "INCOMPLETE · issues unknown · No retained result for this skill" in demo
+ assert "Sibling only issue" not in demo and "9 issues" not in demo
+ assert "FAILED · 9 issues" in other and "Sibling only issue" in other
+ assert "INCOMPLETE · issues unknown" in other
+
+
+def test_empty_tier_preflight_failure_keeps_its_declared_reason():
+ payload = manifest()
+ payload["tiers"][1].update(status="failed", skills=[], reason="Duplication check failed")
+
+ cell = data_rows(render(payload))[0].split("|")[3]
+
+ assert "FAILED · issues unknown · Duplication check failed" in cell
+
+
+def test_missing_whole_tier_and_unrequested_tier_are_distinct():
+ payload = manifest()
+ payload["tiers"] = payload["tiers"][:1]
+ body = render(payload)
+ assert body.count("NOT_RUN · issues unknown · No retained result") == 2
+ payload["expected_tiers"] = [1]
+ assert render(payload).count("NOT_RUN · issues unknown · Not requested") == 2
+
+
[email protected]("required_paid", [[], [2], [3], [2, 3]])
+def test_policy_matches_historical_required_flags(required_paid):
+ payload = manifest()
+ for tier in required_paid:
+ record = payload["tiers"][tier - 1]
+ record.update(required=True, status="failed")
+ record["skills"][0]["status"] = "failed"
+
+ body = render(payload)
+
+ if required_paid:
+ assert "Required gate: **Not passed**" in body
+ assert "Only Tier 1 blocks CI" not in body
+ required = ", ".join(f"Tier {tier}" for tier in [1, *required_paid])
+ advisory = ", ".join(f"Tier {tier}" for tier in (2, 3) if tier not in required_paid) or "none"
+ assert f"Required tiers: {required}. Advisory tiers: {advisory}." in body
+ else:
+ assert "Required gate: **Passed**" in body
+ assert "Only Tier 1 blocks CI" in body
+
+
+def test_no_work_keeps_each_tier_state_and_a_single_report_link():
+ payload = manifest()
+ for record in payload["tiers"]:
+ record.update(status="skipped", skills=[], reason="No changed skills")
+ body = render(payload)
+ assert "Required gate: **Skipped**" in body
+ assert len(data_rows(body)) == 1
+ assert "No skills evaluated" in body
+ assert body.count("SKIPPED · issues unknown · No changed skills") == 3
+ assert body.count(f"[Report]({ARTIFACT_URL})") == 1
+
+
+def test_cell_content_cannot_create_markup_mentions_or_extra_rows():
+ payload = manifest()
+ for tier in payload["tiers"]:
+ skill = tier["skills"][0]
+ skill["path"] = "skills/@everyone[demo]|<b>*"
+ skill["metrics"].update(
+ issue_count=1, high_count=1, top_issue="@team <script> [link](https://bad.test) | **bold**\n" + "x" * 500
+ )
+
+ body = render(payload)
+ row = data_rows(body)[0]
+
+ assert len(data_rows(body)) == 1 and row.count("|") == 6
+ assert re.search(r"(@|&#64;)\w", body) is None
+ assert "<script>" not in body and "<b>" not in body
+ assert "[link](https://bad.test)" not in body and "**bold**" not in body
+ assert "x" * 150 not in body and "…" in body
+
+
[email protected]("handle", ["@user", "@all", "@org/team", "&#64;user", "&commat;user", "\\@user"])
+def test_untrusted_text_never_renders_user_or_team_mentions(handle):
+ from ci.summary_metrics import _plain_text
+
+ payload = manifest()
+ path = f"skills/{handle}"
+ tier1, tier2, tier3 = payload["tiers"]
+ tier1.update(status="failed")
+ tier1["skills"][0].update(path=path, status="failed")
+ tier1["skills"][0]["metrics"].update(issue_count=1, high_count=1, top_issue=f"{handle} raw top issue")
+ other = copy.deepcopy(tier1["skills"][0])
+ other.update(path="skills/other")
+ other["metrics"].update(top_issue=_plain_text(f"{handle} summarized issue"))
+ tier1["skills"].append(other)
+ # A tier without per-skill evidence explains itself with its own error text.
+ tier2.update(status="incomplete", skills=[], error=f"Tier error from {handle}")
+ tier3.update(status="failed")
+ tier3["skills"][0].update(path=path, status="failed", error=f"{handle} skill error")
+ tier3["skills"][0]["metrics"].update(issue_count_known=False)
+
+ body = render(payload)
+
+ # CommonMark decodes "&#64;" to "@" before GitHub and GitLab resolve mentions.
+ assert re.search(r"(@|&#64;)\w", body) is None
+ assert set(re.findall(r"&[^\s&;]*;", body)) <= {"&amp;", "&lt;", "&gt;", "&#124;"}
+ rendered_text = html.unescape(re.sub(r"\\(.)", r"\1", body))
+ assert re.search(r"@\w", rendered_text) is None
+ assert "skills/" + handle.replace("@", "@\u200b") in rendered_text
+ for text in ("skills/other", "raw top issue", "summarized issue", "Tier error from", "skill error"):
+ assert text in rendered_text
+
+
+def test_large_skill_set_is_bounded_and_reports_the_omitted_count():
+ payload = manifest()
+ for tier in payload["tiers"]:
+ original = tier["skills"][0]
+ tier["skills"] = [dict(original, path=f"skills/demo-{index:04d}") for index in range(1000)]
+
+ body = render(payload)
+ rows = data_rows(body)
+ omitted = re.search(r"([0-9]+) additional skills omitted", body)
+
+ assert len(body.encode("utf-8")) < 55000
+ assert 0 < len(rows) < 1000 and omitted is not None
+ assert len(rows) + int(omitted.group(1)) == 1000
+ assert body.count(f"[Report]({ARTIFACT_URL})") == len(rows)
+
+
+def test_rejects_contradictory_gate_instead_of_rendering_it():
+ payload = manifest()
+ payload["overall_passed"] = False
+ with pytest.raises(ValueError, match="contradicts"):
+ render(payload)
+
+
+ "url", ["javascript:alert(1)", "http://example.test/archive.zip", "https://a.test/x\n| forged |"]
+)
+def test_rejects_unsafe_artifact_links(url):
+ from ci.comment_summary import render_comment_summary
+
+ with pytest.raises(ValueError, match="artifact"):
+ render_comment_summary(manifest(), url)
+
+
+def test_skill_a_tier_did_not_select_is_skipped_not_incomplete():
+ payload = manifest()
+ other = copy.deepcopy(payload["tiers"][1]["skills"][0])
+ other["path"] = "skills/other"
+ for record in payload["tiers"][1:]:
+ record["skills"].append(copy.deepcopy(other))
+ # Tier 1 recorded its selection; Tier 2 selected both skills but lost one result.
+ payload["tiers"][0]["selected"] = ["skills/demo"]
+ payload["tiers"][1]["selected"] = ["skills/demo", "skills/other"]
+ payload["tiers"][1]["skills"].pop()
+ payload["tiers"][1]["status"] = "incomplete"
+
+ row = next(row for row in data_rows(render(payload)) if row.startswith("| skills/other |"))
+ tier1, tier2, tier3 = row.split(" | ")[1:4]
+
+ assert tier1 == "SKIPPED · issues unknown · Not selected for this tier"
+ assert tier2 == "INCOMPLETE · issues unknown · No retained result for this skill"
+ assert tier3.startswith("PASSED · 0 issues")
diff --git a/tests/ci/test_compact_completeness.py b/tests/ci/test_compact_completeness.py
new file mode 100644
index 00000000..d75b2fcb
--- /dev/null
+++ b/tests/ci/test_compact_completeness.py
@@ -0,0 +1,100 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Compact feedback must preserve canonical Tier 3 execution uncertainty."""
+
+import io
+import json
+import zipfile
+
+from ci.feedback import read_results
+from ci.summary_metrics import summarize_results
+from ci.tier_manifest import tier3_execution_complete
+
+from skillevaluator.models import ValidationResult
+from skillevaluator.reporting.json_reporter import JSONReporter
+from skillevaluator.reporting.retained import retained_results
+from skillevaluator.validators.hygiene import HygieneValidator
+
+
+def test_failed_unpaired_tier3_evidence_does_not_claim_a_complete_issue_total():
+ result = ValidationResult(
+ validator_name="AGENT_EVAL",
+ metadata={
+ "gating": {"tier": 3, "blocking": False},
+ "agent_eval": {
+ "mode": "with_skill",
+ "execution_status": "succeeded",
+ "verdict": "fail",
+ "summary": {
+ "expected_attempts": 2,
+ "scored_attempts": 2,
+ "execution_status": "succeeded",
+ "verdict": "fail",
+ "overall_score": 0.2,
+ "overall_lift": 0.1,
+ },
+ },
+ },
+ )
+ result.fail_gate("Score is below the required minimum")
+ native = json.loads(JSONReporter().render_all([result]))
+ assert tier3_execution_complete(native) is False
+ json_path = "tier3/skill-001/skillevaluator-tier3.json"
+ html_path = json_path.removesuffix(".json") + ".html"
+ manifest = {
+ "schema_version": 1,
+ "report_contract": "skillevaluator-ci-v1",
+ "commit": "a" * 40,
+ "repository": "acme/skills",
+ "platform": "github",
+ "run_id": "123",
+ "run_attempt": "1",
+ "environment": "docker",
+ "expected_tiers": [3],
+ "tiers": [
+ {
+ "tier": 3,
+ "required": False,
+ "status": "failed",
+ "skills": [
+ {
+ "path": "skills/demo",
+ "status": "failed",
+ "report_json": json_path,
+ "report_html": html_path,
+ }
+ ],
+ }
+ ],
+ }
+ archive = io.BytesIO()
+ with zipfile.ZipFile(archive, "w") as retained:
+ retained.writestr("ci-results.json", json.dumps(manifest))
+ retained.writestr(json_path, json.dumps(native))
+ retained.writestr(html_path, "<p>Retained native evidence</p>")
+
+ validated = read_results(archive.getvalue())
+ metrics = validated["tiers"][0]["skills"][0]["metrics"]
+
+ assert metrics["issue_count"] == 1
+ assert metrics["issue_count_known"] is False
+ assert "score" not in metrics
+ assert "skill_lift" not in metrics
+
+
+def test_current_tier1_legacy_error_and_warning_count_as_issues(tmp_path):
+ (tmp_path / "SKILL.md").write_text("# Demo\n\nRead the [guide](missing.md).\n", encoding="utf-8")
+ validator = HygieneValidator()
+ result = validator.validate(tmp_path)
+ result.validator_name = validator.name
+ result.metadata["gating"] = {"tier": 1, "blocking": True}
+ assert any("Dead link" in error for error in result.errors)
+ assert any("test-file candidates" in warning for warning in result.warnings)
+ assert not result.findings
+ assert not result.is_incomplete
+ native = json.loads(JSONReporter().render_all([result]))
+ validated = retained_results(native, allowed_tiers={1})
+
+ metrics = summarize_results(validated, tier=1, native=native)
+
+ assert metrics["issue_count"] == 2
+ assert metrics["issue_count_known"] is True
diff --git a/tests/ci/test_feedback.py b/tests/ci/test_feedback.py
new file mode 100644
index 00000000..0000c664
--- /dev/null
+++ b/tests/ci/test_feedback.py
@@ -0,0 +1,1756 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Trusted feedback accepts API-bound current evidence and owns only its bot notes."""
+
+from __future__ import annotations
+
+import base64
+import copy
+import importlib
+import io
+import json
+import re
+import stat
+import sys
+import zipfile
+from pathlib import Path
+
+import pytest
+
+REPO = "acme/skills"
+SHA = "a" * 40
+MERGE = "d" * 40
+BLOB = "b" * 40
+WORKFLOW = "NVIDIA/SkillEvaluator/.github/workflows/evaluate-all-tiers.yml@" + "c" * 40
+
+
+def adapter():
+ assert importlib.util.find_spec("ci.feedback") is not None, "trusted all-tier feedback adapter is required"
+ return importlib.import_module("ci.feedback")
+
+
+def manifest(platform="github"):
+ return {
+ "schema_version": 1,
+ "report_contract": "skillevaluator-ci-v1",
+ "commit": SHA,
+ "base_commit": None,
+ "repository": REPO,
+ "platform": platform,
+ "run_id": "123",
+ "run_attempt": "1",
+ "environment": "docker",
+ "tiers": [
+ {"tier": n, "status": "skipped", "required": n != 3, "reason": "No changed skills", "skills": []}
+ for n in (1, 2, 3)
+ ],
+ }
+
+
+def archive(payload=None, extra=None, prefix=""):
+ output = io.BytesIO()
+ with zipfile.ZipFile(output, "w") as zipped:
+ zipped.writestr(prefix + "ci-results.json", json.dumps(payload or manifest()))
+ for name, value in (extra or {}).items():
+ zipped.writestr(name, value)
+ return output.getvalue()
+
+
+class GitHub:
+ def __init__(self):
+ self.run = {
+ "id": 123,
+ "run_attempt": 1,
+ "event": "pull_request",
+ "head_sha": SHA,
+ "path": ".github/workflows/skill-checks-all-tiers.yml",
+ "status": "completed",
+ "conclusion": "success",
+ "repository": {"full_name": REPO, "id": 12},
+ "head_repository": {"full_name": REPO, "id": 12},
+ "run_started_at": "2026-11-01T00:00:00Z",
+ "updated_at": "2026-11-01T00:10:00Z",
+ "pull_requests": [{"number": 7}],
+ "referenced_workflows": [{"path": WORKFLOW, "sha": "c" * 40}],
+ }
+ self.pr = {
+ "state": "open",
+ "number": 7,
+ "head": {"sha": SHA, "repo": {"full_name": REPO}},
+ "base": {"repo": {"full_name": REPO}},
+ }
+ self.artifacts = [
+ {
+ "id": n,
+ "name": name,
+ "expired": False,
+ "size_in_bytes": 100,
+ "created_at": "2026-11-01T00:05:00Z",
+ "workflow_run": {"id": 123, "head_sha": SHA},
+ }
+ for n, name in (
+ (21, "skill-evaluator-results-attempt-1"),
+ (22, "skill-evaluator-results-provenance-attempt-1"),
+ )
+ ]
+ self.payload = archive()
+ self.comments = []
+ self.writes = []
+ self.gets = []
+ self.downloads = []
+ self.other_runs = {}
+ self.flip_head_on_recheck = False
+
+ def get(self, path):
+ self.gets.append(path)
+ prefix = "/repos/" + REPO
+ if path == prefix + "/actions/runs/123":
+ return copy.deepcopy(self.run)
+ if path.startswith(prefix + "/actions/runs/") and path.rsplit("/", 1)[-1].isdigit():
+ identifier = int(path.rsplit("/", 1)[-1])
+ if identifier not in self.other_runs:
+ import urllib.error
+
+ raise urllib.error.HTTPError("https://api.github.com" + path, 404, "Not Found", {}, None)
+ return copy.deepcopy(self.other_runs[identifier])
+ if path == prefix + "/actions/runs/123/artifacts?per_page=100":
+ return {"total_count": len(self.artifacts), "artifacts": copy.deepcopy(self.artifacts)}
+ if path.startswith(prefix + "/contents/"):
+ assert path.endswith("?ref=" + MERGE)
+ return {"type": "file", "path": ".github/workflows/skill-checks-all-tiers.yml", "sha": BLOB}
+ if path == prefix + "/pulls/7":
+ pr = copy.deepcopy(self.pr)
+ if self.flip_head_on_recheck and self.gets.count(path) > 1:
+ pr["head"]["sha"] = "e" * 40
+ return pr
+ if path.startswith(prefix + "/issues/7/comments?"):
+ return copy.deepcopy(self.comments)
+ if path.startswith(prefix + "/issues/comments/"):
+ identifier = int(path.rsplit("/", 1)[-1])
+ return copy.deepcopy(next(c for c in self.comments if c["id"] == identifier))
+ raise AssertionError(path)
+
+ def download_artifact(self, identifier):
+ self.downloads.append(identifier)
+ return self.payload if identifier == 21 else b"signed-receipt"
+
+ def post(self, path, payload):
+ self.writes.append(("POST", path, payload))
+ comment = {
+ "id": 51,
+ "body": payload["body"],
+ "user": {"login": "github-actions[bot]", "type": "Bot"},
+ "html_url": "https://github.com/acme/skills/pull/7#issuecomment-51",
+ }
+ self.comments.append(comment)
+ return copy.deepcopy(comment)
+
+ def patch(self, path, payload):
+ self.writes.append(("PATCH", path, payload))
+ comment = next(c for c in self.comments if c["id"] == int(path.rsplit("/", 1)[-1]))
+ comment.update(payload)
+ return copy.deepcopy(comment)
+
+
+def github(monkeypatch):
+ module = adapter()
+ monkeypatch.setenv("SKILL_EVAL_TRUSTED_WORKFLOW_REF", WORKFLOW)
+ monkeypatch.setenv("SKILL_EVAL_TRUSTED_CALLER_BLOBS", BLOB)
+
+ def verify(raw, **kw):
+ assert raw == b"signed-receipt"
+ assert kw["evaluator_workflow"] + "@" + kw["evaluator_sha"] == WORKFLOW
+ assert kw["caller_workflow_path"] == ".github/workflows/skill-checks-all-tiers.yml"
+ return {"workflow_sha": MERGE}
+
+ monkeypatch.setattr(module, "verify_receipt", verify)
+ return module, GitHub()
+
+
+def test_github_creates_one_owned_comment_with_private_artifact_and_gate(github):
+ module, api = github
+ result = module.github_feedback(api, REPO, 123, 1)
+ assert result["comment_action"] == "created"
+ body = api.comments[0]["body"]
+ assert module.MARKER in body
+ assert "https://github.com/acme/skills/actions/runs/123/artifacts/21" in body
+ assert "Required tiers: Tier 1, Tier 2. Advisory tiers: Tier 3." in body
+ assert body.count("SKIPPED") == 3
+ assert body.count("[Report](") == 1
+ assert "(tier" not in body # archive members are not live web pages
+ assert module.github_feedback(api, REPO, 123, 1)["comment_action"] == "unchanged"
+ assert len(api.writes) == 1
+
+
[email protected]("platform", ["github", "gitlab"])
[email protected]("tier1_status", ["passed", "incomplete"])
+def test_trusted_feedback_keeps_paid_failures_advisory_and_tier1_blocking(request, platform, tier1_status):
+ from skillevaluator.models import ValidationResult
+ from skillevaluator.reporting.json_reporter import JSONReporter
+
+ module, api = request.getfixturevalue(platform)
+ payload = manifest(platform)
+ payload["tiers"][0].update(status=tier1_status, reason="Tier 1 validation")
+ extra = {}
+ if tier1_status == "passed":
+ native = JSONReporter().render_all(
+ [ValidationResult(validator_name="FORMAT", metadata={"gating": {"tier": 1, "blocking": True}})]
+ )
+ payload["tiers"][0]["skills"] = [
+ {
+ "path": "skills/demo",
+ "status": "passed",
+ "report_json": "tier1/skill-001/skillevaluator-tier1.json",
+ "report_html": "tier1/skill-001/skillevaluator-tier1.html",
+ }
+ ]
+ extra = {
+ "tier1/skill-001/skillevaluator-tier1.json": native,
+ "tier1/skill-001/skillevaluator-tier1.html": "<p>Tier 1 passed</p>",
+ }
+ payload["tiers"][1].update(status="failed", required=False, reason="Duplication check failed")
+ payload["tiers"][2].update(status="incomplete", required=False, reason="Paired evaluation timed out")
+ prefix = "skill-evaluator-results/" if platform == "gitlab" else ""
+ api.payload = archive(payload, {prefix + key: value for key, value in extra.items()}, prefix=prefix)
+
+ retained = module.read_results(api.payload, prefix=prefix)
+ assert retained["overall_passed"] is (tier1_status == "passed")
+ if platform == "github":
+ result = module.github_feedback(api, REPO, 123, 1)
+ body = api.comments[0]["body"]
+ report_url = "https://github.com/acme/skills/actions/runs/123/artifacts/21"
+ else:
+ result = module.gitlab_feedback(api, "https://gitlab.example/api/v4", "12", 123)
+ body = api.notes[0]["body"]
+ report_url = "https://gitlab.example/acme/skills/-/jobs/91/artifacts/download"
+ assert result["comment_action"] == "created"
+ assert f"Required gate: **{'Passed' if tier1_status == 'passed' else 'Not passed'}**" in body
+ assert tier1_status.upper() in body
+ assert "FAILED" in body and "Duplication check failed" in body
+ assert "INCOMPLETE" in body and "Paired evaluation timed out" in body
+ assert "Only Tier 1 blocks CI; Tier 2 and Tier 3 are advisory." in body
+ assert report_url in body
+
+
+def compact_archive(platform):
+ from skillevaluator.models import Finding, Severity, ValidationResult
+ from skillevaluator.reporting.json_reporter import JSONReporter
+
+ native = ValidationResult(validator_name="Security", metadata={"gating": {"tier": 1, "blocking": True}})
+ for severity, message in (
+ (Severity.LOW, "Missing optional metadata"),
+ (Severity.CRITICAL, "Exposed credential pattern"),
+ (Severity.HIGH, "Unsafe shell command"),
+ (Severity.INFO, "Static checks completed"),
+ ):
+ native.add_finding(
+ Finding(category="SECURITY", severity=severity, check_name="fixture", message=message, file_path="SKILL.md")
+ )
+ payload = manifest(platform)
+ for tier in payload["tiers"]:
+ tier.update(
+ status="failed" if tier["tier"] == 1 else "incomplete",
+ required=tier["tier"] == 1,
+ reason="Validation findings" if tier["tier"] == 1 else "Missing provider credentials",
+ skills=[
+ {
+ "path": "skills/demo",
+ "status": "failed" if tier["tier"] == 1 else "incomplete",
+ "report_json": None,
+ "report_html": None,
+ # Producer-supplied counters are not trusted comment evidence.
+ "metrics": {"issue_count": 0, "issue_count_known": True, "critical_count": 0},
+ }
+ ],
+ )
+ skill = payload["tiers"][0]["skills"][0]
+ skill.update(
+ report_json="tier1/skill-001/skillevaluator-tier1.json",
+ report_html="tier1/skill-001/skillevaluator-tier1.html",
+ )
+ prefix = "skill-evaluator-results/" if platform == "gitlab" else ""
+ extra = {
+ prefix + skill["report_json"]: JSONReporter().render_all([native]),
+ prefix + skill["report_html"]: "<p>Complete retained Tier 1 findings</p>",
+ }
+ return archive(payload, extra, prefix=prefix)
+
+
[email protected]("platform", ["github", "gitlab"])
+def test_trusted_comment_has_one_combined_report_link_and_compact_verified_skill_summary(request, platform):
+ module, api = request.getfixturevalue(platform)
+ api.payload = compact_archive(platform)
+ if platform == "github":
+ result = module.github_feedback(api, REPO, 123, 1)
+ body = api.comments[0]["body"]
+ report_url = "https://github.com/acme/skills/actions/runs/123/artifacts/21"
+ else:
+ result = module.gitlab_feedback(api, "https://gitlab.example/api/v4", "12", 123)
+ body = api.notes[0]["body"]
+ report_url = "https://gitlab.example/acme/skills/-/jobs/91/artifacts/download"
+ assert result["comment_action"] == "created"
+ assert body.count("| Skill |") == 1
+ assert body.count("[Report](" + report_url + ")") == 1
+ assert body.count(report_url) == 1
+ assert all(name in body for name in ("Static and Security Validation", "Deduplication", "Live Agent Evaluation"))
+ skill_row = next(line for line in body.splitlines() if line.startswith("| skills/demo |"))
+ assert "FAILED" in skill_row and "3 issues" in skill_row
+ assert "1 critical" in skill_row and "1 high" in skill_row
+ assert "Exposed credential pattern" in skill_row
+ assert skill_row.count("INCOMPLETE") == 2
+ assert skill_row.lower().count("issues unknown") == 2
+ assert "skill evidence" not in body and "In downloadable artifact" not in body
+ assert "Required gate: **Not passed**" in body
+
+
[email protected]("platform", ["github", "gitlab"])
+def test_feedback_issue_counts_are_derived_from_native_evidence_and_unknown_without_it(platform):
+ module = adapter()
+ prefix = "skill-evaluator-results/" if platform == "gitlab" else ""
+ retained = module.read_results(compact_archive(platform), prefix=prefix)
+ metrics = retained["tiers"][0]["skills"][0]["metrics"]
+ assert metrics["issue_count"] == 3
+ assert metrics["critical_count"] == 1
+ assert metrics["high_count"] == 1
+ assert metrics["issue_count_known"] is True
+ for tier in retained["tiers"][1:]:
+ assert tier["skills"][0].get("metrics", {}).get("issue_count_known", False) is False
+
+
+ "change", ["attempt", "revision", "expired", "duplicate", "caller", "workflow", "head", "foreign"]
+)
+def test_github_rejects_untrusted_or_stale_evidence_before_write(github, monkeypatch, change):
+ module, api = github
+ if change == "attempt":
+ api.run["run_attempt"] = 2
+ if change == "revision":
+ payload = manifest()
+ payload["commit"] = "e" * 40
+ api.payload = archive(payload)
+ if change == "expired":
+ api.artifacts[0]["expired"] = True
+ if change == "duplicate":
+ api.artifacts.append(copy.deepcopy(api.artifacts[0]))
+ if change == "caller":
+ monkeypatch.setenv("SKILL_EVAL_TRUSTED_CALLER_BLOBS", "f" * 40)
+ if change == "workflow":
+ api.run["referenced_workflows"][0]["sha"] = "e" * 40
+ if change == "head":
+ api.pr["head"]["sha"] = "e" * 40
+ if change == "foreign":
+ api.pr["head"]["repo"]["full_name"] = "fork/skills"
+ try:
+ result = module.github_feedback(api, REPO, 123, 1)
+ assert result["comment_action"] == "skipped"
+ except module.FeedbackError:
+ pass
+ assert not api.writes
+
+
+def test_github_rechecks_head_after_comments_and_preserves_human_marker(github):
+ module, api = github
+ api.comments = [{"id": 5, "body": module.MARKER, "user": {"login": "someone", "type": "User"}}]
+ api.flip_head_on_recheck = True
+ assert module.github_feedback(api, REPO, 123, 1)["comment_action"] == "skipped"
+ assert not api.writes
+
+
[email protected]("pulls", [[{"number": 7}], [{"number": 8}, {"number": 7}], []])
+def test_github_does_not_overwrite_newer_run_receipt(github, pulls):
+ module, api = github
+ # GitHub may omit a run's pull requests; it then stays bound by head and repository.
+ api.other_runs[124] = {**copy.deepcopy(api.run), "id": 124, "pull_requests": pulls}
+ api.comments = [
+ {
+ "id": 5,
+ "body": module.MARKER + "\n<!-- skillevaluator-all-tiers-run:124:1 -->",
+ "user": {"login": "github-actions[bot]", "type": "Bot"},
+ }
+ ]
+ assert module.github_feedback(api, REPO, 123, 1)["comment_action"] == "skipped"
+ assert not api.writes
+
+
+def _bot_comment(module, identifier, marker):
+ body = module.MARKER + f"\n<!-- skillevaluator-all-tiers-run:{marker} -->\nRequired gate: **Passed**"
+ return {"id": identifier, "body": body, "user": {"login": "github-actions[bot]", "type": "Bot"}}
+
+
+ "marker",
+ [
+ "99999999999:1", # no such run
+ "124:1", # another workflow's run
+ "125:1", # producer run for a different PR head
+ "126:1", # producer run from another event
+ "127:1", # fork pull-request run of the same head commit
+ "128:1", # producer run of another pull request on the same head
+ "129:1", # run whose head repository was deleted
+ "123:9", # attempt that never existed
+ ],
+)
+def test_github_overwrites_unverifiable_bot_marker_instead_of_deferring(github, marker):
+ module, api = github
+ api.other_runs[124] = {**copy.deepcopy(api.run), "id": 124, "path": ".github/workflows/other.yml"}
+ api.other_runs[125] = {**copy.deepcopy(api.run), "id": 125, "head_sha": "e" * 40}
+ api.other_runs[126] = {**copy.deepcopy(api.run), "id": 126, "event": "push"}
+ fork = {"full_name": "contributor/skills", "id": 99}
+ api.other_runs[127] = {**copy.deepcopy(api.run), "id": 127, "head_repository": fork, "pull_requests": []}
+ api.other_runs[128] = {**copy.deepcopy(api.run), "id": 128, "pull_requests": [{"number": 8}]}
+ api.other_runs[129] = {**copy.deepcopy(api.run), "id": 129, "head_repository": None}
+ api.comments = [_bot_comment(module, 5, marker)]
+ result = module.github_feedback(api, REPO, 123, 1)
+ assert result["comment_action"] == "updated"
+ assert [(method, path) for method, path, _ in api.writes] == [("PATCH", f"/repos/{REPO}/issues/comments/5")]
+ assert "<!-- skillevaluator-all-tiers-run:123:1 -->" in api.comments[0]["body"]
+ assert "Required gate: **Passed**" not in api.comments[0]["body"]
+
+
+def test_github_multiple_unverifiable_bot_markers_do_not_block_genuine_feedback(github):
+ module, api = github
+ api.comments = [
+ _bot_comment(module, 5, "99999999999:1"),
+ _bot_comment(module, 6, "99999999998:1"),
+ {**_bot_comment(module, 7, "1:1"), "body": module.MARKER + "\nno producer receipt"},
+ ]
+ assert module.github_feedback(api, REPO, 123, 1)["comment_action"] == "updated"
+ assert [path for _, path, _ in api.writes] == [f"/repos/{REPO}/issues/comments/5"]
+ # A verified genuine comment is preferred over leftover unverifiable ones.
+ assert module.github_feedback(api, REPO, 123, 1)["comment_action"] == "unchanged"
+ assert len(api.writes) == 1
+
+
+def test_github_marker_verification_does_not_hide_api_failures(github):
+ import urllib.error
+
+ module, api = github
+ api.comments = [_bot_comment(module, 5, "124:1")]
+ original = api.get
+
+ def unavailable(path):
+ if path.endswith("/actions/runs/124"):
+ raise urllib.error.HTTPError("https://api.github.com" + path, 503, "Unavailable", {}, None)
+ return original(path)
+
+ api.get = unavailable
+ with pytest.raises(urllib.error.HTTPError):
+ module.github_feedback(api, REPO, 123, 1)
+ assert not api.writes
+
+
+ "change",
+ ["fork", "deleted-fork", "rerun-started", "rerun-completed", "rerun-in-progress"],
+)
+def test_github_skips_fork_and_superseded_producer_runs_without_failing(github, change):
+ module, api = github
+ if change == "fork":
+ api.run["head_repository"] = {"full_name": "contributor/skills", "id": 99}
+ # Fork runs have no OIDC token, so no provenance receipt is uploaded.
+ api.artifacts = [a for a in api.artifacts if "provenance" not in a["name"]]
+ elif change == "deleted-fork":
+ api.run["head_repository"] = None
+ elif change == "rerun-started":
+ api.run.update(run_attempt=2, status="in_progress")
+ elif change == "rerun-completed":
+ api.run["run_attempt"] = 2
+ else:
+ api.run["status"] = "in_progress"
+ result = module.github_feedback(api, REPO, 123, 1)
+ assert result["comment_action"] == "skipped"
+ assert not api.writes and not api.downloads
+ assert not any("/artifacts" in path for path in api.gets)
+
+
+def test_github_feedback_job_skips_fork_pull_request_runs():
+ import yaml
+
+ root = Path(__file__).resolve().parents[2]
+ workflow = yaml.safe_load((root / ".github/workflows/feedback-all-tiers.yml").read_text())
+ condition = workflow["jobs"]["feedback"]["if"]
+ assert "github.event.workflow_run.event == 'pull_request'" in condition
+ assert "github.event.workflow_run.head_repository.full_name == github.repository" in condition
+
+
[email protected]("name", ["../ci-results.json", "/ci-results.json", "tier1/../../secret.json", "evil\\file"])
+def test_zip_paths_are_rejected_without_extraction(name):
+ module = adapter()
+ with pytest.raises(module.FeedbackError):
+ module.read_results(archive(extra={name: "{}"}))
+
+
+def test_zip_symlinks_duplicate_json_and_missing_native_evidence_are_rejected():
+ module = adapter()
+ output = io.BytesIO()
+ with zipfile.ZipFile(output, "w") as zipped:
+ link = zipfile.ZipInfo("ci-results.json")
+ link.external_attr = (stat.S_IFLNK | 0o777) << 16
+ zipped.writestr(link, json.dumps(manifest()))
+ with pytest.raises(module.FeedbackError):
+ module.read_results(output.getvalue())
+ 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",
+ }
+ ],
+ )
+ with pytest.raises(module.FeedbackError):
+ module.read_results(archive(payload))
+ output = io.BytesIO()
+ with zipfile.ZipFile(output, "w") as zipped:
+ zipped.writestr("ci-results.json", '{"schema_version":1,"schema_version":1}')
+ with pytest.raises(module.FeedbackError):
+ module.read_results(output.getvalue())
+
+
+def config_content():
+ import yaml
+
+ root = {
+ "include": [
+ {
+ "remote": "https://raw.githubusercontent.com/NVIDIA/SkillEvaluator/"
+ + "c" * 40
+ + "/ci/gitlab/all-tiers.yml"
+ },
+ {
+ "local": ".gitlab/skill-feedback.yml",
+ "rules": [
+ {
+ "if": '$CI_PIPELINE_SOURCE == "pipeline" && $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH && $SKILL_EVAL_FEEDBACK == "true"'
+ }
+ ],
+ },
+ ]
+ }
+ return {"encoding": "base64", "content": base64.b64encode(yaml.safe_dump(root).encode()).decode()}
+
+
+class GitLab:
+ def __init__(self):
+ self.project = {
+ "id": 12,
+ "path_with_namespace": REPO,
+ "default_branch": "main",
+ "ci_config_path": None,
+ "web_url": "https://gitlab.example/acme/skills",
+ }
+ self.pipeline = {"id": 123, "sha": SHA, "ref": "feature", "source": "merge_request_event", "status": "success"}
+ self.publisher = {"id": 456, "sha": MERGE, "ref": "main", "source": "pipeline", "status": "running"}
+ self.job = {
+ "id": 91,
+ "name": "skill-evaluation-aggregate",
+ "status": "success",
+ "retried": False,
+ "pipeline": {"id": 123},
+ "commit": {"id": SHA},
+ "ref": "feature",
+ "artifacts_file": {"filename": "skill-evaluator-results-123-91.zip", "size": 1000},
+ }
+ self.mr = {
+ "iid": 7,
+ "state": "opened",
+ "source_project_id": 12,
+ "target_project_id": 12,
+ "sha": SHA,
+ "source_branch": "feature",
+ "head_pipeline": {"id": 123},
+ }
+ self.request_job = {
+ "id": 93,
+ "name": "skill-evaluation-request-feedback",
+ "status": "success",
+ "retried": False,
+ "pipeline": {"id": 123},
+ "commit": {"id": SHA},
+ "ref": "feature",
+ }
+ self.relationship = {
+ "project": {
+ "fullPath": REPO,
+ "pipeline": {
+ "id": "gid://gitlab/Ci::Pipeline/456",
+ "project": {"fullPath": REPO},
+ "sourceJob": {"id": "gid://gitlab/Ci::Build/93"},
+ "upstream": {
+ "id": "gid://gitlab/Ci::Pipeline/123",
+ "project": {"fullPath": REPO},
+ "mergeRequest": {"iid": "7", "sourceProjectId": 12, "targetProjectId": 12},
+ },
+ },
+ }
+ }
+ self.current_request_id = 93
+ self.notes = []
+ self.writes = []
+ self.payload = archive(manifest("gitlab"), prefix="skill-evaluator-results/")
+ self.user = {"id": 77, "username": "project_12_bot_abc", "bot": True}
+ self.source_blob = BLOB
+ self.flip_head_on_recheck = False
+ self.head_checks = 0
+ self.variables = [
+ {"key": "SKILL_EVAL_FEEDBACK", "value": "true", "variable_type": "env_var"},
+ {"key": "SKILL_EVAL_SOURCE_PIPELINE_ID", "value": "123", "variable_type": "env_var"},
+ ]
+
+ def get(self, path):
+ if path == "/user":
+ return copy.deepcopy(self.user)
+ if path in {"/projects/acme%2Fskills", "/projects/12"}:
+ return copy.deepcopy(self.project)
+ root = "/projects/12"
+ if path == root + "/pipelines/123":
+ return copy.deepcopy(self.pipeline)
+ if path == root + "/pipelines/456":
+ return copy.deepcopy(self.publisher)
+ if path == root + "/pipelines/456/variables":
+ return copy.deepcopy(self.variables)
+ if path == root + "/pipelines/123/variables":
+ return []
+ if path == root + "/repository/branches/main":
+ return {"name": "main", "protected": True, "commit": {"id": MERGE}}
+ if path == root + "/jobs/92":
+ return {
+ "id": 92,
+ "name": "skill-evaluation-feedback",
+ "status": "running",
+ "ref": "main",
+ "pipeline": {"id": 456},
+ "commit": {"id": MERGE},
+ }
+ if path == root + "/jobs/93":
+ return copy.deepcopy(self.request_job)
+ if path.startswith(root + "/pipelines/123/jobs?"):
+ request = {**self.request_job, "id": self.current_request_id}
+ return [copy.deepcopy(self.job), copy.deepcopy(request)]
+ if path == root + "/repository/files/.gitlab-ci.yml?ref=" + SHA:
+ return {"file_path": ".gitlab-ci.yml", "blob_id": self.source_blob, "commit_id": SHA, **config_content()}
+ if path == root + "/repository/files/.gitlab-ci.yml?ref=" + MERGE:
+ return {"file_path": ".gitlab-ci.yml", "blob_id": BLOB, "commit_id": MERGE, **config_content()}
+ if path == root + "/merge_requests/7":
+ mr = copy.deepcopy(self.mr)
+ self.head_checks += 1
+ if self.flip_head_on_recheck and self.head_checks > 1:
+ mr["sha"] = "e" * 40
+ return mr
+ if path.startswith(root + "/merge_requests/7/notes?"):
+ return copy.deepcopy(self.notes)
+ if path.startswith(root + "/merge_requests/7/notes/"):
+ return copy.deepcopy(next(n for n in self.notes if n["id"] == int(path.rsplit("/", 1)[-1])))
+ raise AssertionError(path)
+
+ def graphql(self, query, variables):
+ assert "sourceJob" in query and "upstream" in query
+ assert "mergeRequest{iid sourceProjectId targetProjectId}" in query
+ assert variables == {"project": REPO, "pipeline": "gid://gitlab/Ci::Pipeline/456"}
+ return copy.deepcopy(self.relationship)
+
+ def download_artifact(self, job):
+ assert job == 91
+ return self.payload
+
+ def post(self, path, payload):
+ self.writes.append(("POST", path, payload))
+ note = {"id": 51, "body": payload["body"], "author": copy.deepcopy(self.user)}
+ self.notes.append(note)
+ return copy.deepcopy(note)
+
+ def put(self, path, payload):
+ self.writes.append(("PUT", path, payload))
+ note = next(n for n in self.notes if n["id"] == int(path.rsplit("/", 1)[-1]))
+ note.update(payload)
+ return copy.deepcopy(note)
+
+
+def gitlab(monkeypatch):
+ module = adapter()
+
+ def verify(api_url, token):
+ assert api_url == "https://gitlab.example/api/v4" and token == "signed-job-token"
+ return {"project_id": "12", "pipeline_id": "456", "job_id": "92", "ref": "main", "sha": MERGE}
+
+ monkeypatch.setenv("SKILL_EVAL_GITLAB_ID_TOKEN", "signed-job-token")
+ monkeypatch.setattr(module, "verify_gitlab_job", verify, raising=False)
+ return module, GitLab()
+
+
+def test_gitlab_binds_protected_downstream_source_job_config_head_job_and_bot(gitlab):
+ module, api = gitlab
+ result = module.gitlab_feedback(api, "https://gitlab.example/api/v4", "acme/skills", 123)
+ assert result["comment_action"] == "created"
+ body = api.notes[0]["body"]
+ assert "https://gitlab.example/acme/skills/-/jobs/91/artifacts/download" in body
+ assert "https://gitlab.example/acme/skills/-/pipelines/123" in body
+ assert module.gitlab_feedback(api, "https://gitlab.example/api/v4", "12", 123)["comment_action"] == "unchanged"
+ assert len(api.writes) == 1
+
+
[email protected]("action", ["created", "updated"])
+def test_gitlab_sends_note_without_the_final_lf_removed_by_server(gitlab, monkeypatch, action):
+ module, api = gitlab
+ if action == "updated":
+ module.gitlab_feedback(api, "https://gitlab.example/api/v4", "12", 123)
+ api.notes[0]["body"] += "\nold content"
+ api.writes.clear()
+
+ def normalize_write(write):
+ def store(path, payload):
+ response = write(path, payload)
+ note = next(note for note in api.notes if note["id"] == response["id"])
+ note["body"] = note["body"].removesuffix("\n")
+ return {**response, "body": note["body"]}
+
+ return store
+
+ monkeypatch.setattr(api, "post", normalize_write(api.post))
+ monkeypatch.setattr(api, "put", normalize_write(api.put))
+ result = module.gitlab_feedback(api, "https://gitlab.example/api/v4", "12", 123)
+ assert result["comment_action"] == action
+ assert api.writes[0][2]["body"] == api.notes[0]["body"]
+ assert not api.notes[0]["body"].endswith("\n")
+ assert module.gitlab_feedback(api, "https://gitlab.example/api/v4", "12", 123)["comment_action"] == "unchanged"
+ assert len(api.writes) == 1
+
+
+ "payload",
+ [
+ '{"id":"12","ref":"main","variables":{"SKILL_EVAL_FEEDBACK":"true","SKILL_EVAL_SOURCE_PIPELINE_ID":"123"}}',
+ "opaque content: not JSON; $(do-not-execute)",
+ ],
+)
+def test_gitlab_accepts_server_added_file_trigger_payload_without_using_its_contents(gitlab, payload):
+ module, api = gitlab
+ api.variables.append({"key": "TRIGGER_PAYLOAD", "value": payload, "variable_type": "file"})
+ result = module.gitlab_feedback(api, "https://gitlab.example/api/v4", "12", 123)
+ assert result["comment_action"] == "created"
+ assert payload not in api.notes[0]["body"]
+
+
+ "change",
+ [
+ "payload-env",
+ "payload-type-missing",
+ "payload-nonstring",
+ "payload-oversized",
+ "payload-duplicate",
+ "selector-duplicate",
+ "selector-file",
+ "selector-type-missing",
+ "extra-env",
+ "feedback-value",
+ "source-value",
+ "invalid-key",
+ ],
+)
+def test_gitlab_rejects_extra_duplicate_or_mistyped_trigger_variables(gitlab, change):
+ module, api = gitlab
+ payload = {"key": "TRIGGER_PAYLOAD", "value": "opaque server payload", "variable_type": "file"}
+ api.variables.append(payload)
+ if change == "payload-env":
+ payload["variable_type"] = "env_var"
+ elif change == "payload-type-missing":
+ payload.pop("variable_type")
+ elif change == "payload-nonstring":
+ payload["value"] = {"ref": "main"}
+ elif change == "payload-oversized":
+ payload["value"] = "x" * (64 * 1024 + 1)
+ elif change == "payload-duplicate":
+ api.variables.append(copy.deepcopy(payload))
+ elif change == "selector-duplicate":
+ api.variables[-1] = copy.deepcopy(api.variables[0])
+ elif change == "selector-file":
+ api.variables[0]["variable_type"] = "file"
+ api.variables.pop()
+ elif change == "selector-type-missing":
+ api.variables[0].pop("variable_type")
+ api.variables.pop()
+ elif change == "extra-env":
+ api.variables[-1] = {"key": "CI_PIPELINE_ID", "value": "123", "variable_type": "env_var"}
+ elif change == "feedback-value":
+ api.variables[0]["value"] = "false"
+ elif change == "source-value":
+ api.variables[1]["value"] = "124"
+ else:
+ payload["key"] = []
+ with pytest.raises(module.FeedbackError, match="forwarded variables"):
+ module.gitlab_feedback(api, "https://gitlab.example/api/v4", "12", 123)
+ assert not api.writes
+
+
[email protected]("ref", ["ci/skillevaluator-all-tiers-setup", "refs/merge-requests/7/head"])
+def test_gitlab_accepts_current_mr_branch_or_exact_detached_head_ref(gitlab, ref):
+ module, api = gitlab
+ api.mr["source_branch"] = "ci/skillevaluator-all-tiers-setup"
+ api.pipeline["ref"] = api.job["ref"] = api.request_job["ref"] = ref
+ result = module.gitlab_feedback(api, "https://gitlab.example/api/v4", "12", 123)
+ assert result["comment_action"] == "created"
+ assert len(api.writes) == 1
+
+
+ "ref",
+ [
+ "refs/merge-requests/8/head",
+ "refs/merge-requests/7/merge",
+ "refs/merge-requests/07/head",
+ "refs/merge-requests/7/head/other",
+ "other-branch",
+ ],
+)
+def test_gitlab_rejects_unrelated_or_non_head_mr_producer_refs(gitlab, ref):
+ module, api = gitlab
+ api.pipeline["ref"] = api.job["ref"] = api.request_job["ref"] = ref
+ result = module.gitlab_feedback(api, "https://gitlab.example/api/v4", "12", 123)
+ assert result["comment_action"] == "skipped"
+ assert not api.writes
+
+
[email protected]("branch", [None, "", ["feature"]])
+def test_gitlab_detached_head_ref_still_requires_a_source_branch(gitlab, branch):
+ module, api = gitlab
+ api.pipeline["ref"] = api.job["ref"] = api.request_job["ref"] = "refs/merge-requests/7/head"
+ api.mr["source_branch"] = branch
+ result = module.gitlab_feedback(api, "https://gitlab.example/api/v4", "12", 123)
+ assert result["comment_action"] == "skipped"
+ assert not api.writes
+
+
[email protected]("change", ["head", "head-pipeline", "job-ref", "recheck"])
+def test_gitlab_detached_head_ref_keeps_exact_current_producer_guards(gitlab, change):
+ module, api = gitlab
+ api.pipeline["ref"] = api.job["ref"] = api.request_job["ref"] = "refs/merge-requests/7/head"
+ if change == "head":
+ api.mr["sha"] = "e" * 40
+ elif change == "head-pipeline":
+ api.mr["head_pipeline"]["id"] = 124
+ elif change == "job-ref":
+ api.job["ref"] = "refs/merge-requests/8/head"
+ else:
+ api.flip_head_on_recheck = True
+ if change == "job-ref":
+ with pytest.raises(module.FeedbackError, match="aggregate job artifact identity"):
+ module.gitlab_feedback(api, "https://gitlab.example/api/v4", "12", 123)
+ else:
+ result = module.gitlab_feedback(api, "https://gitlab.example/api/v4", "12", 123)
+ assert result["comment_action"] == "skipped"
+ assert not api.writes
+
+
+def test_gitlab_accepts_running_source_when_request_job_and_aggregate_are_bound(gitlab):
+ module, api = gitlab
+ api.pipeline["status"] = api.request_job["status"] = "running"
+ result = module.gitlab_feedback(api, "https://gitlab.example/api/v4", "12", 123)
+ assert result["comment_action"] == "created"
+
+
[email protected]("status", ["manual", "pending", "created", "waiting_for_resource", "preparing", "scheduled"])
+def test_gitlab_accepts_unfinished_source_pipeline_when_other_consumer_jobs_remain(gitlab, status):
+ module, api = gitlab
+ # Merged consumer CI can leave later or blocking manual jobs after the
+ # finished aggregate and request jobs, which carry the bound evidence.
+ api.pipeline["status"] = status
+ result = module.gitlab_feedback(api, "https://gitlab.example/api/v4", "12", 123)
+ assert result["comment_action"] == "created"
+
+
+def test_gitlab_uses_persisted_graphql_mr_without_unsupported_pipeline_rest_endpoint(gitlab):
+ import urllib.error
+
+ module, api = gitlab
+ original = api.get
+
+ def historical_api(path):
+ if path == "/projects/12/pipelines/123/merge_requests":
+ raise urllib.error.HTTPError("https://gitlab.example/api/v4" + path, 404, "Not found", {}, None)
+ return original(path)
+
+ api.get = historical_api
+ result = module.gitlab_feedback(api, "https://gitlab.example/api/v4", "12", 123)
+ assert result["comment_action"] == "created"
+
+
+ "linked_mr",
+ [
+ None,
+ [],
+ {},
+ {"iid": 7, "sourceProjectId": 12, "targetProjectId": 12},
+ {"iid": "0", "sourceProjectId": 12, "targetProjectId": 12},
+ {"iid": "07", "sourceProjectId": 12, "targetProjectId": 12},
+ {"iid": "-7", "sourceProjectId": 12, "targetProjectId": 12},
+ {"iid": "7/head", "sourceProjectId": 12, "targetProjectId": 12},
+ {"iid": "9223372036854775808", "sourceProjectId": 12, "targetProjectId": 12},
+ {"iid": "7", "sourceProjectId": 13, "targetProjectId": 12},
+ {"iid": "7", "sourceProjectId": 12, "targetProjectId": 13},
+ {"iid": "7", "sourceProjectId": "12", "targetProjectId": 12},
+ {"iid": "7", "sourceProjectId": 12, "targetProjectId": "12"},
+ ],
+)
+def test_gitlab_rejects_missing_malformed_or_cross_project_persisted_mr(gitlab, linked_mr):
+ module, api = gitlab
+ api.relationship["project"]["pipeline"]["upstream"]["mergeRequest"] = linked_mr
+ with pytest.raises(module.FeedbackError, match="linked same-project merge request"):
+ module.gitlab_feedback(api, "https://gitlab.example/api/v4", "12", 123)
+ assert not api.writes
+
+
+ "change",
+ [
+ "project",
+ "publisher",
+ "publisher-project",
+ "upstream",
+ "upstream-project",
+ "missing-job",
+ "bridge-job",
+ "job-name",
+ "job-pipeline",
+ "job-sha",
+ "job-ref",
+ "retried",
+ "not-current",
+ "aggregate-running",
+ ],
+)
+def test_gitlab_api_trigger_requires_server_bound_current_request_job(gitlab, change):
+ module, api = gitlab
+ relation = api.relationship["project"]["pipeline"]
+ if change == "project":
+ api.relationship["project"]["fullPath"] = "other/project"
+ elif change == "publisher":
+ relation["id"] = "gid://gitlab/Ci::Pipeline/457"
+ elif change == "publisher-project":
+ relation["project"]["fullPath"] = "other/project"
+ elif change == "upstream":
+ relation["upstream"]["id"] = "gid://gitlab/Ci::Pipeline/124"
+ elif change == "upstream-project":
+ relation["upstream"]["project"]["fullPath"] = "other/project"
+ elif change == "missing-job":
+ relation["sourceJob"] = None
+ elif change == "bridge-job":
+ relation["sourceJob"]["id"] = "gid://gitlab/Ci::Bridge/93"
+ elif change == "job-name":
+ api.request_job["name"] = "untrusted-job"
+ elif change == "job-pipeline":
+ api.request_job["pipeline"]["id"] = 124
+ elif change == "job-sha":
+ api.request_job["commit"]["id"] = "e" * 40
+ elif change == "job-ref":
+ api.request_job["ref"] = "other"
+ elif change == "retried":
+ api.request_job["retried"] = True
+ elif change == "not-current":
+ api.current_request_id = 94
+ else:
+ api.job["status"] = "running"
+ with pytest.raises(module.FeedbackError):
+ module.gitlab_feedback(api, "https://gitlab.example/api/v4", "12", 123)
+ assert not api.writes
+
+
+def test_gitlab_rechecks_request_job_after_artifact_download(gitlab):
+ module, api = gitlab
+ original = api.download_artifact
+
+ def replaced(job):
+ payload = original(job)
+ api.current_request_id = 94
+ return payload
+
+ api.download_artifact = replaced
+ with pytest.raises(module.FeedbackError):
+ module.gitlab_feedback(api, "https://gitlab.example/api/v4", "12", 123)
+ assert not api.writes
+
+
+ "change",
+ [
+ "relationship",
+ "producer-config",
+ "ref",
+ "fork",
+ "head",
+ "job-ref",
+ "job-name",
+ "retried",
+ "head-pipeline",
+ "bot",
+ "variable-override",
+ ],
+)
+def test_gitlab_rejects_forged_producer_or_privileged_context(gitlab, change):
+ module, api = gitlab
+ if change == "relationship":
+ api.relationship["project"]["pipeline"]["upstream"]["id"] = "gid://gitlab/Ci::Pipeline/124"
+ if change == "producer-config":
+ api.source_blob = "e" * 40
+ if change == "ref":
+ api.publisher["ref"] = "feature"
+ if change == "fork":
+ api.mr["source_project_id"] = 13
+ if change == "head":
+ api.mr["sha"] = "e" * 40
+ if change == "job-ref":
+ api.job["ref"] = "other"
+ if change == "job-name":
+ api.job["name"] = "evil-artifact"
+ if change == "retried":
+ api.job["retried"] = True
+ if change == "head-pipeline":
+ api.mr["head_pipeline"]["id"] = 124
+ if change == "bot":
+ api.user["bot"] = False
+ if change == "variable-override":
+ api.variables.append({"key": "CI_PIPELINE_ID", "value": "123"})
+ try:
+ result = module.gitlab_feedback(api, "https://gitlab.example/api/v4", "12", 123)
+ assert result["comment_action"] == "skipped"
+ except module.FeedbackError:
+ pass
+ assert not api.writes
+
+
+def test_gitlab_rechecks_head_and_ignores_human_or_other_bot_marker(gitlab):
+ module, api = gitlab
+ api.notes = [{"id": 5, "body": module.MARKER, "author": {"id": 78, "bot": True}}]
+ api.flip_head_on_recheck = True
+ assert module.gitlab_feedback(api, "https://gitlab.example/api/v4", "12", 123)["comment_action"] == "skipped"
+ assert not api.writes
+
+
+ "url",
+ [
+ "http://gitlab.example/api/v4",
+ "https://gitlab.example.evil/api/v4",
+ "https://u:[email protected]/api/v4",
+ "https://gitlab.example/api/v4/../user",
+ ],
+)
+def test_gitlab_api_blocks_unsafe_urls_and_cross_host_redirects(url):
+ module = adapter()
+ if "example.evil" in url:
+ api = module.GitLabAPI("https://gitlab.example/api/v4", "12", "secret")
+ with pytest.raises(module.FeedbackError):
+ api.get(url)
+ else:
+ with pytest.raises(module.FeedbackError):
+ module.GitLabAPI(url, "12", "secret")
+
+
+def test_gitlab_rejects_source_pipeline_runtime_variable_overrides(gitlab):
+ module, api = gitlab
+ original = api.get
+
+ def overridden(path):
+ if path == "/projects/12/pipelines/123/variables":
+ return [{"key": "SKILL_EVAL_TOOLS_REF", "value": "e" * 40}]
+ return original(path)
+
+ api.get = overridden
+ with pytest.raises(module.FeedbackError):
+ module.gitlab_feedback(api, "https://gitlab.example/api/v4", "12", 123)
+ assert not api.writes
+
+
+def test_native_pass_requires_matching_retained_tier_evidence():
+ module = adapter()
+ from skillevaluator.models import ValidationResult
+ from skillevaluator.reporting.json_reporter import JSONReporter
+
+ result = ValidationResult(validator_name="FORMAT", metadata={"gating": {"tier": 1, "blocking": True}})
+ native = JSONReporter().render_all([result])
+ 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",
+ }
+ ],
+ )
+ extra = {
+ "tier1/skill-001/skillevaluator-tier1.json": native,
+ "tier1/skill-001/skillevaluator-tier1.html": '<script>throw "NEVER EXECUTE"</script>',
+ }
+ assert module.read_results(archive(payload, extra))["tiers"][0]["status"] == "passed"
+ forged = json.loads(native)
+ forged["results"][0]["passed"] = False
+ extra["tier1/skill-001/skillevaluator-tier1.json"] = json.dumps(forged)
+ with pytest.raises(module.FeedbackError):
+ module.read_results(archive(payload, extra))
+
+
+def _tier3_neutral_archive(status, *, complete=True, blocking=True):
+ from tests.ci.test_tier3_execution_complete import complete_report
+
+ from skillevaluator.models import ValidationResult
+ from skillevaluator.reporting.json_reporter import JSONReporter
+
+ payload = complete_report()["tier3"]
+ payload["verdict"] = payload["summary"]["verdict"] = "neutral"
+ if not complete:
+ payload.pop("run_id")
+ payload["summary"].pop("run_id")
+ result = ValidationResult(
+ validator_name="AGENT_EVAL",
+ passed=True,
+ metadata={"gating": {"tier": 3, "blocking": blocking}, "agent_eval": payload},
+ )
+ native = JSONReporter(expected_skill_name="demo").render_all([result])
+ document = manifest()
+ document["tiers"][2].update(
+ status=status,
+ skills=[
+ {
+ "path": "skills/demo",
+ "status": status,
+ "report_json": "tier3/skill-001/skillevaluator-tier3.json",
+ "report_html": "tier3/skill-001/skillevaluator-tier3.html",
+ }
+ ],
+ )
+ document["tiers"][2].pop("reason")
+ return archive(
+ document,
+ {
+ "tier3/skill-001/skillevaluator-tier3.json": native,
+ "tier3/skill-001/skillevaluator-tier3.html": "<p>Tier 3</p>",
+ },
+ )
+
+
[email protected]("blocking", [True, False])
[email protected](("complete", "status"), [(True, "neutral"), (True, "incomplete"), (False, "incomplete")])
+def test_tier3_neutral_evidence_accepts_recorded_neutral_or_producer_incomplete_downgrade(blocking, complete, status):
+ module = adapter()
+ retained = module.read_results(_tier3_neutral_archive(status, complete=complete, blocking=blocking))
+ assert retained["tiers"][2]["skills"][0]["status"] == status
+
+
[email protected](("complete", "status"), [(True, "passed"), (False, "neutral"), (False, "passed")])
+def test_tier3_neutral_evidence_is_never_promoted(complete, status):
+ module = adapter()
+ with pytest.raises(module.FeedbackError):
+ module.read_results(_tier3_neutral_archive(status, complete=complete))
+
+
+def _retained_diagnostics(tmp_path, trials):
+ """Members of one real worker-diagnostics tree for a failed Harbor run."""
+ from ci.diagnostics import retain_diagnostics
+
+ raw, leaf = tmp_path / "raw", tmp_path / "leaf"
+ for number in range(trials):
+ trial = raw / f"harbor/job/trial-{number:03d}"
+ (trial / "agent/setup").mkdir(parents=True)
+ (trial / "trial.log").write_text("trial started\n")
+ (trial / "exception.txt").write_text("RuntimeError: startup failed\n")
+ (trial / "agent/setup/install-agent-runtime.failed.log").write_text("install failed\n")
+ (tmp_path / "command.log").write_text("command\n")
+ retain_diagnostics(raw, leaf, set(), command_log=tmp_path / "command.log")
+ paths = sorted((leaf / "diagnostics").rglob("*"))
+ files = [p.relative_to(leaf).as_posix() for p in paths if p.is_file()]
+ folders = ["diagnostics/"] + [p.relative_to(leaf).as_posix() + "/" for p in paths if p.is_dir()]
+ return files, folders
+
+
+def _aggregate_layout(skills, *, directories, diagnostics=((), ())):
+ """Member names of a full three-tier aggregate as its producers retain them.
+
+ ``diagnostics`` holds one worker-diagnostics tree (files, folders) retained
+ for every Tier 2 and Tier 3 skill and for a failed Tier 2 catalog.
+ """
+ prefix = "skill-evaluator-results/" if directories else ""
+ names = [
+ "ci-results.json",
+ "index.html",
+ "summary.md",
+ "tier1/summary.json",
+ "tier1/index.html",
+ "tier2/ci-tier.json",
+ "tier3/ci-tier.json",
+ ]
+ folders = ["", "tier1/", "tier2/", "tier3/"]
+ for number in range(1, skills + 1):
+ leaf = f"skill-{number:03d}"
+ tier1 = ("json", "html", "md", "sarif.json")
+ names += [f"tier1/{leaf}/skillevaluator-tier1.{ext}" for ext in tier1]
+ names += [f"tier1/{leaf}/stdout.log", f"tier1/{leaf}/stderr.log"]
+ for tier in (2, 3):
+ names += [f"tier{tier}/{leaf}/skillevaluator-tier{tier}.{ext}" for ext in ("json", "html", "md")]
+ folders += [f"tier{tier}/{leaf}/" for tier in (1, 2, 3)]
+ files, nested = diagnostics
+ for root in [f"tier{tier}/skill-{n:03d}/" for n in range(1, skills + 1) for tier in (2, 3)] + ["tier2/catalog/"]:
+ if files:
+ names += [root + name for name in files]
+ folders += ([root] if root == "tier2/catalog/" else []) + [root + name for name in nested]
+ output = io.BytesIO()
+ with zipfile.ZipFile(output, "w") as zipped:
+ for folder in folders if directories else []:
+ zipped.writestr(prefix + folder, "")
+ for name in names:
+ zipped.writestr(prefix + name, json.dumps(manifest()) if name == "ci-results.json" else "{}")
+ return output.getvalue(), prefix, len(zipped.infolist())
+
+
[email protected]("directories", [False, True])
+def test_member_limit_admits_the_documented_maximum_skill_count_on_every_platform(directories):
+ from ci import run_tier1, select_changed_skills
+
+ module = adapter()
+ assert module.MAX_SKILLS == run_tier1.MAX_SKILLS == select_changed_skills.MAX_SELECTED_SKILLS
+ raw, prefix, members = _aggregate_layout(module.MAX_SKILLS, directories=directories)
+ assert members <= module.MAX_FILES
+ assert module.read_results(raw, prefix=prefix)["tiers"][0]["status"] == "skipped"
+
+
[email protected]("trials", [24, 40])
[email protected]("directories", [False, True])
+def test_member_limit_admits_worker_diagnostics_at_the_per_root_caps(tmp_path, monkeypatch, directories, trials):
+ from ci import diagnostics
+
+ module = adapter()
+ # The bound covers any layout up to the per-root file cap, not only the
+ # few trials the producer keeps today, so lift the trial caps here.
+ monkeypatch.setattr(diagnostics, "MAX_TRIALS_PER_JOB", trials)
+ monkeypatch.setattr(diagnostics, "MAX_TRIALS", trials)
+ files, folders = _retained_diagnostics(tmp_path, trials)
+ # 40 trials reach the producer's own retained-file cap.
+ assert "diagnostics/index.json" in files
+ assert (len(files) == diagnostics.MAX_FILES + 1) is (trials == 40)
+ raw, prefix, members = _aggregate_layout(module.MAX_SKILLS, directories=directories, diagnostics=(files, folders))
+ assert members > module.MAX_FILES
+ assert module.read_results(raw, prefix=prefix)["tiers"][0]["status"] == "skipped"
+ assert module.DIAGNOSTIC_FILES == diagnostics.MAX_FILES + 1
+ assert module.MAX_DIAGNOSTIC_BYTES == module.DIAGNOSTIC_ROOTS * (
+ diagnostics.MAX_TOTAL_BYTES + diagnostics.MAX_FILE_BYTES
+ )
+
+
+def test_worker_diagnostic_bytes_do_not_consume_the_report_expansion_limit():
+ from ci import diagnostics
+
+ module = adapter()
+ output = io.BytesIO()
+ log = b"startup failed\n" * (diagnostics.MAX_FILE_BYTES // 15)
+ roots = module.MAX_BYTES // diagnostics.MAX_TOTAL_BYTES + 1
+ with zipfile.ZipFile(output, "w", zipfile.ZIP_DEFLATED) as zipped:
+ zipped.writestr("ci-results.json", json.dumps(manifest()))
+ for number in range(1, roots + 1):
+ for trial in range(diagnostics.MAX_TOTAL_BYTES // len(log)):
+ zipped.writestr(f"tier3/skill-{number:03d}/diagnostics/harbor/job/t{trial}/trial.log", log)
+ declared = sum(entry.file_size for entry in zipped.infolist())
+ assert declared > module.MAX_BYTES and len(output.getvalue()) <= module.MAX_BYTES
+ assert module.read_results(output.getvalue())["tiers"][0]["status"] == "skipped"
+
+
+ "name",
+ [
+ "tier3/skill-001/diagnostics/harbor/job/trial/trial.log",
+ "tier2/skill-001/diagnostics/",
+ "tier2/catalog/diagnostics/command.log",
+ ],
+)
+def test_worker_diagnostics_keep_their_own_member_and_byte_bounds(monkeypatch, name):
+ module = adapter()
+
+ def payload(members, size):
+ output = io.BytesIO()
+ with zipfile.ZipFile(output, "w") as zipped:
+ zipped.writestr("ci-results.json", json.dumps(manifest()))
+ for number in range(members):
+ zipped.writestr(f"{name}{number}" + ("/" if name.endswith("/") else ""), b"x" * size)
+ return output.getvalue()
+
+ monkeypatch.setattr(module, "MAX_FILES", 1)
+ monkeypatch.setattr(module, "MAX_DIAGNOSTIC_MEMBERS", 3)
+ monkeypatch.setattr(module, "MAX_DIAGNOSTIC_BYTES", 30)
+ assert module.read_results(payload(3, 10))["tiers"][0]["status"] == "skipped"
+ for members, size in ((4, 0), (3, 11)):
+ with pytest.raises(module.FeedbackError, match="member or expansion limits"):
+ module.read_results(payload(members, size))
+ # Similar names outside a retained diagnostics root stay in the report budget.
+ monkeypatch.setattr(module, "MAX_FILES", 2)
+ output = io.BytesIO()
+ with zipfile.ZipFile(output, "w") as zipped:
+ zipped.writestr("ci-results.json", json.dumps(manifest()))
+ zipped.writestr("tier1/skill-001/diagnostics/a.log", "x")
+ zipped.writestr("tier3/skill-001/other/diagnostics/b.log", "x")
+ with pytest.raises(module.FeedbackError, match="member or expansion limits"):
+ module.read_results(output.getvalue())
+
+
+def test_member_limit_still_rejects_one_member_above_the_derived_bound():
+ module = adapter()
+ output = io.BytesIO()
+ with zipfile.ZipFile(output, "w") as zipped:
+ zipped.writestr("ci-results.json", json.dumps(manifest()))
+ for number in range(module.MAX_FILES - 1):
+ zipped.writestr(f"tier1/extra-{number:05d}.json", "{}")
+ assert module.read_results(output.getvalue())["tiers"][0]["status"] == "skipped"
+ with zipfile.ZipFile(output, "a") as zipped:
+ zipped.writestr("tier1/one-too-many.json", "{}")
+ with pytest.raises(module.FeedbackError, match="member or expansion limits"):
+ module.read_results(output.getvalue())
+
+
+def test_gitlab_signed_job_claims_are_not_replaced_by_ci_environment(monkeypatch):
+ module = adapter()
+ import time
+
+ import jwt
+ from cryptography.hazmat.primitives.asymmetric import rsa
+
+ key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
+ jwk = {**json.loads(jwt.algorithms.RSAAlgorithm.to_jwk(key.public_key())), "kid": "gitlab", "use": "sig"}
+ monkeypatch.setattr(module, "_gitlab_signing_keys", lambda _origin: [jwk])
+ monkeypatch.setenv("CI_PIPELINE_ID", "999")
+ now = int(time.time())
+ claims = {
+ "iss": "https://gitlab.example",
+ "aud": module.GL_AUDIENCE,
+ "iat": now,
+ "nbf": now - 5,
+ "exp": now + 300,
+ "project_id": "12",
+ "pipeline_id": "456",
+ "job_id": "92",
+ "ref": "main",
+ "ref_protected": "true",
+ "ref_type": "branch",
+ "sha": MERGE,
+ "pipeline_source": "pipeline",
+ }
+ token = jwt.encode(claims, key, algorithm="RS256", headers={"kid": "gitlab"})
+ assert module.verify_gitlab_job("https://gitlab.example/api/v4", token)["pipeline_id"] == "456"
+ for changes in (
+ {"ref_protected": "false"},
+ {"aud": "evil"},
+ {"project_id": 12},
+ {"pipeline_source": "merge_request_event"},
+ {"sha": "branch"},
+ {"exp": now - 1},
+ {"iss": "https://evil.example"},
+ ):
+ bad = jwt.encode({**claims, **changes}, key, algorithm="RS256", headers={"kid": "gitlab"})
+ with pytest.raises(module.FeedbackError):
+ module.verify_gitlab_job("https://gitlab.example/api/v4", bad)
+
+
+ "include",
+ [
+ [{"local": "untrusted.yml"}],
+ [{"remote": "https://raw.githubusercontent.com/NVIDIA/SkillEvaluator/main/ci/gitlab/all-tiers.yml"}],
+ [{"remote": "https://evil.example/source.yml"}],
+ [{"local": ".gitlab/skill-feedback.yml"}],
+ ],
+)
+def test_gitlab_transitive_config_sources_cannot_be_mutable(include):
+ module = adapter()
+ with pytest.raises(module.FeedbackError):
+ module.validate_gitlab_config({"include": include})
+
+
+def test_github_update_rechecks_bot_ownership_and_requires_exact_readback(github):
+ module, api = github
+ module.github_feedback(api, REPO, 123, 1)
+ api.comments[0]["body"] += "\nold content"
+ assert module.github_feedback(api, REPO, 123, 1)["comment_action"] == "updated"
+ api.comments.clear()
+ original_get = api.get
+
+ def wrong_owner(path):
+ value = original_get(path)
+ if path == "/repos/acme/skills/issues/comments/51":
+ value["user"]["login"] = "another-bot[bot]"
+ return value
+
+ api.get = wrong_owner
+ with pytest.raises(module.FeedbackError, match="readback"):
+ module.github_feedback(api, REPO, 123, 1)
+
+
[email protected]("tamper", ["owner", "body"])
+def test_gitlab_preserves_other_bot_marker_and_requires_its_own_readback(gitlab, tamper):
+ module, api = gitlab
+ api.notes = [{"id": 5, "body": module.MARKER, "author": {"id": 78, "bot": True}}]
+ assert module.gitlab_feedback(api, "https://gitlab.example/api/v4", "12", 123)["comment_action"] == "created"
+ assert api.notes[0]["id"] == 5 and api.notes[0]["body"] == module.MARKER
+ api.notes.pop()
+ original_get = api.get
+
+ def wrong_readback(path):
+ value = original_get(path)
+ if path == "/projects/12/merge_requests/7/notes/51":
+ if tamper == "owner":
+ value["author"]["id"] = 78
+ else:
+ value["body"] += "\n"
+ return value
+
+ api.get = wrong_readback
+ with pytest.raises(module.FeedbackError, match="readback"):
+ module.gitlab_feedback(api, "https://gitlab.example/api/v4", "12", 123)
+
+
+class _ArtifactResponse(io.BytesIO):
+ def __init__(self, payload):
+ super().__init__(payload)
+ self.headers = {}
+
+
+class _RedirectingStorage:
+ """Answer the artifact endpoint with a redirect chain, then the archive bytes."""
+
+ def __init__(self, locations, payload=b"zip-bytes"):
+ self.locations, self.payload, self.requests = list(locations), payload, []
+
+ def open(self, request, *, timeout):
+ import urllib.error
+
+ assert timeout > 0
+ self.requests.append(request)
+ if self.locations:
+ location = self.locations.pop(0)
+ raise urllib.error.HTTPError(request.full_url, 302, "Found", {"Location": location}, None)
+ return _ArtifactResponse(self.payload)
+
+
+def test_gitlab_follows_object_storage_artifact_redirect_without_the_token():
+ module = adapter()
+ api = module.GitLabAPI("https://gitlab.example/api/v4", "12", "secret")
+ api.opener = _RedirectingStorage(["https://objects.example/bucket/artifact.zip?X-Amz-Signature=abc"])
+ assert api.download_artifact(91) == b"zip-bytes"
+ first, second = api.opener.requests
+ assert first.full_url == "https://gitlab.example/api/v4/projects/12/jobs/91/artifacts"
+ assert first.get_header("Private-token") == "secret"
+ assert second.full_url == "https://objects.example/bucket/artifact.zip?X-Amz-Signature=abc"
+ assert all("secret" not in str(value) for value in second.header_items())
+ assert second.get_header("Private-token") is None and second.get_header("Authorization") is None
+
+
+def test_gitlab_artifact_redirect_resolves_relative_locations_and_stays_bounded():
+ module = adapter()
+ api = module.GitLabAPI("https://gitlab.example/api/v4", "12", "secret")
+ api.opener = _RedirectingStorage(["/-/object-storage/artifact.zip", "https://cdn.example/signed"])
+ assert api.download_artifact(91) == b"zip-bytes"
+ assert [r.full_url for r in api.opener.requests[1:]] == [
+ "https://gitlab.example/-/object-storage/artifact.zip",
+ "https://cdn.example/signed",
+ ]
+ api.opener = _RedirectingStorage(["https://objects.example/hop"] * module.MAX_REDIRECTS)
+ assert api.download_artifact(91) == b"zip-bytes"
+ api.opener = _RedirectingStorage(["https://objects.example/zip"], payload=b"x" * (module.MAX_BYTES + 1))
+ with pytest.raises(module.FeedbackError, match="size limit"):
+ api.download_artifact(91)
+
+
+ "locations",
+ [
+ ["http://objects.example/artifact.zip"],
+ ["https://user:[email protected]/artifact.zip"],
+ ["https://[email protected]/artifact.zip"],
+ ["https://objects.example/artifact.zip\r\nX-Injected: 1"],
+ ["ftp://objects.example/artifact.zip"],
+ [""],
+ ["https://objects.example/1", "http://objects.example/2"],
+ ["https://objects.example/hop"] * 6, # one more than MAX_REDIRECTS
+ ],
+)
+def test_gitlab_artifact_redirect_rejects_insecure_credentialed_or_looping_targets(locations):
+ module = adapter()
+ api = module.GitLabAPI("https://gitlab.example/api/v4", "12", "secret")
+ api.opener = _RedirectingStorage(locations)
+ with pytest.raises(module.FeedbackError, match="redirect"):
+ api.download_artifact(91)
+ assert all(r.get_header("Private-token") is None for r in api.opener.requests[1:])
+ assert all(r.full_url.startswith("https://") and "@" not in r.full_url for r in api.opener.requests)
+
+
+def test_gitlab_json_api_calls_still_never_follow_redirects():
+ import urllib.error
+
+ module = adapter()
+ api = module.GitLabAPI("https://gitlab.example/api/v4", "12", "secret")
+ api.opener = _RedirectingStorage(["https://evil.example/data"])
+ with pytest.raises(urllib.error.HTTPError):
+ api.get("/projects/12/pipelines/123")
+ assert len(api.opener.requests) == 1
+
+
+def test_gitlab_cli_does_not_fall_back_to_job_token(monkeypatch, capsys):
+ module = adapter()
+ monkeypatch.delenv("SKILLEVALUATOR_GITLAB_TOKEN", raising=False)
+ monkeypatch.setenv("CI_JOB_TOKEN", "never-use-me-for-notes")
+ assert (
+ module.main(
+ [
+ "--platform",
+ "gitlab",
+ "--api-url",
+ "https://gitlab.example/api/v4",
+ "--project-id",
+ "12",
+ "--pipeline-id",
+ "123",
+ ]
+ )
+ == 1
+ )
+ assert "never-use-me" not in capsys.readouterr().err
+
+
+def _failed_gitlab_main(module):
+ return module.main(
+ [
+ "--platform",
+ "gitlab",
+ "--api-url",
+ "https://gitlab.example/api/v4",
+ "--project-id",
+ "12",
+ "--pipeline-id",
+ "123",
+ ]
+ )
+
+
+def _safe_diagnostic(stderr, category):
+ match = re.fullmatch(
+ r"Trusted feedback could not validate its producer, current head, or bot-owned comment\. "
+ r"\[check=feedback\.py:([1-9][0-9]*); category=" + category + r"\]\n",
+ stderr,
+ )
+ assert match is not None
+ return int(match[1])
+
+
+ "failure,category", [("feedback", "validation"), ("http", "http_401"), ("named", "validation")]
+)
+def test_cli_failure_diagnostic_uses_only_trusted_line_and_finite_category(
+ gitlab, monkeypatch, capsys, failure, category
+):
+ import urllib.error
+
+ module, api = gitlab
+ secret = "synthetic-private-token-with-claims-and-headers"
+ monkeypatch.setenv("SKILLEVALUATOR_GITLAB_TOKEN", secret)
+ monkeypatch.setattr(module, "GitLabAPI", lambda *_args: api)
+ error = module.FeedbackError(secret)
+ if failure == "http":
+ error = urllib.error.HTTPError(
+ "https://private.example/" + secret, 401, secret, {"Authorization": secret}, None
+ )
+ elif failure == "named":
+ error = type(secret, (module.FeedbackError,), {})(secret)
+ error.add_note("private notes: " + secret)
+ original = api.get
+
+ def get(path):
+ if "/notes?" in path:
+ raise error
+ return original(path)
+
+ api.get = get
+ assert _failed_gitlab_main(module) == 1
+ output = capsys.readouterr()
+ assert output.out == ""
+ line = _safe_diagnostic(output.err, category)
+ assert "api.get(" in Path(module.__file__).read_text().splitlines()[line - 1]
+ assert secret not in output.err and "https://" not in output.err
+
+
+def test_cli_validation_diagnostic_identifies_guard_callsite_not_shared_require(gitlab, monkeypatch, capsys):
+ module, api = gitlab
+ monkeypatch.setenv("SKILLEVALUATOR_GITLAB_TOKEN", "synthetic-private-token")
+ monkeypatch.setattr(module, "GitLabAPI", lambda *_args: api)
+ api.variables = []
+ original = module._require
+ failed_lines = []
+
+ def require(condition, message):
+ if not condition:
+ failed_lines.append(sys._getframe(1).f_lineno)
+ original(condition, message)
+
+ monkeypatch.setattr(module, "_require", require)
+ assert _failed_gitlab_main(module) == 1
+ assert _safe_diagnostic(capsys.readouterr().err, "validation") == failed_lines[0]
+
+
+ "exception_name,category",
+ [
+ ("ExpiredSignatureError", "auth_expired"),
+ ("InvalidAudienceError", "auth_audience"),
+ ("InvalidSignatureError", "auth_signature"),
+ ("InvalidIssuerError", "auth_issuer"),
+ ("ImmatureSignatureError", "auth_immature"),
+ ("MissingRequiredClaimError", "auth_missing_claim"),
+ ("DecodeError", "auth_invalid"),
+ ("spoofed", "validation"),
+ ],
+)
+def test_cli_auth_diagnostic_whitelists_classes_without_messages(monkeypatch, capsys, exception_name, category):
+ import jwt
+
+ module = adapter()
+ secret = "synthetic-jwt-claim-and-signature-value"
+ monkeypatch.setenv("SKILLEVALUATOR_GITLAB_TOKEN", secret)
+ cause = (
+ type("ExpiredSignatureError", (Exception,), {})(secret)
+ if exception_name == "spoofed"
+ else getattr(jwt, exception_name)(secret)
+ )
+ cause.add_note(secret)
+
+ def fail(*_args):
+ raise module.FeedbackError(secret) from cause
+
+ monkeypatch.setattr(module, "gitlab_feedback", fail)
+ assert _failed_gitlab_main(module) == 1
+ output = capsys.readouterr()
+ _safe_diagnostic(output.err, category)
+ assert secret not in output.err and output.out == ""
+
+
+def test_cli_auth_diagnostic_reports_only_finite_wrapped_http_code(monkeypatch, capsys):
+ import urllib.error
+
+ import jwt
+
+ module = adapter()
+ secret = "synthetic-jwks-url-token-and-header"
+ monkeypatch.setenv("SKILLEVALUATOR_GITLAB_TOKEN", secret)
+ cause = jwt.PyJWKClientError(secret)
+ cause.__cause__ = urllib.error.HTTPError(
+ "https://private.example/" + secret, 404, secret, {"Authorization": secret}, None
+ )
+ cause.add_note(secret)
+
+ def fail(*_args):
+ raise module.FeedbackError(secret) from cause
+
+ monkeypatch.setattr(module, "gitlab_feedback", fail)
+ assert _failed_gitlab_main(module) == 1
+ output = capsys.readouterr()
+ _safe_diagnostic(output.err, "http_404")
+ assert output.out == "" and secret not in output.err
+
+
+def test_all_tier_receipt_caller_path_is_explicit_and_legacy_default_is_unchanged(monkeypatch):
+ module = adapter()
+ from datetime import datetime
+
+ import jwt
+ from cryptography.hazmat.primitives.asymmetric import rsa
+
+ from ci import verify_provenance
+
+ key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
+ jwk = {
+ **json.loads(jwt.algorithms.RSAAlgorithm.to_jwk(key.public_key())),
+ "kid": "gh",
+ "alg": "RS256",
+ "use": "sig",
+ }
+ monkeypatch.setattr(verify_provenance, "fetch_signing_keys", lambda: {"keys": [jwk]})
+ run = GitHub().run
+ now = int(datetime.fromisoformat(run["run_started_at"]).timestamp())
+ claims = {
+ "iss": verify_provenance.ISSUER,
+ "aud": verify_provenance.AUDIENCE,
+ "iat": now + 30,
+ "nbf": now,
+ "exp": now + 300,
+ "repository": REPO,
+ "repository_id": "12",
+ "run_id": "123",
+ "run_attempt": "1",
+ "event_name": "pull_request",
+ "workflow_ref": REPO + "/" + module.CALLER_PATH + "@refs/pull/7/merge",
+ "workflow_sha": MERGE,
+ "sha": MERGE,
+ "ref": "refs/pull/7/merge",
+ "job_workflow_ref": WORKFLOW,
+ "job_workflow_sha": "c" * 40,
+ }
+ raw = io.BytesIO()
+ with zipfile.ZipFile(raw, "w") as zipped:
+ zipped.writestr("execution.jwt", jwt.encode(claims, key, algorithm="RS256", headers={"kid": "gh"}))
+ arguments = {
+ "repository": REPO,
+ "run": run,
+ "evaluator_workflow": WORKFLOW.rsplit("@", 1)[0],
+ "evaluator_sha": "c" * 40,
+ }
+ assert (
+ verify_provenance.verify_receipt(raw.getvalue(), **arguments, caller_workflow_path=module.CALLER_PATH)[
+ "workflow_sha"
+ ]
+ == MERGE
+ )
+ with pytest.raises(verify_provenance.ProvenanceError):
+ verify_provenance.verify_receipt(raw.getvalue(), **arguments)
+
+
+def test_gitlab_api_supports_an_https_instance_mounted_under_a_path():
+ module = adapter()
+ api = module.GitLabAPI("https://gitlab.example/company/api/v4", "12", "secret")
+ assert api.origin == "https://gitlab.example/company"
+
+
[email protected]("launcher", ["script", "runpy"])
+def test_isolated_feedback_launcher_uses_trusted_siblings_from_any_consumer_directory(tmp_path, launcher):
+ import os
+ import subprocess
+ import sys
+ from pathlib import Path
+
+ script = Path(__file__).resolve().parents[2] / "ci" / "feedback.py"
+ for name in ("github_api", "publish_reports", "tier_manifest", "verify_provenance"):
+ (tmp_path / f"{name}.py").write_text('raise RuntimeError("CONSUMER CODE MUST NOT RUN")\n')
+ for name in ("ci", "skillevaluator"):
+ package = tmp_path / name
+ package.mkdir()
+ (package / "__init__.py").write_text('raise RuntimeError("CONSUMER CODE MUST NOT RUN")\n')
+ command = [sys.executable, "-I", str(script), "--help"]
+ if launcher == "runpy":
+ command = [
+ sys.executable,
+ "-I",
+ "-c",
+ "import runpy,sys;sys.argv=[sys.argv[1],'--help'];runpy.run_path(sys.argv[0],run_name='__main__')",
+ str(script),
+ ]
+ result = subprocess.run(
+ command,
+ cwd=tmp_path,
+ env={**os.environ, "PYTHONPATH": str(tmp_path)},
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ assert result.returncode == 0, result.stderr
+ assert "--platform" in result.stdout
+ assert "CONSUMER CODE" not in result.stdout + result.stderr
diff --git a/tests/ci/test_github_admission_workflow.py b/tests/ci/test_github_admission_workflow.py
new file mode 100644
index 00000000..c02a9838
--- /dev/null
+++ b/tests/ci/test_github_admission_workflow.py
@@ -0,0 +1,143 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Execute the actual credential-admission workflow scripts against GitHub data."""
+
+import io
+import json
+import urllib.error
+import urllib.parse
+import urllib.request
+from pathlib import Path
+
+import pytest
+import yaml
+
+ROOT = Path(__file__).parents[2]
+SHA = "a" * 40
+
+
+def run_admission(
+ tmp_path,
+ monkeypatch,
+ stage,
+ *,
+ permission="write",
+ event_name="pull_request",
+ head=SHA,
+ fork=False,
+ actor="alice",
+ ref="refs/heads/main",
+):
+ workflow = yaml.load((ROOT / ".github/workflows/evaluate-all-tiers.yml").read_text(), Loader=yaml.BaseLoader)
+ if stage == "eligibility":
+ shell = workflow["jobs"]["eligibility"]["steps"][0]["run"]
+ else:
+ shell = next(s["run"] for s in workflow["jobs"]["paid-tiers"]["steps"] if s.get("id") == "current-head")
+ event = {"repository": {"default_branch": "main"}}
+ current = {"state": "open", "head": {"sha": head, "repo": {"full_name": "acme/skills"}}}
+ if event_name == "pull_request":
+ event["pull_request"] = {
+ "number": 7,
+ "head": {"sha": SHA, "repo": {"full_name": "outsider/fork" if fork else "acme/skills"}},
+ }
+ event_path = tmp_path / "event.json"
+ event_path.write_text(json.dumps(event))
+ output = tmp_path / "outputs"
+ environment = {
+ "TOOLS_REF": SHA,
+ "ENV_MODE": "docker",
+ "TIERS": "1,2,3",
+ "SCAN_MODE": "auto",
+ "GH_TOKEN": "read-only-token",
+ "API_URL": "https://api.github.example",
+ "GITHUB_REPOSITORY": "acme/skills",
+ "GITHUB_ACTOR": actor,
+ "GITHUB_TRIGGERING_ACTOR": "rerun-user",
+ "GITHUB_EVENT_PATH": str(event_path),
+ "GITHUB_OUTPUT": str(output),
+ "GITHUB_REF": ref,
+ "GITHUB_SHA": SHA,
+ "GITHUB_EVENT_NAME": event_name,
+ }
+ for key, value in environment.items():
+ monkeypatch.setenv(key, value)
+ requested = []
+
+ def respond(request, **_kwargs):
+ url = request.full_url
+ requested.append(url)
+ if url.endswith("/collaborators/" + urllib.parse.quote(actor, safe="") + "/permission"):
+ if permission is None:
+ raise urllib.error.HTTPError(url, 404, "No access", {}, None)
+ payload = {"permission": permission}
+ elif url.endswith("/pulls/7"):
+ payload = current
+ elif "/pulls/7/files?" in url:
+ payload = []
+ elif url.endswith("/repos/acme/skills"):
+ payload = {"default_branch": "main"}
+ elif url.endswith("/branches/main"):
+ payload = {"commit": {"sha": head}}
+ else:
+ raise AssertionError(f"Unexpected API request {url}")
+ return io.BytesIO(json.dumps(payload).encode())
+
+ monkeypatch.setattr(urllib.request, "urlopen", respond)
+ try:
+ exec(compile("\n".join(shell.splitlines()[1:-1]), "<workflow admission>", "exec"), {})
+ except SystemExit as error:
+ if error.code not in (None, 0):
+ return False, requested
+ allowed = output.exists() and "allowed=true\n" in output.read_text()
+ return allowed, requested
+
+
[email protected]("stage", ["eligibility", "recheck"])
[email protected]("permission", ["read", "triage", "none", None])
[email protected]("event_name", ["pull_request", "push", "workflow_dispatch"])
+def test_provider_jobs_require_proven_write_permission(tmp_path, monkeypatch, stage, permission, event_name):
+ allowed, requested = run_admission(tmp_path, monkeypatch, stage, permission=permission, event_name=event_name)
+ assert not allowed
+ assert any("/collaborators/alice/permission" in url for url in requested)
+
+
[email protected]("stage", ["eligibility", "recheck"])
[email protected]("permission", ["write", "maintain", "admin"])
+def test_initiating_writer_can_run_current_same_repo_head(tmp_path, monkeypatch, stage, permission):
+ allowed, requested = run_admission(tmp_path, monkeypatch, stage, permission=permission)
+ assert allowed
+ assert any("/collaborators/alice/permission" in url for url in requested)
+ assert not any("rerun-user" in url for url in requested)
+
+
[email protected]("stage", ["eligibility", "recheck"])
[email protected]("event_name", ["push", "workflow_dispatch"])
+def test_default_branch_execution_requires_current_commit(tmp_path, monkeypatch, stage, event_name):
+ allowed, _ = run_admission(tmp_path, monkeypatch, stage, event_name=event_name, head="b" * 40)
+ assert not allowed
+
+
[email protected]("stage", ["eligibility", "recheck"])
[email protected]("event_name", ["push", "workflow_dispatch"])
+def test_current_default_branch_writer_is_eligible(tmp_path, monkeypatch, stage, event_name):
+ allowed, requested = run_admission(tmp_path, monkeypatch, stage, event_name=event_name)
+ assert allowed
+ assert any(url.endswith("/branches/main") for url in requested)
+
+
[email protected]("stage", ["eligibility", "recheck"])
+def test_a_fork_head_cannot_use_writer_permissions(tmp_path, monkeypatch, stage):
+ allowed, _ = run_admission(tmp_path, monkeypatch, stage, fork=True)
+ assert not allowed
+
+
[email protected]("stage", ["eligibility", "recheck"])
+def test_nondefault_branch_is_not_authorized_for_manual_model_work(tmp_path, monkeypatch, stage):
+ allowed, _ = run_admission(tmp_path, monkeypatch, stage, event_name="workflow_dispatch", ref="refs/heads/feature")
+ assert not allowed
+
+
[email protected]("stage", ["eligibility", "recheck"])
+def test_app_bot_needs_the_same_api_proven_write_role(tmp_path, monkeypatch, stage):
+ allowed, requested = run_admission(tmp_path, monkeypatch, stage, actor="my-app[bot]")
+ assert allowed
+ assert any("/collaborators/my-app%5Bbot%5D/permission" in url for url in requested)
diff --git a/tests/ci/test_gitlab_admission_transport.py b/tests/ci/test_gitlab_admission_transport.py
new file mode 100644
index 00000000..b3078517
--- /dev/null
+++ b/tests/ci/test_gitlab_admission_transport.py
@@ -0,0 +1,99 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Current-head admission must use a separate read credential without redirects."""
+
+import importlib.util
+import io
+import json
+import urllib.error
+import urllib.request
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).parents[2]
+
+
+def gate():
+ spec = importlib.util.spec_from_file_location("eligible_gate", ROOT / "ci/eligible_gitlab.py")
+ result = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(result)
+ return result
+
+
+def mr_env(monkeypatch):
+ monkeypatch.setattr(urllib.request, "_opener", None)
+ for key, value in {
+ "CI_PIPELINE_SOURCE": "merge_request_event",
+ "CI_API_V4_URL": "https://gitlab.example.test/api/v4",
+ "CI_PROJECT_ID": "42",
+ "CI_MERGE_REQUEST_IID": "1",
+ "CI_MERGE_REQUEST_SOURCE_PROJECT_ID": "42",
+ "CI_COMMIT_SHA": "a" * 40,
+ "CI_JOB_TOKEN": "job-test-token",
+ "SKILLEVALUATOR_GITLAB_TOKEN": "feedback-must-never-be-used",
+ }.items():
+ monkeypatch.setenv(key, value)
+ monkeypatch.delenv("SKILLEVALUATOR_GITLAB_READ_TOKEN", raising=False)
+
+
[email protected]("read_token", [None, "project-read-only-test-token"])
+def test_admission_uses_only_job_or_separate_read_token(mr_env, monkeypatch, read_token):
+ module = gate()
+ if read_token:
+ monkeypatch.setenv("SKILLEVALUATOR_GITLAB_READ_TOKEN", read_token)
+ requests = []
+
+ class Opener:
+ def open(self, request, *_args, **_kwargs):
+ requests.append(request)
+ return io.BytesIO(
+ json.dumps(
+ {"state": "opened", "source_project_id": 42, "target_project_id": 42, "sha": "a" * 40}
+ ).encode()
+ )
+
+ monkeypatch.setattr(module.urllib.request, "build_opener", lambda *_handlers: Opener())
+ assert module.main() == 0
+ headers = {k.lower(): v for k, v in requests[0].header_items()}
+ assert headers == ({"private-token": read_token} if read_token else {"job-token": "job-test-token"})
+
+
+def test_admission_redirect_is_not_followed_or_logged(mr_env, monkeypatch, capsys):
+ module = gate()
+ monkeypatch.setenv("SKILLEVALUATOR_GITLAB_READ_TOKEN", "project-read-only-test-token")
+ calls = []
+ real_builder = urllib.request.build_opener
+
+ class RedirectingHTTPS(urllib.request.HTTPSHandler):
+ def https_open(self, request):
+ calls.append(request.full_url)
+ raise urllib.error.HTTPError(request.full_url, 302, "sensitive response body", {}, None)
+
+ def build(*handlers):
+ assert any(
+ isinstance(h, urllib.request.HTTPRedirectHandler)
+ and h.redirect_request(None, None, 302, "", {}, "https://other.example") is None
+ for h in handlers
+ )
+ return real_builder(*handlers, RedirectingHTTPS())
+
+ monkeypatch.setattr(module.urllib.request, "build_opener", build)
+ assert module.main() == 2
+ output = capsys.readouterr().out
+ assert "HTTP 302" in output
+ assert "project-read-only-test-token" not in output and "sensitive response body" not in output
+ assert len(calls) == 1
+
+
+def test_admission_auth_failure_reports_only_numeric_status(mr_env, monkeypatch, capsys):
+ module = gate()
+
+ class Opener:
+ def open(self, request, *_args, **_kwargs):
+ raise urllib.error.HTTPError(request.full_url, 404, "job-test-token", {}, None)
+
+ monkeypatch.setattr(module.urllib.request, "build_opener", lambda *_handlers: Opener())
+ assert module.main() == 2
+ output = capsys.readouterr().out
+ assert "HTTP 404" in output and "job-test-token" not in output
diff --git a/tests/ci/test_gitlab_feedback_relation.py b/tests/ci/test_gitlab_feedback_relation.py
new file mode 100644
index 00000000..551dc109
--- /dev/null
+++ b/tests/ci/test_gitlab_feedback_relation.py
@@ -0,0 +1,113 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Bounded authenticated GitLab GraphQL relationship reads."""
+
+import http.client
+import io
+import json
+import urllib.error
+
+import pytest
+
+from ci import feedback
+
+
+class Response(io.BytesIO):
+ def __init__(self, body, status=200):
+ super().__init__(body)
+ self.status = status
+ self.headers = {}
+
+ def getcode(self):
+ return self.status
+
+
+class Opener:
+ def __init__(self, body, status=200, error=None):
+ self.body, self.status, self.error = body, status, error
+ self.requests = []
+
+ def open(self, request, *, timeout):
+ assert timeout > 0
+ self.requests.append(request)
+ if self.error:
+ raise self.error
+ return Response(self.body, self.status)
+
+
+def test_graphql_uses_only_the_configured_instance_origin_and_json_post():
+ api = feedback.GitLabAPI("https://gitlab.example/company/api/v4", "12", "private-feedback-token")
+ api.opener = Opener(b'{"data":{"project":{"fullPath":"acme/skills"}}}')
+ data = api.graphql("query($project:ID!){project(fullPath:$project){fullPath}}", {"project": "acme/skills"})
+ assert data == {"project": {"fullPath": "acme/skills"}}
+ request = api.opener.requests[0]
+ assert request.full_url == "https://gitlab.example/company/api/graphql"
+ assert request.method == "POST"
+ assert request.get_header("Private-token") == "private-feedback-token"
+ assert json.loads(request.data)["variables"] == {"project": "acme/skills"}
+
+
[email protected]("status", [301, 302, 307, 400, 401, 403, 500])
+def test_graphql_http_errors_and_redirects_never_forward_or_echo_credentials(status):
+ api = feedback.GitLabAPI("https://gitlab.example/api/v4", "12", "private-feedback-token")
+ error = urllib.error.HTTPError(
+ "https://gitlab.example/api/graphql",
+ status,
+ "private-feedback-token",
+ {"Location": "https://evil.example"},
+ None,
+ )
+ api.opener = Opener(b"", error=error)
+ with pytest.raises(feedback.FeedbackError) as raised:
+ api.graphql("query{__typename}", {})
+ assert "private-feedback-token" not in str(raised.value)
+ assert len(api.opener.requests) == 1
+ assert api.opener.requests[0].full_url == "https://gitlab.example/api/graphql"
+
+
+ "error", [http.client.BadStatusLine("private-feedback-token"), http.client.HTTPException("private-feedback-token")]
+)
+def test_graphql_sanitizes_low_level_http_parser_errors(error):
+ api = feedback.GitLabAPI("https://gitlab.example/api/v4", "12", "private-feedback-token")
+ api.opener = Opener(b"", error=error)
+ with pytest.raises(feedback.FeedbackError) as raised:
+ api.graphql("query{__typename}", {})
+ assert "private-feedback-token" not in str(raised.value)
+ assert raised.value.__cause__ is None
+
+
+ "body",
+ [
+ b'{"errors":[{"message":"private-feedback-token"}],"data":{"project":{}}}',
+ b'{"data":null}',
+ b'{"data":{}} trailing',
+ b'{"data":{},"data":{}}',
+ b"[]",
+ ],
+)
+def test_graphql_rejects_error_partial_or_malformed_responses(body):
+ api = feedback.GitLabAPI("https://gitlab.example/api/v4", "12", "private-feedback-token")
+ api.opener = Opener(body)
+ with pytest.raises(feedback.FeedbackError) as raised:
+ api.graphql("query{__typename}", {})
+ assert "private-feedback-token" not in str(raised.value)
+
+
+def test_graphql_response_and_request_sizes_are_bounded(monkeypatch):
+ api = feedback.GitLabAPI("https://gitlab.example/api/v4", "12", "private-feedback-token")
+ api.opener = Opener(b'{"data":{"value":"' + b"x" * 80 + b'"}}')
+ monkeypatch.setattr(feedback.github_api, "MAX_API_BYTES", 64)
+ with pytest.raises(feedback.FeedbackError, match="size limit"):
+ api.graphql("query{__typename}", {})
+ api.opener.requests.clear()
+ with pytest.raises(feedback.FeedbackError):
+ api.graphql("query{__typename}", {"project": "x" * (64 * 1024)})
+ assert not api.opener.requests
+
+
+def test_graphql_rejects_a_non_error_http_redirect_response():
+ api = feedback.GitLabAPI("https://gitlab.example/api/v4", "12", "private-feedback-token")
+ api.opener = Opener(b'{"data":{}}', status=302)
+ with pytest.raises(feedback.FeedbackError):
+ api.graphql("query{__typename}", {})
diff --git a/tests/ci/test_gitlab_feedback_request.py b/tests/ci/test_gitlab_feedback_request.py
new file mode 100644
index 00000000..dc13257c
--- /dev/null
+++ b/tests/ci/test_gitlab_feedback_request.py
@@ -0,0 +1,218 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Request a same-project publisher using only the running job's token."""
+
+import http.client
+import importlib.util
+import io
+import json
+import urllib.error
+import urllib.parse
+import urllib.request
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).parents[2]
+
+
+def helper():
+ path = ROOT / "ci/request_gitlab_feedback.py"
+ assert path.is_file(), "The pinned feedback requester must exist"
+ spec = importlib.util.spec_from_file_location("request_gitlab_feedback", path)
+ result = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(result)
+ return result
+
+
+def request_env(monkeypatch):
+ values = {
+ "CI_API_V4_URL": "https://gitlab.example.test/gitlab/api/v4",
+ "CI_SERVER_URL": "https://gitlab.example.test/gitlab",
+ "CI_PROJECT_ID": "42",
+ "CI_PIPELINE_ID": "123",
+ "CI_DEFAULT_BRANCH": "main",
+ "CI_PIPELINE_SOURCE": "merge_request_event",
+ "CI_MERGE_REQUEST_SOURCE_PROJECT_ID": "42",
+ "CI_JOB_TOKEN": "job-token-must-not-appear-in-output",
+ "SKILLEVALUATOR_GITLAB_TOKEN": "publisher-token-must-never-be-used",
+ "SKILLEVALUATOR_GITLAB_READ_TOKEN": "reader-token-must-never-be-used",
+ "SKILL_EVAL_TOOLS_REF": "untrusted-extra-must-not-be-forwarded",
+ }
+ for key, value in values.items():
+ monkeypatch.setenv(key, value)
+ return values
+
+
+def install_response(module, monkeypatch, payload=None):
+ requests = []
+ payload = {"id": 456, "project_id": 42, "ref": "main", "source": "pipeline"} if payload is None else payload
+
+ class Opener:
+ def open(self, request, **kwargs):
+ requests.append((request, kwargs))
+ return io.BytesIO(json.dumps(payload).encode())
+
+ monkeypatch.setattr(module.urllib.request, "build_opener", lambda *_handlers: Opener())
+ return requests
+
+
+def test_same_project_request_uses_token_body_and_only_two_selector_variables(request_env, monkeypatch, capsys):
+ module = helper()
+ requests = install_response(module, monkeypatch)
+ assert module.main() == 0
+ assert len(requests) == 1
+ request, kwargs = requests[0]
+ assert request.full_url == "https://gitlab.example.test/gitlab/api/v4/projects/42/trigger/pipeline"
+ assert request.method == "POST"
+ assert urllib.parse.parse_qs(request.data.decode()) == {
+ "token": [request_env["CI_JOB_TOKEN"]],
+ "ref": ["main"],
+ "variables[SKILL_EVAL_FEEDBACK]": ["true"],
+ "variables[SKILL_EVAL_SOURCE_PIPELINE_ID]": ["123"],
+ }
+ assert "token" not in request.full_url
+ assert not any("token" in key.lower() for key, _value in request.header_items())
+ assert 0 < kwargs["timeout"] <= 30
+ output = capsys.readouterr().out
+ assert "456" in output
+ assert all(secret not in output for key, secret in request_env.items() if "TOKEN" in key)
+
+
+ "key,value",
+ [
+ ("CI_PROJECT_ID", "42/other"),
+ ("CI_PROJECT_ID", "0"),
+ ("CI_PIPELINE_ID", "123&ref=evil"),
+ ("CI_PIPELINE_ID", "-1"),
+ ("CI_JOB_TOKEN", ""),
+ ("CI_JOB_TOKEN", "token\nvalue"),
+ ("CI_DEFAULT_BRANCH", ""),
+ ("CI_DEFAULT_BRANCH", "../main"),
+ ("CI_DEFAULT_BRANCH", "main\nother"),
+ ("CI_DEFAULT_BRANCH", "refs/heads/../main"),
+ ("CI_API_V4_URL", "http://gitlab.example.test/gitlab/api/v4"),
+ ("CI_API_V4_URL", "https://other.example/api/v4"),
+ ("CI_API_V4_URL", "https://gitlab.example.test/gitlab/api/v4?token=secret"),
+ ("CI_API_V4_URL", "https://gitlab.example.test/gitlab/api/v4#fragment"),
+ ("CI_API_V4_URL", "https://user:[email protected]/gitlab/api/v4"),
+ ("CI_SERVER_URL", "https://user:[email protected]/gitlab"),
+ ("CI_MERGE_REQUEST_SOURCE_PROJECT_ID", "43"),
+ ("CI_PIPELINE_SOURCE", "web"),
+ ],
+)
+def test_malformed_or_foreign_request_is_rejected_before_network(request_env, monkeypatch, key, value, capsys):
+ module = helper()
+ monkeypatch.setenv(key, value)
+ monkeypatch.setattr(
+ module.urllib.request, "build_opener", lambda *_args: pytest.fail("Invalid input must not send credentials")
+ )
+ assert module.main() == 2
+ output = capsys.readouterr().out
+ assert all(secret not in output for name, secret in request_env.items() if "TOKEN" in name)
+ assert "feedback is skipped" in output and "same-project merge request pipeline" in output
+ assert "permission" not in output
+ # An HTTP-only instance satisfies the MR context; the hint must name the HTTPS requirement.
+ assert "an HTTPS API URL" in output
+
+
+def test_redirect_is_refused_without_logging_token_or_response(request_env, monkeypatch, capsys):
+ module = helper()
+ calls = []
+ real_builder = urllib.request.build_opener
+
+ class RedirectingHTTPS(urllib.request.HTTPSHandler):
+ def https_open(self, request):
+ calls.append(request.full_url)
+ raise urllib.error.HTTPError(request.full_url, 302, request_env["CI_JOB_TOKEN"], {}, None)
+
+ def build(*handlers):
+ assert any(
+ isinstance(handler, urllib.request.HTTPRedirectHandler)
+ and handler.redirect_request(None, None, 302, "", {}, "https://other.example") is None
+ for handler in handlers
+ )
+ return real_builder(*handlers, RedirectingHTTPS())
+
+ monkeypatch.setattr(module.urllib.request, "build_opener", build)
+ assert module.main() == 2
+ assert len(calls) == 1
+ output = capsys.readouterr().out
+ assert "HTTP 302" in output and request_env["CI_JOB_TOKEN"] not in output
+
+
[email protected]("code", [400, 401, 403, 404, 422, 500])
+def test_http_failure_logs_only_status(request_env, monkeypatch, capsys, code):
+ module = helper()
+
+ class Opener:
+ def open(self, request, **_kwargs):
+ raise urllib.error.HTTPError(request.full_url, code, request_env["CI_JOB_TOKEN"], {}, None)
+
+ monkeypatch.setattr(module.urllib.request, "build_opener", lambda *_handlers: Opener())
+ assert module.main() == 2
+ output = capsys.readouterr().out
+ assert f"HTTP {code}" in output and request_env["CI_JOB_TOKEN"] not in output
+ # A refused request (e.g. no default-branch permission) skips comments, not the gate.
+ assert "feedback is skipped" in output and "still gates Tier 1" in output
+ # Only a refusal points at permissions; other failures are retried or checked on the server.
+ refused = code in {400, 401, 403, 404}
+ assert ("permission to run pipelines on the protected default branch" in output) is refused
+ assert ("pass pipeline variables" in output) is refused
+ assert ("added no jobs" in output) is (code == 400)
+ assert ("retry this job" in output) is not refused
+
+
[email protected]("error_type", [urllib.error.URLError, http.client.BadStatusLine])
+def test_transport_failure_does_not_print_server_data(request_env, monkeypatch, capsys, error_type):
+ module = helper()
+
+ class Opener:
+ def open(self, *_args, **_kwargs):
+ raise error_type(request_env["CI_JOB_TOKEN"])
+
+ monkeypatch.setattr(module.urllib.request, "build_opener", lambda *_handlers: Opener())
+ assert module.main() == 2
+ output = capsys.readouterr().out
+ assert request_env["CI_JOB_TOKEN"] not in output
+ assert "feedback is skipped" in output and "could not be reached" in output
+ assert "permission" not in output
+
+
+ "payload",
+ [
+ [],
+ {"id": True},
+ {"id": 0},
+ {"id": 456, "project_id": 43, "ref": "main", "source": "pipeline"},
+ {"id": 456, "project_id": 42, "ref": "other", "source": "pipeline"},
+ {"id": 456, "project_id": 42, "ref": "main", "source": "trigger"},
+ ],
+)
+def test_response_must_identify_same_project_default_branch_pipeline(request_env, monkeypatch, payload, capsys):
+ module = helper()
+ install_response(module, monkeypatch, payload)
+ assert module.main() == 2
+ output = capsys.readouterr().out
+ assert "feedback is skipped" in output and "did not confirm a default-branch pipeline" in output
+ assert "permission" not in output
+
+
+def test_response_read_is_bounded(request_env, monkeypatch):
+ module = helper()
+ reads = []
+
+ class Response(io.BytesIO):
+ def read(self, size=-1):
+ reads.append(size)
+ return b" " * size
+
+ class Opener:
+ def open(self, *_args, **_kwargs):
+ return Response()
+
+ monkeypatch.setattr(module.urllib.request, "build_opener", lambda *_handlers: Opener())
+ assert module.main() == 2
+ assert reads == [1024 * 1024 + 1]
diff --git a/tests/ci/test_native_reports.py b/tests/ci/test_native_reports.py
index 6ccc6aa8..ff9ea348 100644
--- a/tests/ci/test_native_reports.py
+++ b/tests/ci/test_native_reports.py
@@ -284,14 +284,34 @@ def test_failed_and_incomplete_counts_agree_across_all_surfaces(tmp_path):
def test_native_overview_displays_quality_threshold_failure_not_an_advisory(tmp_path):
result = ValidationResult(validator_name="QUALITY", validator_description="Quality score")
- result.add_finding(Finding(category="QUALITY", severity="medium", check_name="version", message="Optional version missing", file_path="skills/example/SKILL.md"))
+ result.add_finding(
+ Finding(
+ category="QUALITY",
+ severity="medium",
+ check_name="version",
+ message="Optional version missing",
+ file_path="skills/example/SKILL.md",
+ )
+ )
result.fail_gate("Quality score 98.2/100 is below the required 100/100")
payload = json.loads(JSONReporter(include_timestamp=False).render_all([result]))
directory = tmp_path / "skill-001"
directory.mkdir()
(directory / "skillevaluator-tier1.json").write_text(json.dumps(payload))
row = {"path": "skills/example", "report_dir": "skill-001", "exit_code": 1, "passed": False}
- row.update({key: payload[key] for key in ("overall_status", "incomplete_scans", "total_validators", "total_errors", "total_warnings", "severity_counts")})
+ row.update(
+ {
+ key: payload[key]
+ for key in (
+ "overall_status",
+ "incomplete_scans",
+ "total_validators",
+ "total_errors",
+ "total_warnings",
+ "severity_counts",
+ )
+ }
+ )
render_native_reports(tmp_path, _summary([row]), {})
index = (tmp_path / "index.html").read_text()
attention = index.split('<section class="attention">', 1)[1].split("</section>", 1)[0]
@@ -361,6 +381,77 @@ def test_index_dark_theme_never_applies_to_print():
assert all(int(size) >= 11 for size in re.findall(r"font-size:(\d+)px", _STYLE))
[email protected]("tier", [2, 3])
+def test_runtime_retains_public_json_and_regenerates_each_native_tier(tmp_path, tier):
+ from ci.run_tiers import _retain
+
+ from skillevaluator.evaluation.tier3_report import build_agent_eval_payload
+ from skillevaluator.tier3.harbor.metrics import DEFAULT_METRICS
+
+ if tier == 2:
+ result = ValidationResult(validator_name="Context Optimization")
+ result.metadata["llm_analysis"] = {"completed_clusters": 1, "failed_clusters": 0}
+ result.add_finding(
+ Finding(
+ category="CONTENT_DEDUP",
+ severity="medium",
+ check_name="redundancy",
+ message="Repeated instructions",
+ file_path="SKILL.md",
+ )
+ )
+ else:
+ conditions = {
+ arm: {"execution_status": "succeeded", "execution_errors": [], "expected_attempts": 1, "scored_attempts": 1}
+ for arm in ("with_skill", "without_skill")
+ }
+ agent_eval = build_agent_eval_payload(
+ "demo",
+ {
+ "opencode": {
+ "with_skill": dict.fromkeys(DEFAULT_METRICS, 0.8),
+ "without_skill": dict.fromkeys(DEFAULT_METRICS, 0.4),
+ "execution_status": "succeeded",
+ "execution_errors": [],
+ "expected_attempts": 2,
+ "scored_attempts": 2,
+ "conditions": conditions,
+ "num_trials": 1,
+ "num_trials_baseline": 1,
+ }
+ },
+ dataset=[{"id": "case-a"}],
+ use_llm_judge=False,
+ attempt_policy={"max_attempts": 1, "stop_on_pass": False, "pass_threshold": 0.5},
+ )
+ result = ValidationResult(validator_name="AGENT_EVAL", metadata={"agent_eval": agent_eval})
+ payload = json.loads(JSONReporter(include_timestamp=False).render_all([result]))
+ raw = tmp_path / "raw"
+ raw.mkdir()
+ (raw / f"skillevaluator-tier{tier}.json").write_text(json.dumps(payload))
+ (raw / f"skillevaluator-tier{tier}.html").write_text("<script>ARTIFACT HTML</script>")
+ output = tmp_path / f"reports/tier{tier}/skill-001"
+ retained = _retain(raw, output, tier, set(), Path("skills/demo"), 0)
+ if tier == 2:
+ # CI supplies an advisory policy even for native JSON without gating.
+ payload["results"][0]["gating"] = {"tier": 2, "blocking": False}
+ payload["gating"] = {"tiers": {"2": {"blocking": False, "validators": ["Context Optimization"]}}}
+ assert json.loads((output / f"skillevaluator-tier{tier}.json").read_text()) == payload
+ document = (output / f"skillevaluator-tier{tier}.html").read_text()
+ assert "ARTIFACT HTML" not in document
+ assert 'href="../../index.html"' in document
+ assert f'href="skillevaluator-tier{tier}.json"' in document
+ assert "Content-Security-Policy" in document
+ if tier == 3:
+ assert retained["metrics"]["score"] == pytest.approx(0.8)
+ assert retained["metrics"]["skill_lift"] == pytest.approx(0.4)
+ assert retained["metrics"]["coverage"] == "2/2"
+ # This fixture has execution coverage but no publication target binding.
+ assert retained["status"] == "incomplete"
+ else:
+ assert retained["metrics"]["findings"] == 1
+
+
def test_native_tier_navigation_remains_within_static_trusted_code():
document = HTMLReporter(requested_tiers=(1,), displayed_tiers=(1, 2, 3)).render_all(
[ValidationResult(validator_name="Schema")]
diff --git a/tests/ci/test_run_tiers.py b/tests/ci/test_run_tiers.py
new file mode 100644
index 00000000..f0c5a14c
--- /dev/null
+++ b/tests/ci/test_run_tiers.py
@@ -0,0 +1,871 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Consumer CI execution must retain honest, independent tier outcomes."""
+
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from ci import run_tiers
+
+
+def consumer(tmp_path):
+ repo = tmp_path / "consumer"
+ repo.mkdir()
+ subprocess.run(["git", "init", "-b", "main", str(repo)], check=True, capture_output=True)
+ for name in ("alpha", "beta"):
+ skill = repo / "skills" / name
+ skill.mkdir(parents=True)
+ (skill / "SKILL.md").write_text(f"---\nname: {name}\ndescription: Use to test {name}.\n---\nInstructions.\n")
+ git = ["git", "-C", str(repo), "-c", "user.name=CI tests", "-c", "[email protected]"]
+ subprocess.run([*git, "add", "."], check=True)
+ subprocess.run([*git, "commit", "-m", "fixtures"], check=True, capture_output=True)
+ return repo
+
+
+def env_for(consumer, **updates):
+ sha = subprocess.check_output(["git", "-C", str(consumer), "rev-parse", "HEAD"], text=True).strip()
+ return {
+ "PATH": os.environ["PATH"],
+ "SKILL_EVAL_PATHS": "skills",
+ "REPORT_COMMIT": sha,
+ "REPORT_REPOSITORY": "example/consumer",
+ "GITHUB_RUN_ID": "123",
+ "GITHUB_RUN_ATTEMPT": "1",
+ "GITHUB_ACTIONS": "true",
+ "SKILL_EVAL_PROVIDER": "nv_build",
+ **updates,
+ }
+
+
[email protected]("tier", [2, 3])
[email protected]("legacy_required", ["false", "true", "unused-legacy-value"])
+def test_missing_credentials_retains_incomplete_advisory_tier(consumer, tmp_path, tier, legacy_required):
+ output = tmp_path / "reports"
+ code = run_tiers.evaluate(tier, consumer, output, env_for(consumer, SKILL_EVAL_TIER3_REQUIRED=legacy_required))
+ result = json.loads((output / f"tier{tier}" / "ci-tier.json").read_text())
+ assert code == 0
+ assert result["tiers"][0]["status"] == "incomplete"
+ assert result["tiers"][0]["required"] is False
+ assert result["overall_passed"] is True
+ assert "credential" in result["tiers"][0]["reason"].lower()
+
+
+def test_missing_tier3_dataset_retains_advisory_failure_without_paid_execution(consumer, tmp_path, monkeypatch):
+ def no_execution(*args, **kwargs):
+ raise AssertionError("An invalid dataset must fail before running an agent or provider")
+
+ monkeypatch.setattr(run_tiers, "run_command", no_execution)
+ output = tmp_path / "reports"
+ code = run_tiers.evaluate(3, consumer, output, env_for(consumer, NVIDIA_API_KEY="test-key-value-123456"))
+ result = json.loads((output / "tier3" / "ci-tier.json").read_text())
+ assert code == 0
+ tier = result["tiers"][0]
+ assert tier["status"] == "incomplete"
+ assert tier["required"] is False
+ assert len(tier["skills"]) == 2
+ assert all(row["status"] == "incomplete" for row in tier["skills"])
+
+
[email protected]("mode", ["gke", "cloud", "docker;echo secret"])
+def test_unsupported_environment_fails_before_execution(consumer, tmp_path, mode):
+ with pytest.raises(run_tiers.ConfigurationError, match="docker or local"):
+ run_tiers.evaluate(3, consumer, tmp_path / "reports", env_for(consumer, SKILL_EVAL_ENV_MODE=mode))
+
+
+def test_tier3_command_demands_all_cases_both_arms_and_explicit_mode(consumer, tmp_path):
+ args = run_tiers.skill_command(
+ 3, consumer / "skills/alpha", tmp_path / "raw", env_for(consumer, SKILL_EVAL_ENV_MODE="local")
+ )
+ assert "native-tier3" in args
+ assert "validate" not in args
+ assert args[args.index("--env-mode") + 1] == "local"
+ assert not set(args) & {"--skip-baseline", "--skip-with-skill", "--max-cases"}
+
+
+def test_native_tier3_options_preserve_complete_paired_coverage(consumer, tmp_path):
+ options = run_tiers.tier3_options(consumer / "skills/alpha", tmp_path, env_for(consumer))
+ assert options.skip_baseline is False
+ assert options.skip_with_skill is False
+ assert options.max_cases is None
+ assert options.stop_on_pass is False
+ assert options.n_attempts == 1
+ assert options.evaluated_source["commit"] == env_for(consumer)["REPORT_COMMIT"]
+
+
+def test_ci_chat_model_uses_native_agent_provider_resolution(consumer, tmp_path):
+ # OpenCode needs its adapter namespace as well as the model's publisher.
+ # Passing the chat model as a native CLI override bypasses that resolution.
+ options = run_tiers.tier3_options(
+ consumer / "skills/alpha", tmp_path, env_for(consumer, SKILL_EVAL_MODEL="nvidia/test-model")
+ )
+ assert options.model is None
+
+
+def test_native_tier3_engine_failure_still_emits_incomplete_evidence(consumer, tmp_path, monkeypatch):
+ from skillevaluator.evaluation.service import EvaluationService
+
+ monkeypatch.setattr(run_tiers, "dataset_preflight", lambda _skill: {})
+ monkeypatch.setattr(EvaluationService, "evaluate", lambda _self, _options: {"error": ["Model routing unavailable"]})
+ monkeypatch.setenv("NVIDIA_API_KEY", "private-provider-key-1234")
+ assert (
+ run_tiers.native_tier3(consumer / "skills/alpha", tmp_path, env_for(consumer, SKILL_EVAL_TIER3_REQUIRED="true"))
+ == 0
+ )
+ report = json.loads((tmp_path / "skillevaluator-tier3.json").read_text())
+ assert report["results"][0]["status"] == "incomplete"
+ assert report["gating"]["tiers"]["3"]["blocking"] is False
+ assert report["results"][0]["gating"] == {"tier": 3, "blocking": False}
+ assert "Model routing unavailable" in json.dumps(report)
+
+
+def test_child_environment_never_passes_feedback_or_repository_tokens():
+ env = run_tiers.child_environment(
+ {
+ "PATH": "/bin",
+ "GITHUB_TOKEN": "repository-token",
+ "CI_JOB_TOKEN": "job-token",
+ "SKILLEVALUATOR_GITLAB_TOKEN": "bot-token",
+ "NVIDIA_API_KEY": "provider-token",
+ "SKILL_EVAL_PROVIDER": "nv_build",
+ }
+ )
+ assert env["NVIDIA_API_KEY"] == "provider-token"
+ assert not set(env) & {"GITHUB_TOKEN", "GH_TOKEN", "CI_JOB_TOKEN", "SKILLEVALUATOR_GITLAB_TOKEN"}
+
+
+def test_setup_workflow_only_change_selects_full_collection(consumer):
+ base = subprocess.check_output(["git", "-C", str(consumer), "rev-parse", "HEAD"], text=True).strip()
+ file = consumer / ".github/workflows/skill-checks.yml"
+ file.parent.mkdir(parents=True)
+ file.write_text("name: Skill checks\n")
+ git = ["git", "-C", str(consumer), "-c", "user.name=CI tests", "-c", "[email protected]"]
+ subprocess.run([*git, "add", "."], check=True)
+ subprocess.run([*git, "commit", "-m", "setup"], check=True, capture_output=True)
+ selected, selection = run_tiers.select_skills(
+ consumer, env_for(consumer, DIFF_BASE_SHA=base, SKILL_EVAL_SCAN_MODE="auto")
+ )
+ assert [p.name for p in selected] == ["alpha", "beta"]
+ assert selection["reason"] == "ci_configuration_changed"
+
+
+def test_changed_selection_without_changes_is_explicitly_skipped(consumer, tmp_path):
+ env = env_for(consumer)
+ env["DIFF_BASE_SHA"] = env["REPORT_COMMIT"]
+ code = run_tiers.evaluate(2, consumer, tmp_path / "reports", env)
+ result = json.loads((tmp_path / "reports/tier2/ci-tier.json").read_text())
+ assert code == 0
+ assert result["tiers"][0]["status"] == "skipped"
+ assert result["tiers"][0]["skills"] == []
+
+
+def test_report_directory_cannot_modify_consumer_checkout(consumer):
+ with pytest.raises(run_tiers.ConfigurationError, match="outside"):
+ run_tiers.evaluate(2, consumer, consumer / "reports", env_for(consumer))
+
+
+def test_head_identity_is_checked_before_full_scan(consumer, tmp_path):
+ with pytest.raises(run_tiers.ConfigurationError, match="commit"):
+ run_tiers.evaluate(2, consumer, tmp_path / "reports", env_for(consumer, REPORT_COMMIT="a" * 40))
+
+
+def test_interrupted_advisory_tier_retains_honest_partial_results(consumer, tmp_path, monkeypatch):
+ from skillevaluator.models import ValidationResult
+ from skillevaluator.reporting.json_reporter import JSONReporter
+
+ attempts = []
+
+ def execute(args, **_kwargs):
+ if "catalog" in args:
+ return 0
+ attempts.append(args)
+ if len(attempts) == 2:
+ raise KeyboardInterrupt
+ result = ValidationResult(
+ validator_name="Context Deduplication", metadata={"gating": {"tier": 2, "blocking": True}}
+ )
+ output = Path(args[args.index("-o") + 1])
+ (output / "skillevaluator-tier2.json").write_text(JSONReporter().render_all([result]))
+ return 0
+
+ monkeypatch.setattr(run_tiers, "run_command", execute)
+ reports = tmp_path / "reports"
+ env = env_for(consumer, NVIDIA_API_KEY="test-provider-value-1234")
+ with pytest.raises(KeyboardInterrupt):
+ run_tiers.evaluate(2, consumer, reports, env)
+ retained = json.loads((reports / "tier2/ci-tier.json").read_text())
+ tier = retained["tiers"][0]
+ assert tier["status"] == "incomplete"
+ assert len(tier["skills"]) == 2
+ assert [row["status"] for row in tier["skills"]] == ["passed", "incomplete"]
+ assert tier["required"] is False
+ assert retained["overall_passed"] is True
+ assert run_tiers.aggregate(reports, (2,), env) == 0
+
+
[email protected]("phase", ["doctor", "catalog", "evaluation"])
+def test_worker_failure_keeps_redacted_diagnostics_after_scratch_cleanup(consumer, tmp_path, monkeypatch, phase):
+ secret = "test-provider-secret-never-retain-12345"
+ scratch_paths = []
+
+ def execute(args, *, log, **_kwargs):
+ log.write_text(f"{phase} startup failure NVIDIA_API_KEY={secret}\n")
+ scratch_paths.append(log.parent)
+ if phase == "evaluation":
+ if "doctor" in args:
+ return 0
+ raw = Path(args[args.index("--output") + 1])
+ trial = raw / "harbor/trials/case"
+ trial.mkdir(parents=True)
+ (trial / "exception.txt").write_text(f"Compose startup failed; provider={secret}\n")
+ return 1
+
+ monkeypatch.setattr(run_tiers, "dataset_preflight", lambda _skill: {})
+ monkeypatch.setattr(run_tiers, "run_command", execute)
+ tier = 2 if phase == "catalog" else 3
+ output = tmp_path / "reports"
+ code = run_tiers.evaluate(tier, consumer, output, env_for(consumer, NVIDIA_API_KEY=secret))
+ assert code == 0
+ assert all(not path.exists() for path in scratch_paths)
+ diagnostics = list((output / f"tier{tier}").rglob("diagnostics/index.json"))
+ assert diagnostics, "Temporary worker errors must survive even without a canonical report"
+ retained = "\n".join(p.read_text() for p in output.rglob("*") if p.is_file())
+ assert secret not in retained
+ assert f"{phase} startup failure" in retained
+ if phase == "evaluation":
+ assert "Compose startup failed" in retained
+ document = json.loads((output / f"tier{tier}/ci-tier.json").read_text())
+ assert document["tiers"][0]["status"] == "incomplete"
+
+
[email protected]("tier", [2, 3])
+def test_advisory_timeout_retains_incomplete_outcome_and_diagnostics(consumer, tmp_path, monkeypatch, tier):
+ def execute(args, *, log, **_kwargs):
+ log.write_text("Worker exceeded its time budget.\n")
+ return 0 if "doctor" in args or "catalog" in args else 124
+
+ monkeypatch.setattr(run_tiers, "dataset_preflight", lambda _skill: {})
+ monkeypatch.setattr(run_tiers, "run_command", execute)
+ reports = tmp_path / "reports"
+ assert (
+ run_tiers.evaluate(
+ tier,
+ consumer,
+ reports,
+ env_for(consumer, NVIDIA_API_KEY="test-provider-value-1234", SKILL_EVAL_TIER3_REQUIRED="true"),
+ )
+ == 0
+ )
+ retained = json.loads((reports / f"tier{tier}/ci-tier.json").read_text())
+ assert retained["tiers"][0]["status"] == "incomplete"
+ assert all(skill["status"] == "incomplete" and skill["error"] for skill in retained["tiers"][0]["skills"])
+ assert retained["overall_passed"] is True
+ assert list((reports / f"tier{tier}").rglob("diagnostics/index.json"))
+
+
+def write_tier(reports, tier, env, status, *, required=True):
+ document = run_tiers.context(env)
+ document.update(
+ expected_tiers=[tier],
+ tiers=[
+ {
+ "tier": tier,
+ "required": required,
+ "status": status,
+ "skills": [
+ {
+ "path": "skills/alpha",
+ "status": status,
+ "report_json": f"tier{tier}/skill-001/report.json",
+ "report_html": f"tier{tier}/skill-001/report.html",
+ "metrics": {"findings": 7},
+ }
+ ],
+ }
+ ],
+ )
+ run_tiers.write_json(reports / f"tier{tier}/ci-tier.json", document)
+
+
[email protected]("status", ["failed", "incomplete", "needs_action", "not_run", "neutral", "skipped", None])
+def test_aggregate_only_tier1_blocks_despite_legacy_paid_requirements(consumer, tmp_path, status):
+ reports = tmp_path / "reports"
+ env = env_for(consumer, SKILL_EVAL_TIER3_REQUIRED="true")
+ write_tier(reports, 1, env, "passed")
+ if status is not None:
+ for tier in (2, 3):
+ write_tier(reports, tier, env, status)
+ assert run_tiers.aggregate(reports, (1, 2, 3), env) == 0
+ document = json.loads((reports / "ci-results.json").read_text())
+ assert document["overall_passed"] is True
+ assert document["overall_status"] == "passed"
+ assert [row["required"] for row in document["tiers"]] == [True, False, False]
+ assert [row["status"] for row in document["tiers"]] == ["passed", status or "incomplete", status or "incomplete"]
+ if status is not None:
+ assert document["tiers"][1]["skills"][0]["report_html"] == "tier2/skill-001/report.html"
+ assert document["tiers"][2]["skills"][0]["metrics"] == {"findings": 7}
+
+
[email protected]("status", ["failed", "incomplete", None])
+def test_aggregate_tier1_nonpass_still_blocks(consumer, tmp_path, status):
+ reports = tmp_path / "reports"
+ env = env_for(consumer)
+ if status is not None:
+ write_tier(reports, 1, env, status)
+ for tier in (2, 3):
+ write_tier(reports, tier, env, "passed")
+ assert run_tiers.aggregate(reports, (1, 2, 3), env) == 1
+ document = json.loads((reports / "ci-results.json").read_text())
+ assert document["overall_passed"] is False
+ assert document["tiers"][0]["status"] == (status or "incomplete")
+
+
[email protected]("damage", ["identity", "required", "path", "status"])
+def test_advisory_artifact_validation_remains_strict(consumer, tmp_path, damage):
+ reports = tmp_path / "reports"
+ env = env_for(consumer)
+ write_tier(reports, 1, env, "passed")
+ write_tier(reports, 2, env, "failed")
+ path = reports / "tier2/ci-tier.json"
+ document = json.loads(path.read_text())
+ if damage == "identity":
+ document["commit"] = "f" * 40
+ elif damage == "required":
+ document["tiers"][0]["required"] = "true"
+ elif damage == "path":
+ document["tiers"][0]["skills"][0]["report_html"] = "../private.html"
+ else:
+ document["tiers"][0]["status"] = "unknown"
+ path.write_text(json.dumps(document))
+ with pytest.raises(ValueError):
+ run_tiers.aggregate(reports, (1, 2, 3), env)
+ assert not (reports / "ci-results.json").exists()
+
+
+def test_consumer_python_module_cannot_shadow_installed_evaluator(consumer, tmp_path):
+ shadow = consumer / "skillevaluator"
+ shadow.mkdir()
+ (shadow / "__init__.py").write_text("")
+ (shadow / "cli.py").write_text("print('CANDIDATE_CODE_EXECUTED')\n")
+ args = run_tiers.skill_command(2, consumer / "skills/alpha", tmp_path / "raw", env_for(consumer))
+ args = [*args[: args.index("skillevaluator.cli") + 1], "--version"]
+ log = tmp_path / "command.log"
+ code = run_tiers.run_command(
+ args, env=run_tiers.child_environment(env_for(consumer)), cwd=consumer, timeout=30, log=log
+ )
+ assert code == 0
+ assert "CANDIDATE_CODE_EXECUTED" not in log.read_text()
+ assert "skillevaluator" in log.read_text().lower()
+
+
[email protected]("legacy_status,expected_code", [("skipped", 0), ("error", 1)])
+def test_legacy_tier1_no_work_and_runtime_error_still_produce_aggregate(
+ consumer, tmp_path, legacy_status, expected_code
+):
+ from ci.run_tier1 import _summary
+
+ env = env_for(consumer)
+ reports = tmp_path / "reports"
+ (reports / "tier1").mkdir(parents=True)
+ legacy = _summary([], "Runtime unavailable" if legacy_status == "error" else None)
+ legacy.update(overall_status=legacy_status, execution={"commit": env["REPORT_COMMIT"]})
+ if legacy_status == "skipped":
+ _, legacy["selection"] = run_tiers.select_changed_skills(
+ consumer, "skills", env["REPORT_COMMIT"], env["REPORT_COMMIT"]
+ )
+ (reports / "tier1/summary.json").write_text(json.dumps(legacy))
+ assert run_tiers.aggregate(reports, (1,), env) == expected_code
+ document = json.loads((reports / "ci-results.json").read_text())
+ assert document["tiers"][0]["status"] == ("skipped" if legacy_status == "skipped" else "incomplete")
+ assert document["tiers"][0]["reason"]
+ assert (reports / "index.html").is_file()
+
+
+def test_child_environment_forwards_docker_tls_settings():
+ env = run_tiers.child_environment(
+ {
+ "PATH": "/bin",
+ "DOCKER_HOST": "tcp://docker:2376",
+ "DOCKER_TLS_VERIFY": "1",
+ "DOCKER_CERT_PATH": "/certs/client",
+ "NVIDIA_API_KEY": "provider-token",
+ "SKILL_EVAL_PROVIDER": "nv_build",
+ }
+ )
+ assert env["DOCKER_TLS_VERIFY"] == "1"
+ assert env["DOCKER_CERT_PATH"] == "/certs/client"
+
+
+def test_anthropic_chat_with_unset_embedding_provider_uses_openai_embeddings():
+ env = run_tiers.child_environment(
+ {
+ "SKILL_EVAL_PROVIDER": "anthropic",
+ "SKILL_EVAL_EMBEDDING_PROVIDER": "",
+ "ANTHROPIC_API_KEY": "anthropic-token",
+ "OPENAI_API_KEY": "openai-token",
+ }
+ )
+ assert env["SKILL_EVAL_EMBEDDING_PROVIDER"] == "openai"
+ assert env["OPENAI_API_KEY"] == "openai-token"
+
+
+def test_post_run_dataset_recheck_failure_downgrades_the_skill(consumer, tmp_path, monkeypatch):
+ calls = []
+
+ def preflight(_skill):
+ calls.append(_skill)
+ if len(calls) % 2 == 0:
+ raise run_tiers.ConfigurationError("Tier 3 authored inputs cannot contain symlinks.")
+ return {}
+
+ monkeypatch.setattr(run_tiers, "dataset_preflight", preflight)
+ monkeypatch.setattr(run_tiers, "run_command", lambda *_args, **_kwargs: 0)
+ monkeypatch.setattr(run_tiers, "_retain", lambda *_args: {"status": "passed", "metrics": {}, "complete": True})
+ reports = tmp_path / "reports"
+ env = env_for(consumer, NVIDIA_API_KEY="test-provider-value-1234")
+ assert run_tiers.evaluate(3, consumer, reports, env) == 0
+ tier = json.loads((reports / "tier3/ci-tier.json").read_text())["tiers"][0]
+ assert tier["status"] == "incomplete"
+ assert {(s["status"], s["error"]) for s in tier["skills"]} == {
+ ("incomplete", "Tier 3 authored inputs cannot contain symlinks.")
+ }
+ assert run_tiers.aggregate(reports, (3,), env) == 0
+ assert (reports / "ci-results.json").is_file()
+ assert (reports / "summary.md").is_file()
+
+
+def test_timeout_keeps_the_time_budget_diagnostic_for_every_skill(consumer, tmp_path, monkeypatch):
+ import sys
+
+ real_run = run_tiers.run_command
+
+ def execute(args, **kwargs):
+ if "catalog" in args:
+ return 0
+ return real_run([sys.executable, "-c", "import time; time.sleep(30)"], **kwargs)
+
+ monkeypatch.setattr(run_tiers, "run_command", execute)
+ reports = tmp_path / "reports"
+ env = env_for(consumer, NVIDIA_API_KEY="test-provider-value-1234", SKILL_EVAL_TIMEOUT_SECONDS="1")
+ assert run_tiers.evaluate(2, consumer, reports, env) == 0
+ skills = json.loads((reports / "tier2/ci-tier.json").read_text())["tiers"][0]["skills"]
+ # The second skill starts after the budget is spent and must say so too.
+ assert [(s["status"], s["error"]) for s in skills] == [
+ ("incomplete", "Evaluation exceeded the configured time budget.")
+ ] * 2
+
+
[email protected]("status", ["passed", "neutral", "skipped"])
+def test_aggregate_rejects_a_completed_claim_missing_selected_skills(consumer, tmp_path, status):
+ reports = tmp_path / "reports"
+ env = env_for(consumer)
+ write_tier(reports, 1, env, "passed")
+ write_tier(reports, 3, env, status)
+ path = reports / "tier3/ci-tier.json"
+ document = json.loads(path.read_text())
+ document["selection"] = {"reason": "full_scan", "selected": ["skills/alpha", "skills/beta"]}
+ path.write_text(json.dumps(document))
+ assert run_tiers.aggregate(reports, (1, 3), env) == 0
+ tier3 = json.loads((reports / "ci-results.json").read_text())["tiers"][1]
+ assert tier3["status"] == "incomplete"
+ assert "missing for selected skills" in tier3["reason"]
+
+
+def test_skill_directories_with_url_delimiters_still_aggregate(tmp_path, monkeypatch):
+ from skillevaluator.models import ValidationResult
+ from skillevaluator.reporting.json_reporter import JSONReporter
+
+ repo = tmp_path / "consumer"
+ names = ("c#-helper", "100%-coverage", "a\\b")
+ for name in names:
+ skill = repo / "skills" / name
+ skill.mkdir(parents=True)
+ (skill / "SKILL.md").write_text("---\nname: helper\ndescription: Use to test paths.\n---\nInstructions.\n")
+ subprocess.run(["git", "init", "-b", "main", str(repo)], check=True, capture_output=True)
+ git = ["git", "-C", str(repo), "-c", "user.name=CI tests", "-c", "[email protected]"]
+ subprocess.run([*git, "add", "."], check=True)
+ subprocess.run([*git, "commit", "-m", "fixtures"], check=True, capture_output=True)
+
+ def execute(args, **_kwargs):
+ if "catalog" in args:
+ return 0
+ result = ValidationResult(
+ validator_name="Context Deduplication", metadata={"gating": {"tier": 2, "blocking": False}}
+ )
+ (Path(args[args.index("-o") + 1]) / "skillevaluator-tier2.json").write_text(JSONReporter().render_all([result]))
+ return 0
+
+ monkeypatch.setattr(run_tiers, "run_command", execute)
+ reports = tmp_path / "reports"
+ env = env_for(repo, NVIDIA_API_KEY="test-provider-value-1234")
+ assert run_tiers.evaluate(2, repo, reports, env) == 0
+ assert run_tiers.aggregate(reports, (2,), env) == 0
+ tier2 = json.loads((reports / "ci-results.json").read_text())["tiers"][0]
+ assert tier2["status"] == "passed"
+ assert sorted(s["path"] for s in tier2["skills"]) == sorted(f"skills/{name}" for name in names)
+
+
+def write_attempt(staging, tier, attempt, env, status):
+ """Lay out one downloaded tier artifact as actions/download-artifact does for a pattern."""
+ artifact = staging / f"skill-evaluator-tier{tier}-attempt-{attempt}"
+ write_tier(artifact, tier, {**env, "GITHUB_RUN_ATTEMPT": str(attempt)}, status)
+ return artifact
+
+
+def test_rerun_failed_jobs_reuses_earlier_attempt_tier_evidence(consumer, tmp_path):
+ from ci.run_tier1 import _summary
+
+ env = env_for(consumer, GITHUB_RUN_ATTEMPT="2")
+ staging, reports = tmp_path / "artifacts", tmp_path / "reports"
+ # Attempt 1: Tier 1 had no work and Tier 3 failed; only the failed Tier 2 job was rerun.
+ tier1 = staging / "skill-evaluator-tier1-attempt-1"
+ tier1.mkdir(parents=True)
+ legacy = _summary([], None)
+ legacy.update(overall_status="skipped", execution={"commit": env["REPORT_COMMIT"]})
+ _, legacy["selection"] = run_tiers.select_changed_skills(
+ consumer, "skills", env["REPORT_COMMIT"], env["REPORT_COMMIT"]
+ )
+ (tier1 / "summary.json").write_text(json.dumps(legacy))
+ write_attempt(staging, 2, 1, env, "incomplete")
+ write_attempt(staging, 2, 2, env, "passed")
+ write_attempt(staging, 3, 1, env, "failed")
+ # Neither a future attempt nor another artifact family can be selected.
+ write_attempt(staging, 3, 3, env, "passed")
+ (staging / "skill-evaluator-results-attempt-1").mkdir()
+ (staging / "skill-evaluator-tier1-provenance-attempt-2").mkdir()
+
+ assert run_tiers.select_attempts(staging, reports, 2) == {"1": "1", "2": "2", "3": "1"}
+ assert json.loads((reports / "source-attempts.json").read_text()) == {"1": "1", "2": "2", "3": "1"}
+ assert run_tiers.aggregate(reports, (1, 2, 3), env) == 0
+ document = json.loads((reports / "ci-results.json").read_text())
+ assert document["run_attempt"] == "2"
+ assert [row["status"] for row in document["tiers"]] == ["skipped", "passed", "failed"]
+ assert [row["source_attempt"] for row in document["tiers"]] == ["1", "2", "1"]
+ assert "evidence from run attempt 1" in (reports / "summary.md").read_text()
+
+
+def test_select_attempts_cli_reads_the_current_attempt(consumer, tmp_path, monkeypatch):
+ env = env_for(consumer)
+ staging, reports = tmp_path / "artifacts", tmp_path / "reports"
+ write_attempt(staging, 2, 1, env, "passed")
+ write_attempt(staging, 2, 2, env, "failed")
+ monkeypatch.setenv("GITHUB_RUN_ATTEMPT", "1")
+ assert run_tiers.main(["select-attempts", "--artifacts", str(staging), "--reports", str(reports)]) == 0
+ assert json.loads((reports / "tier2/ci-tier.json").read_text())["run_attempt"] == "1"
+
+
[email protected]("damage", ["future", "run_id", "recorded", "recorded_future"])
+def test_aggregate_rejects_foreign_or_future_tier_attempts(consumer, tmp_path, damage):
+ env = env_for(consumer, GITHUB_RUN_ATTEMPT="2")
+ reports = tmp_path / "reports"
+ write_tier(reports, 1, env, "passed")
+ write_tier(reports, 2, {**env, "GITHUB_RUN_ATTEMPT": "1"}, "passed")
+ path = reports / "tier2/ci-tier.json"
+ document = json.loads(path.read_text())
+ if damage == "future":
+ document["run_attempt"] = "3"
+ elif damage == "run_id":
+ document["run_id"] = "124"
+ path.write_text(json.dumps(document))
+ if damage.startswith("recorded"):
+ recorded = {"2": "2"} if damage == "recorded" else {"2": "3"}
+ (reports / "source-attempts.json").write_text(json.dumps(recorded))
+ with pytest.raises(run_tiers.ConfigurationError):
+ run_tiers.aggregate(reports, (1, 2), env)
+ assert not (reports / "ci-results.json").exists()
+
+
+def _commit_change(consumer, *, write=(), rename=()):
+ git = ["git", "-C", str(consumer), "-c", "user.name=CI tests", "-c", "[email protected]"]
+ for relative, text in write:
+ path = consumer / relative
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text)
+ for source, target in rename:
+ (consumer / target).parent.mkdir(parents=True, exist_ok=True)
+ subprocess.run([*git, "mv", source, target], check=True)
+ subprocess.run([*git, "add", "-A"], check=True)
+ subprocess.run([*git, "commit", "-m", "change"], check=True, capture_output=True)
+ return subprocess.check_output(["git", "-C", str(consumer), "rev-parse", "HEAD"], text=True).strip()
+
+
+def test_unrelated_ci_directory_change_keeps_the_tier1_changed_selection(consumer):
+ base = subprocess.check_output(["git", "-C", str(consumer), "rev-parse", "HEAD"], text=True).strip()
+ # A consumer's own ci/ scripts are not SkillEvaluator setup; Tier 1 keeps changed mode here too.
+ _commit_change(
+ consumer, write=[("ci/build.sh", "echo build\n"), ("skills/alpha/SKILL.md", "---\nname: alpha\n---\n")]
+ )
+ selected, selection = run_tiers.select_skills(consumer, env_for(consumer, DIFF_BASE_SHA=base))
+ assert [p.name for p in selected] == ["alpha"]
+ assert selection["mode"] == "changed" and "reason" not in selection
+
+
+def test_setup_file_renamed_away_still_selects_full_collection(consumer):
+ _commit_change(consumer, write=[(".gitlab/skill-feedback.yml", "include: []\n" * 20)])
+ base = subprocess.check_output(["git", "-C", str(consumer), "rev-parse", "HEAD"], text=True).strip()
+ # GitHub eligibility checks a rename's previous path; native selection must see it too.
+ _commit_change(consumer, rename=[(".gitlab/skill-feedback.yml", "docs/skill-feedback.yml")])
+ selected, selection = run_tiers.select_skills(consumer, env_for(consumer, DIFF_BASE_SHA=base))
+ assert [p.name for p in selected] == ["alpha", "beta"]
+ assert selection["reason"] == "ci_configuration_changed"
+
+
+def test_aggregate_keeps_each_tier_selection_so_unselected_skills_are_not_incomplete(consumer, tmp_path):
+ from ci.comment_summary import render_comment_summary
+
+ reports = tmp_path / "reports"
+ env = env_for(consumer)
+ for tier, selected in ((1, ["skills/alpha"]), (2, ["skills/alpha", "skills/beta"])):
+ write_tier(reports, tier, env, "passed")
+ path = reports / f"tier{tier}/ci-tier.json"
+ document = json.loads(path.read_text())
+ document["selection"] = {"mode": "changed", "selected": selected}
+ document["tiers"][0]["selected"] = ["forged"]
+ skill = document["tiers"][0]["skills"][0]
+ document["tiers"][0]["skills"] = [
+ {
+ **skill,
+ "path": p,
+ "report_json": f"tier{tier}/skill-00{i}/r.json",
+ "report_html": f"tier{tier}/skill-00{i}/r.html",
+ }
+ for i, p in enumerate(selected, 1)
+ ]
+ path.write_text(json.dumps(document))
+ assert run_tiers.aggregate(reports, (1, 2), env) == 0
+ manifest = json.loads((reports / "ci-results.json").read_text())
+ assert [row["selected"] for row in manifest["tiers"]] == [["skills/alpha"], ["skills/alpha", "skills/beta"]]
+ body = render_comment_summary(manifest, "https://github.com/example/consumer/actions/runs/123/artifacts/9")
+ beta = next(line for line in body.splitlines() if line.startswith("| skills/beta |"))
+ assert "Required gate: **Passed**" in body
+ assert beta.split(" | ")[1] == "SKIPPED · issues unknown · Not selected for this tier"
+ assert "INCOMPLETE" not in beta
+
+
+def _failed_tier2_report(output: Path, *, incomplete: bool = False) -> None:
+ from skillevaluator.models import Finding, Severity, ValidationResult
+ from skillevaluator.reporting.json_reporter import JSONReporter
+
+ result = ValidationResult(
+ validator_name="Context Deduplication",
+ passed=False,
+ errors=["Duplicate deployment instructions"],
+ metadata={"gating": {"tier": 2, "blocking": True}},
+ )
+ if incomplete:
+ # A blocking finding outranks the incomplete scan, so the status stays failed.
+ result.add_finding(
+ Finding(
+ category="DEDUP",
+ severity=Severity.HIGH,
+ check_name="duplicate-instructions",
+ message="Duplicate deployment instructions",
+ file_path="SKILL.md",
+ )
+ )
+ result.mark_scan_incomplete("LLM review")
+ (output / "skillevaluator-tier2.json").write_text(JSONReporter().render_all([result]))
+
+
+ ("failed", "incomplete", "status"), [(True, False, "failed"), (False, True, "incomplete"), (True, True, "failed")]
+)
+def test_retained_tier2_reports_apply_ci_advisory_policy(consumer, tmp_path, failed, incomplete, status):
+ from skillevaluator.models import Finding, Severity, ValidationResult
+ from skillevaluator.publication_evidence import stamp_publication_evidence
+ from skillevaluator.publication_identity import finalize_publication_target, publication_target_from_path
+ from skillevaluator.reporting.json_reporter import JSONReporter
+ from skillevaluator.reporting.retained import retained_results
+ from skillevaluator.reporting.run_status import resolve_run_status
+ from skillevaluator.tier_workflows import _record_scope
+
+ skill = consumer / "skills/alpha"
+ result = ValidationResult(validator_name="Context Deduplication")
+ if failed:
+ result.add_finding(
+ Finding(
+ category="DEDUP",
+ severity=Severity.HIGH,
+ check_name="duplicate-instructions",
+ message="Duplicate deployment instructions",
+ file_path="SKILL.md",
+ )
+ )
+ if incomplete:
+ result.mark_scan_incomplete("LLM review")
+ stamp_publication_evidence([result], tier=2, check_id="context-optimization")
+ finalize_publication_target([result], skill, publication_target_from_path(skill))
+ _record_scope([result], 2, {"intra_skill": {"status": status}})
+ env = env_for(consumer)
+ source = {"repository": "example/consumer", "commit": env["REPORT_COMMIT"]}
+ result.metadata["evaluated_source"] = source
+ document = JSONReporter().render_all([result])
+ original = json.loads(document)
+ assert original["overall_passed"] is False
+ assert original["results"][0]["gating"] == {"tier": 2, "blocking": True}
+ raw = tmp_path / "raw"
+ raw.mkdir()
+ (raw / "skillevaluator-tier2.json").write_text(document)
+ reports = tmp_path / "reports"
+ destination = reports / "tier2/skill-001"
+
+ outcome = run_tiers._retain(raw, destination, 2, set(), skill, 1)
+
+ assert outcome == {"status": status, "metrics": {"findings": int(failed)}, "complete": not incomplete}
+ retained = json.loads((destination / "skillevaluator-tier2.json").read_text())
+ assert retained["gating"]["tiers"]["2"]["blocking"] is False
+ assert retained["overall_passed"] is True
+ assert retained["overall_status"] == "passed"
+ assert retained["results"][0]["gating"] == {"tier": 2, "blocking": False}
+ assert retained["results"][0]["status"] == status
+ assert retained["results"][0]["passed"] is False
+ assert retained["evaluated_source"] == source
+ for key in set(original) - {"gating", "overall_passed", "overall_status", "results"}:
+ assert retained[key] == original[key], key
+ for key in set(original["results"][0]) - {"gating"}:
+ assert retained["results"][0][key] == original["results"][0][key], key
+ restored = retained_results(retained, allowed_tiers={2})
+ assert resolve_run_status(restored).tiers[2].status.value == status
+ html = (destination / "skillevaluator-tier2.html").read_text()
+ assert "Advisory (Tier 2)" in html
+ assert "Blocking (Tier 2)" not in html
+ if failed:
+ assert "Failed (advisory)" in html
+ markdown = (destination / "skillevaluator-tier2.md").read_text()
+ assert "**Status:** ✅ PASSED" in markdown
+ assert f"| ❌ Failed | {int(failed)} |" in markdown
+ assert f"| ⚠️ Incomplete | {int(incomplete)} |" in markdown
+ assert (raw / "skillevaluator-tier2.json").read_text() == document
+ assert result.metadata["gating"] == {"tier": 2, "blocking": True}
+
+ tier2 = run_tiers.context(env)
+ tier2.update(
+ expected_tiers=[2],
+ tiers=[
+ {
+ "tier": 2,
+ "required": False,
+ "status": status,
+ "skills": [
+ {
+ "path": "skills/alpha",
+ "status": status,
+ "report_json": "tier2/skill-001/skillevaluator-tier2.json",
+ "report_html": "tier2/skill-001/skillevaluator-tier2.html",
+ }
+ ],
+ }
+ ],
+ )
+ run_tiers.write_json(reports / "tier2/ci-tier.json", tier2)
+ write_tier(reports, 1, env, "passed")
+ assert run_tiers.aggregate(reports, (1, 2), env) == 0
+ aggregate = json.loads((reports / "ci-results.json").read_text())
+ assert aggregate["overall_passed"] is True
+ assert aggregate["tiers"][1]["status"] == status
+
+
+ ("code", "incomplete", "retained"), [(1, False, False), (1, True, True), (2, False, True), (-9, False, True)]
+)
+def test_worker_diagnostics_are_kept_for_execution_problems_not_complete_verdicts(
+ consumer, tmp_path, monkeypatch, code, incomplete, retained
+):
+ def execute(args, *, log, **_kwargs):
+ if "catalog" in args:
+ return 0
+ log.write_text("worker output\n")
+ _failed_tier2_report(Path(args[args.index("-o") + 1]), incomplete=incomplete)
+ return code
+
+ monkeypatch.setattr(run_tiers, "run_command", execute)
+ reports = tmp_path / "reports"
+ assert run_tiers.evaluate(2, consumer, reports, env_for(consumer, NVIDIA_API_KEY="test-provider-value-1234")) == 0
+ skills = json.loads((reports / "tier2/ci-tier.json").read_text())["tiers"][0]["skills"]
+ assert [s["status"] for s in skills] == ["failed", "failed"]
+ assert bool(list((reports / "tier2").rglob("diagnostics"))) is retained
+
+
+def test_neutral_tier3_verdict_keeps_no_worker_diagnostics(consumer, tmp_path, monkeypatch):
+ def execute(args, *, log, **_kwargs):
+ log.write_text("worker output\n")
+ if "doctor" in args:
+ return 0
+ trial = Path(args[args.index("--output") + 1]) / "harbor/run/_harbor-jobs/job/trial"
+ trial.mkdir(parents=True)
+ (trial / "trial.log").write_text("trial ran\n")
+ return 1 # native-tier3 exits 1 for any headline other than passed
+
+ monkeypatch.setattr(run_tiers, "dataset_preflight", lambda _skill: {})
+ monkeypatch.setattr(run_tiers, "run_command", execute)
+ monkeypatch.setattr(run_tiers, "_retain", lambda *_args: {"status": "neutral", "metrics": {}, "complete": True})
+ reports = tmp_path / "reports"
+ assert run_tiers.evaluate(3, consumer, reports, env_for(consumer, NVIDIA_API_KEY="test-provider-value-1234")) == 0
+ tier = json.loads((reports / "tier3/ci-tier.json").read_text())["tiers"][0]
+ assert {s["status"] for s in tier["skills"]} == {"neutral"}
+ assert not list((reports / "tier3").rglob("diagnostics"))
+
+
[email protected]("code", [0, 1])
+def test_failed_tier3_verdict_with_incomplete_execution_keeps_worker_diagnostics(consumer, tmp_path, monkeypatch, code):
+ from skillevaluator.evaluation.tier3_report import _validation_result_from_payload
+ from skillevaluator.reporting.json_reporter import JSONReporter
+
+ def execute(args, *, log, **_kwargs):
+ log.write_text("worker output: codex installation failed\n")
+ if "doctor" in args:
+ return 0
+ output = Path(args[args.index("--output") + 1])
+ trial = output / "harbor/run/_harbor-jobs/skill-codex-with/trial"
+ trial.mkdir(parents=True)
+ (trial / "trial.log").write_text("trial ran\n")
+ (trial / "exception.txt").write_text("AgentInstallError\n")
+ # One agent failed to execute while another finished with a failing score.
+ result = _validation_result_from_payload(
+ {
+ "execution_status": "failed",
+ "execution_errors": ["codex: agent installation failed"],
+ "overall_score": 0.41,
+ "verdict": "fail",
+ "summary": {"verdict": "fail"},
+ }
+ )
+ result.metadata["gating"] = {"tier": 3, "blocking": False}
+ result.mark_scan_incomplete("Tier 3 execution") # as native_tier3 records a failure reason
+ (output / "skillevaluator-tier3.json").write_text(JSONReporter().render_all([result]))
+ return code
+
+ monkeypatch.setattr(run_tiers, "dataset_preflight", lambda _skill: {})
+ monkeypatch.setattr(run_tiers, "run_command", execute)
+ reports = tmp_path / "reports"
+ assert run_tiers.evaluate(3, consumer, reports, env_for(consumer, NVIDIA_API_KEY="test-provider-value-1234")) == 0
+ skills = json.loads((reports / "tier3/ci-tier.json").read_text())["tiers"][0]["skills"]
+ assert [(s["status"], s["metrics"]["execution_complete"]) for s in skills] == [("failed", False)] * 2
+ assert "complete" not in skills[0]
+ for number in (1, 2):
+ diagnostics = reports / f"tier3/skill-00{number}/diagnostics"
+ assert (diagnostics / "command.log").is_file()
+ assert (diagnostics / "harbor/run/_harbor-jobs/skill-codex-with/trial/exception.txt").is_file()
+
+
+def test_tier_diagnostics_budget_is_shared_by_every_skill(consumer, tmp_path, monkeypatch):
+ from ci import diagnostics
+
+ def execute(args, *, log, **_kwargs):
+ log.write_text("worker startup failed\n")
+ return 0 if "catalog" in args else 1
+
+ monkeypatch.setattr(diagnostics, "MAX_TIER_FILES", 1)
+ monkeypatch.setattr(run_tiers, "run_command", execute)
+ reports = tmp_path / "reports"
+ assert run_tiers.evaluate(2, consumer, reports, env_for(consumer, NVIDIA_API_KEY="test-provider-value-1234")) == 0
+ first, second = (reports / "tier2/skill-001/diagnostics", reports / "tier2/skill-002/diagnostics")
+ assert (first / "command.log").is_file()
+ assert not (second / "command.log").exists()
+ index = json.loads((second / "index.json").read_text())
+ assert index["omitted"] == [{"path": "command.log", "reason": "tier_limit"}]
diff --git a/tests/ci/test_select_changed_skills.py b/tests/ci/test_select_changed_skills.py
index fd5d529b..4a34344e 100644
--- a/tests/ci/test_select_changed_skills.py
+++ b/tests/ci/test_select_changed_skills.py
@@ -354,3 +354,19 @@ def test_shallow_clone_fails_changed_selection_instead_of_scanning_everything(re
git(clone, "checkout", "-q", "--detach", head)
with pytest.raises(selector.SelectionError):
select(clone, base, head)
+
+
+ ("paths", "expected"),
+ [
+ (["skills/demo/SKILL.md"], False),
+ (["ci/build.sh", "skills/demo/SKILL.md"], False),
+ ([".skillevaluator/notes.md", ".gitlab-ci.yaml"], False),
+ ([".github/workflows/skill-checks-all-tiers.yml"], True),
+ ([".gitlab/skill-feedback.yml"], True),
+ ([".gitlab-ci.yml"], True),
+ ([".skillevaluator/ci.yml"], True),
+ ],
+)
+def test_setup_change_predicate_is_the_documented_ci_setup_paths(paths, expected):
+ assert selector.setup_changed(paths) is expected
diff --git a/tests/ci/test_summary_metrics.py b/tests/ci/test_summary_metrics.py
new file mode 100644
index 00000000..ebe68256
--- /dev/null
+++ b/tests/ci/test_summary_metrics.py
@@ -0,0 +1,238 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Compact comment metrics preserve findings and uncertainty from native results."""
+
+import json
+
+import pytest
+from ci.summary_metrics import summarize_results
+
+from skillevaluator.models import Finding, ValidationResult
+from skillevaluator.validators.license import LicenseValidator
+
+
+def _finding(severity, message):
+ return Finding(category="TEST", severity=severity, check_name="check", message=message, file_path="SKILL.md")
+
+
+def test_counts_findings_and_independent_diagnostics_without_success_info_or_mirrors():
+ result = ValidationResult(validator_name="Schema")
+ result.add_success("good", "Valid metadata")
+ for severity, message in (
+ ("low", "Small issue"),
+ ("info", "Nothing needs changing"),
+ ("high", "Risky operation"),
+ ("critical", "Unsafe secret handling"),
+ ("medium", "Missing guidance"),
+ ):
+ result.add_finding(_finding(severity, message))
+ result.summary.high_count = 900
+ result.add_warning("Independent diagnostic counts once without being copied")
+
+ assert summarize_results([result], tier=1, native={"metrics": {"issue_count": 99}}) == {
+ "issue_count": 5,
+ "issue_count_known": True,
+ "critical_count": 1,
+ "high_count": 1,
+ "top_issue": "Unsafe secret handling",
+ }
+
+
[email protected]("incomplete", [False, True])
+def test_clean_and_partial_scans_have_distinct_count_certainty(incomplete):
+ result = ValidationResult(validator_name="Security")
+ if incomplete:
+ result.mark_scan_incomplete("scanner")
+
+ summary = summarize_results([result], tier=1)
+
+ assert summary["issue_count"] == 0
+ assert summary["issue_count_known"] is not incomplete
+ assert summary["top_issue"] is None
+
+
+def test_partial_scan_with_confirmed_findings_keeps_observed_count_unknown_total():
+ result = ValidationResult(validator_name="Security")
+ result.mark_scan_incomplete("scanner")
+ result.add_finding(_finding("critical", "Confirmed issue"))
+
+ summary = summarize_results([result], tier=1)
+
+ assert summary["issue_count"] == 1
+ assert summary["critical_count"] == 1
+ assert summary["issue_count_known"] is False
+
+
[email protected]("results", [[], [ValidationResult(validator_name="QUALITY", metadata={"skipped": True})]])
+def test_absent_and_skipped_scans_do_not_claim_zero_known_issues(results):
+ summary = summarize_results(results, tier=2)
+
+ assert summary["issue_count"] == 0
+ assert summary["issue_count_known"] is False
+
+
+def test_top_issue_is_bounded_single_line_plain_text_from_highest_severity_only():
+ result = ValidationResult(validator_name="Security")
+ result.add_finding(_finding("low", "Earlier low finding"))
+ result.add_finding(
+ _finding("high", "First high\n\x00\u202e<script> [link](javascript:x) | @team `code` " + "x" * 300)
+ )
+ result.add_finding(_finding("high", "Second high finding"))
+
+ summary = summarize_results([result], tier=1)
+ text = summary["top_issue"]
+
+ assert text.startswith("First high")
+ assert len(text) <= 160
+ assert text.endswith("…")
+ assert not any(character in text for character in "\n\x00\u202e<>[]|@`")
+ assert "Earlier low finding" not in text
+ assert "Second high finding" not in text
+ assert json.loads(json.dumps(summary)) == summary
+
+
+def test_info_only_scan_has_no_top_issue():
+ result = ValidationResult(validator_name="Schema", findings=[_finding("info", "Verified safe behavior")])
+
+ assert summarize_results([result], tier=1)["top_issue"] is None
+
+
+def test_repeated_finding_across_locations_and_validators_counts_one_highest_severity_issue():
+ first = _finding("medium", "Repeated problem")
+ second = _finding("high", "Repeated problem")
+ second.file_path = "other/SKILL.md"
+ results = [
+ ValidationResult(validator_name="One", findings=[first]),
+ ValidationResult(validator_name="Two", findings=[second, second]),
+ ]
+
+ summary = summarize_results(results, tier=1)
+
+ assert summary["issue_count"] == 1
+ assert summary["high_count"] == 1
+ assert summary["top_issue"] == "Repeated problem"
+
+
+def test_gate_failure_without_findings_keeps_safe_gate_reason_in_key_information():
+ result = ValidationResult(validator_name="QUALITY")
+ result.fail_gate("Score 40 is below the required minimum 70\n<details> | @team")
+ result.errors.append("Provider diagnostic must not be copied")
+
+ summary = summarize_results([result], tier=2)
+
+ assert summary["issue_count"] == 2
+ assert summary["issue_count_known"] is True
+ assert summary["top_issue"] == "Score 40 is below the required minimum 70 details (at)team"
+
+
+def test_gate_reason_does_not_hide_a_structured_finding():
+ result = ValidationResult(validator_name="QUALITY")
+ result.fail_gate("Score below minimum")
+ result.add_finding(_finding("high", "Fix this concrete problem"))
+
+ assert summarize_results([result], tier=2)["top_issue"] == "Fix this concrete problem"
+
+
[email protected]("strict", [False, True])
+def test_missing_license_legacy_error_or_warning_counts_as_an_issue(tmp_path, strict):
+ (tmp_path / "SKILL.md").write_text("---\nname: example\ndescription: An example skill\n---\n")
+ result = LicenseValidator(strict_mode=strict).validate(tmp_path)
+
+ summary = summarize_results([result], tier=1)
+
+ assert summary["issue_count"] == 1
+ assert summary["issue_count_known"] is True
+ assert summary["critical_count"] == 0
+ assert summary["high_count"] == 0
+ assert summary["top_issue"] == "Additional validation errors/warnings; see report"
+
+
+def test_workflow_scope_warning_does_not_count_as_an_issue():
+ result = ValidationResult(validator_name="Workflow")
+ result.add_warning("Workflow scope: semantic validation was disabled")
+
+ summary = summarize_results([result], tier=1)
+
+ assert summary["issue_count"] == 0
+ assert summary["top_issue"] is None
+
+
+def test_legacy_finding_mirrors_do_not_increase_issue_count():
+ result = ValidationResult(validator_name="Schema")
+ result.add_finding(_finding("high", "Fix a serious problem"))
+ result.add_finding(_finding("low", "Fix a minor problem"))
+ result.add_finding(_finding("info", "Informational finding"))
+
+ assert summarize_results([result], tier=1)["issue_count"] == 2
+
+
+def test_independent_provider_diagnostic_is_counted_without_copying_raw_text():
+ result = ValidationResult(validator_name="QUALITY")
+ result.add_error("Provider diagnostic contains private source content and a credential")
+ result.mark_scan_incomplete("provider")
+
+ summary = summarize_results([result], tier=2)
+
+ assert summary["issue_count"] == 1
+ assert summary["issue_count_known"] is False
+ assert summary["top_issue"] == "Additional validation errors/warnings; see report"
+ assert "private source content" not in json.dumps(summary)
+
+
+def test_tier3_uses_validated_result_metadata_for_scores_and_coverage():
+ result = ValidationResult(
+ validator_name="AGENT_EVAL",
+ metadata={
+ "agent_eval": {
+ "execution_status": "succeeded",
+ "verdict": "pass",
+ "summary": {
+ "overall_score": 0.8,
+ "overall_lift": 0.25,
+ "scored_attempts": 4,
+ "expected_attempts": 4,
+ },
+ }
+ },
+ )
+
+ summary = summarize_results([result], tier=3, native={"tier3": {"overall_score": 1.0}})
+
+ assert summary["score"] == 0.8
+ assert summary["skill_lift"] == 0.25
+ assert summary["coverage"] == "4/4"
+ assert summary["issue_count_known"] is True
+
+
+def test_tier3_missing_execution_does_not_invent_scores_or_zero_coverage():
+ result = ValidationResult(validator_name="AGENT_EVAL")
+
+ summary = summarize_results([result], tier=3)
+
+ assert summary["issue_count_known"] is False
+ assert "score" not in summary
+ assert "skill_lift" not in summary
+ assert "coverage" not in summary
+
+
+def test_tier3_partial_execution_retains_coverage_without_claiming_clean_counts_or_scores():
+ result = ValidationResult(
+ validator_name="AGENT_EVAL",
+ metadata={
+ "agent_eval": {
+ "execution_status": "failed",
+ "summary": {
+ "overall_score": 0.9,
+ "overall_lift": 0.2,
+ "scored_attempts": 1,
+ "expected_attempts": 4,
+ },
+ }
+ },
+ )
+
+ summary = summarize_results([result], tier=3)
+
+ assert summary["issue_count_known"] is False
+ assert summary["coverage"] == "1/4"
+ assert "score" not in summary
+ assert "skill_lift" not in summary
diff --git a/tests/ci/test_tier3_execution_complete.py b/tests/ci/test_tier3_execution_complete.py
new file mode 100644
index 00000000..29acd4ad
--- /dev/null
+++ b/tests/ci/test_tier3_execution_complete.py
@@ -0,0 +1,131 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Paired execution coverage is independent of benchmark metric applicability."""
+
+import copy
+
+import pytest
+
+from ci import tier_manifest
+from skillevaluator.reporting.base import agent_eval_publication_evidence_complete
+
+
+def complete_report(*, baseline_na=True):
+ """Compact native shape, containing no task prompts or model output."""
+ dimensions = [
+ {"id": name, "with_skill": 0.8, "score": 0.8, "baseline": 0.4, "lift": 0.4}
+ for name in ("security", "correctness", "discoverability", "effectiveness", "efficiency")
+ ]
+ agent = {
+ "model": "fixture-model",
+ "execution_status": "succeeded",
+ "execution_errors": [],
+ "with_skill": 0.8,
+ "baseline": 0.4,
+ "lift": 0.4,
+ "dimensions": copy.deepcopy(dimensions),
+ "expected_attempts": 4,
+ "scored_attempts": 4,
+ "conditions": {
+ arm: {"execution_status": "succeeded", "execution_errors": [], "expected_attempts": 2, "scored_attempts": 2}
+ for arm in ("with_skill", "without_skill")
+ },
+ }
+ payload = {
+ "schema_version": "2.0",
+ "mode": "both",
+ "verdict": "pass",
+ "execution_status": "succeeded",
+ "execution_errors": [],
+ "skill_name": "demo",
+ "environment": "local",
+ "evaluator_version": "fixture-1",
+ "publication_target": {
+ "skill_name": "demo",
+ "skill_digest": "sha256:" + "a" * 64,
+ "skill_digest_algorithm": "skill-evaluator-source-tree/2",
+ },
+ "run_id": "fixture-run-001",
+ "evaluated_at": "2026-01-01T00:00:00+00:00",
+ "dataset_digest": "sha256:" + "b" * 64,
+ "dataset_digest_algorithm": "skill-evaluator-dataset-snapshot/1",
+ "dataset_summary": {"total_tasks": 2},
+ "attempt_policy": {"max_attempts": 1, "stop_on_pass": False, "pass_threshold": 0.5},
+ "expected_attempts": 4,
+ "scored_attempts": 4,
+ "best_agent": "fixture-agent",
+ "agents_run": ["fixture-agent"],
+ "overall_score": 0.8,
+ "overall_lift": 0.4,
+ "dimensions": dimensions,
+ }
+ payload["summary"] = copy.deepcopy(payload)
+ payload["agents"] = {"fixture-agent": agent}
+ assert agent_eval_publication_evidence_complete(payload)
+ if baseline_na:
+ for dimension in [*dimensions, *agent["dimensions"]]:
+ if dimension["id"] in {"discoverability", "efficiency"}:
+ dimension.update(baseline=None, lift=None)
+ payload["summary"]["dimensions"] = copy.deepcopy(dimensions)
+ return {
+ "tier3": payload,
+ "incomplete_scans": [],
+ "results": [{"validator": "AGENT_EVAL", "tier3": copy.deepcopy(payload), "incomplete_scans": []}],
+ "publication": {"tier3": {"evidence_complete": not baseline_na}},
+ }
+
+
+def test_complete_execution_with_na_baseline_dimensions_is_not_incomplete():
+ report = complete_report()
+ assert not agent_eval_publication_evidence_complete(report["tier3"])
+ original = copy.deepcopy(report)
+ assert tier_manifest.tier3_execution_complete(report) is True
+ assert report == original
+ assert report["publication"]["tier3"]["evidence_complete"] is False
+
+
[email protected]("verdict", ["pass", "neutral", "fail"])
+def test_execution_complete_does_not_reinterpret_the_native_quality_verdict(verdict):
+ report = complete_report()
+ report["tier3"]["verdict"] = report["tier3"]["summary"]["verdict"] = verdict
+ assert tier_manifest.tier3_execution_complete(report) is True
+
+
+ "key", ["dataset_digest", "dataset_digest_algorithm", "publication_target", "run_id", "evaluated_at"]
+)
+def test_missing_canonical_run_provenance_remains_incomplete(key):
+ report = complete_report()
+ report["tier3"].pop(key)
+ report["tier3"]["summary"].pop(key)
+ assert tier_manifest.tier3_execution_complete(report) is False
+
+
+ "mutate",
+ [
+ lambda p: p["tier3"]["agents"]["fixture-agent"]["conditions"].pop("without_skill"),
+ lambda p: p["tier3"]["summary"].update(mode="with_skill"),
+ lambda p: p["tier3"].update(publication_target_conflict="source changed during evaluation"),
+ lambda p: p["tier3"].update(mode="with_skill"),
+ lambda p: p["tier3"].update(mode="without_skill"),
+ lambda p: p["tier3"].update(scored_attempts=3),
+ lambda p: p["tier3"]["summary"].update(execution_status="failed"),
+ lambda p: p["tier3"].update(verdict="inconclusive"),
+ lambda p: p["tier3"]["agents"]["fixture-agent"]["conditions"]["without_skill"].update(scored_attempts=1),
+ lambda p: p["tier3"]["agents"]["fixture-agent"]["conditions"]["with_skill"].update(
+ execution_status="skipped", expected_attempts=0, scored_attempts=0
+ ),
+ lambda p: p["tier3"]["agents"]["fixture-agent"]["conditions"]["without_skill"].update(
+ execution_errors=["fixture error"]
+ ),
+ lambda p: p["tier3"].update(case_selection={"total": 3, "selected": 2}),
+ lambda p: p["results"][0].update(incomplete_scans=["live-agent"]),
+ lambda p: p.update(incomplete_scans=["live-agent"]),
+ lambda p: p.update(tier3=None),
+ lambda p: p.update(results=[]),
+ ],
+)
+def test_partial_baseline_only_or_contradictory_execution_remains_incomplete(mutate):
+ report = complete_report()
+ mutate(report)
+ assert tier_manifest.tier3_execution_complete(report) is False
diff --git a/tests/ci/test_tier_manifest.py b/tests/ci/test_tier_manifest.py
new file mode 100644
index 00000000..580545ec
--- /dev/null
+++ b/tests/ci/test_tier_manifest.py
@@ -0,0 +1,268 @@
+# SPDX-License-Identifier: Apache-2.0
+"""The aggregate gate and its display depend on typed retained outcomes."""
+
+import copy
+import json
+
+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",
+ "producer": {"workflow": "trusted"},
+ "tiers": [
+ {
+ "tier": tier,
+ "status": "passed",
+ "required": tier == 1,
+ "skills": [
+ {
+ "path": "skills/demo",
+ "status": "passed",
+ "report_json": f"tier{tier}/skill-001/skillevaluator-tier{tier}.json",
+ "report_html": f"tier{tier}/skill-001/skillevaluator-tier{tier}.html",
+ }
+ ],
+ }
+ for tier in (1, 2, 3)
+ ],
+ }
+
+
+def test_advisory_failure_keeps_own_status_without_failing_required_gate():
+ payload = manifest()
+ payload["tiers"][2].update(status="failed", metrics={"score": 0.8, "skill_lift": -0.1, "coverage": "1/1"})
+ payload["tiers"][2]["skills"][0]["status"] = "failed"
+ validated = tier_manifest.validate_manifest(payload)
+ assert validated["overall_passed"] is True
+ assert validated["tiers"][2]["status"] == "failed"
+ assert validated["producer"] == payload["producer"]
+ validated["producer"]["workflow"] = "changed"
+ assert payload["producer"]["workflow"] == "trusted"
+ markdown = tier_manifest.render_markdown(payload, "https://example.test/artifacts/123")
+ assert "Tier 1 | passed | Required" in markdown
+ assert "Tier 2 | passed | Advisory" in markdown
+ assert "Tier 3 | failed | Advisory" in markdown
+ assert "score: 0.8" in markdown and "skill lift: -0.1" in markdown and "coverage: 1/1" in markdown
+ assert "https://example.test/artifacts/123/tier3/skill-001/skillevaluator-tier3.html" in markdown
+
+
[email protected]("tier,status", [(1, "failed"), (2, "incomplete"), (2, "skipped"), (3, "needs_action")])
+def test_required_tier_nonpass_blocks_overall(tier, status):
+ payload = manifest()
+ record = payload["tiers"][tier - 1]
+ record.update(required=True, status=status)
+ record["skills"][0]["status"] = status
+ assert tier_manifest.validate_manifest(payload)["overall_passed"] is False
+
+
+def test_missing_required_tier_and_empty_pass_cannot_claim_success():
+ payload = manifest()
+ payload["tiers"] = payload["tiers"][1:]
+ assert tier_manifest.validate_manifest(payload)["overall_passed"] is False
+ markdown = tier_manifest.render_markdown(payload)
+ assert "Required gate: **Not passed**" in markdown
+ assert "Tier 1 | not_run | Required" in markdown
+ payload = manifest()
+ payload["tiers"][0]["skills"] = []
+ with pytest.raises(ValueError, match=r"empty|nonempty"):
+ tier_manifest.validate_manifest(payload)
+
+
[email protected]("tier", [2, 3])
[email protected]("status", ["failed", "incomplete", "needs_action", "not_run", "neutral", "skipped"])
+def test_paid_advisory_outcomes_do_not_change_required_gate(tier, status):
+ payload = manifest()
+ payload["tiers"][tier - 1]["status"] = status
+ payload["tiers"][tier - 1]["skills"][0]["status"] = status
+ result = tier_manifest.validate_manifest(payload)
+ assert result["overall_passed"] is True
+ assert result["overall_status"] == "passed"
+ assert result["tiers"][tier - 1]["status"] == status
+
+
+def test_missing_paid_advisory_results_do_not_block_tier1():
+ payload = manifest()
+ payload["tiers"] = payload["tiers"][:1]
+ result = tier_manifest.validate_manifest(payload)
+ assert result["overall_passed"] is True
+ assert result["overall_status"] == "passed"
+ markdown = tier_manifest.render_markdown(result)
+ assert "Tier 2 | not_run | Advisory" in markdown
+ assert "Tier 3 | not_run | Advisory" in markdown
+
+
[email protected]("required_paid", [[], [2], [3], [2, 3]])
+def test_report_policy_text_matches_current_or_historical_declared_flags(tmp_path, required_paid):
+ payload = manifest()
+ for tier in required_paid:
+ payload["tiers"][tier - 1]["required"] = True
+ required = "Required tiers: " + ", ".join(f"Tier {tier}" for tier in [1, *required_paid]) + "."
+ advisory = "Advisory tiers: " + ", ".join(f"Tier {tier}" for tier in (2, 3) if tier not in required_paid) + "."
+ if len(required_paid) == 2:
+ advisory = "Advisory tiers: none."
+ tier_manifest.write_reports(tmp_path, payload)
+ for name in ("summary.md", "index.html"):
+ rendered = (tmp_path / name).read_text()
+ assert required in rendered and advisory in rendered
+
+
+ "mutate",
+ [
+ lambda p: p.update(overall_passed=False),
+ lambda p: p.update(run_id="0"),
+ lambda p: p.update(commit="branch"),
+ lambda p: p["tiers"].append(copy.deepcopy(p["tiers"][0])),
+ lambda p: p["tiers"][0].update(tier=True),
+ lambda p: p["tiers"][0].update(required=False),
+ lambda p: p["tiers"][0]["skills"][0].update(status="failed"),
+ lambda p: p["tiers"][0]["skills"][0].update(report_html="../secret.html"),
+ lambda p: p["tiers"][0]["skills"][0].update(report_json="https://evil.test/x"),
+ lambda p: p["tiers"][0]["skills"][0].update(path="skills/demo\nforged"),
+ lambda p: p.update(producer={"number": float("nan")}),
+ ],
+)
+def test_rejects_contradictory_or_unsafe_manifest(mutate):
+ payload = manifest()
+ mutate(payload)
+ with pytest.raises(ValueError):
+ tier_manifest.validate_manifest(payload)
+
+
+def test_write_reports_escapes_content_and_leaves_native_evidence_untouched(tmp_path):
+ payload = manifest()
+ payload["tiers"][1]["metrics"] = {"findings": "<img src=x onerror=alert(1)> | fake"}
+ path = tmp_path / "tier2/skill-001"
+ path.mkdir(parents=True)
+ (path / "skillevaluator-tier2.html").write_text("native evidence")
+ tier_manifest.write_reports(tmp_path, payload)
+ assert json.loads((tmp_path / "ci-results.json").read_text())["overall_passed"] is True
+ html = (tmp_path / "index.html").read_text()
+ assert "Content-Security-Policy" in html
+ assert "&lt;img src=x" in html and "<img src=x" not in html
+ assert 'href="tier2/skill-001/skillevaluator-tier2.html"' in html
+ assert "Tier 3" in html and "Advisory" in html
+ assert "\\| fake" in (tmp_path / "summary.md").read_text()
+ assert (path / "skillevaluator-tier2.html").read_text() == "native evidence"
+
+
+def test_write_reports_rejects_symlink_output(tmp_path):
+ external = tmp_path / "external"
+ external.write_text("keep")
+ output = tmp_path / "reports"
+ output.mkdir()
+ (output / "index.html").symlink_to(external)
+ with pytest.raises(ValueError):
+ tier_manifest.write_reports(output, manifest())
+ assert external.read_text() == "keep"
+
+
+ "mutate",
+ [
+ lambda p: p.update(platform=[]),
+ lambda p: p.update(environment={}),
+ lambda p: p["tiers"][0].update(status=[]),
+ lambda p: p["tiers"][0]["skills"][0].update(status={}),
+ ],
+)
+def test_untyped_discriminators_raise_validation_errors(mutate):
+ payload = manifest()
+ mutate(payload)
+ with pytest.raises(ValueError):
+ tier_manifest.validate_manifest(payload)
+
+
+def test_explicit_expected_tiers_supports_a_single_tier_producer():
+ payload = manifest()
+ payload["expected_tiers"] = [1]
+ payload["tiers"] = payload["tiers"][:1]
+ result = tier_manifest.validate_manifest(payload)
+ assert result["overall_passed"] is True
+ assert result["overall_status"] == "passed"
+ assert "Tier 2 | not_run" in tier_manifest.render_markdown(result)
+
+
+def test_explicit_empty_selection_satisfies_gate_with_skipped_headline():
+ payload = manifest()
+ payload["expected_tiers"] = [1]
+ payload["tiers"] = [
+ {
+ "tier": 1,
+ "required": True,
+ "status": "skipped",
+ "skills": [],
+ "reason": "No selected skills changed; evaluation did not run.",
+ }
+ ]
+ result = tier_manifest.validate_manifest(payload)
+ assert result["overall_passed"] is True
+ assert result["overall_status"] == "skipped"
+ markdown = tier_manifest.render_markdown(result)
+ assert "**Skipped**" in markdown and "Required gate: **Passed**" not in markdown
+
+
+def test_neutral_advisory_result_keeps_its_outcome():
+ payload = manifest()
+ payload["tiers"][2]["status"] = "neutral"
+ payload["tiers"][2]["skills"][0]["status"] = "neutral"
+ result = tier_manifest.validate_manifest(payload)
+ assert result["overall_passed"] is True
+ assert "Tier 3 | neutral | Advisory" in tier_manifest.render_markdown(result)
+
+
+ "path", ["skills/c#-helper", "skills/100%-coverage", "skills/a:b", "skills/why?", "skills/a\\b"]
+)
+def test_skill_directories_may_contain_url_delimiters_but_report_paths_may_not(path):
+ payload = manifest()
+ payload["tiers"][1]["skills"][0]["path"] = path
+ validated = tier_manifest.validate_manifest(payload)
+ assert validated["tiers"][1]["skills"][0]["path"] == path
+ assert tier_manifest.render_markdown(validated)
+ for unsafe in (f"../{path}", f"/{path}", f"{path}/", path.replace("/", "/./")):
+ payload["tiers"][1]["skills"][0]["path"] = unsafe
+ with pytest.raises(ValueError, match="Unsafe skill path"):
+ tier_manifest.validate_manifest(payload)
+ payload = manifest()
+ payload["tiers"][1]["skills"][0]["report_json"] = f"tier2/{path.split('/')[1]}/report.json"
+ with pytest.raises(ValueError, match="Unsafe report_json"):
+ tier_manifest.validate_manifest(payload)
+
+
+def test_tier_source_attempt_is_an_earlier_or_current_attempt_of_the_run():
+ payload = manifest()
+ payload["run_attempt"] = "2"
+ payload["tiers"][0]["source_attempt"] = "1"
+ payload["tiers"][1]["source_attempt"] = "2"
+ validated = tier_manifest.validate_manifest(payload)
+ assert [record.get("source_attempt") for record in validated["tiers"]] == ["1", "2", None]
+ markdown = tier_manifest.render_markdown(validated)
+ assert "evidence from run attempt 1" in markdown
+ assert "evidence from run attempt 2" not in markdown
+ for invalid in ("3", "0", 1, ""):
+ payload["tiers"][0]["source_attempt"] = invalid
+ with pytest.raises(ValueError, match="source_attempt"):
+ tier_manifest.validate_manifest(payload)
+
+
+def test_documented_tier_statuses_match_the_manifest_contract():
+ import re
+ from pathlib import Path
+
+ text = " ".join((Path(__file__).parents[2] / "docs/reports.mdx").read_text().split())
+ sentence = re.search(r"A tier can be (.+?)\.", text)
+ assert sentence is not None
+ assert set(re.findall(r"`([a-z_]+)`", sentence[1])) == tier_manifest._STATUSES
diff --git a/tests/embedding/test_registry.py b/tests/embedding/test_registry.py
index 8a2b62ae..64d5cf3a 100644
--- a/tests/embedding/test_registry.py
+++ b/tests/embedding/test_registry.py
@@ -83,6 +83,27 @@ def _make_mock_client(vectors: list[list[float]]) -> EmbeddingClient:
return client
+def test_build_explicit_paths_preserves_cross_root_identity(tmp_path: Path, write_skill) -> None:
+ first = write_skill(tmp_path / "skills", "alpha", description="First distinct fixture")
+ second = write_skill(tmp_path / ".agents/skills", "alpha", description="Second distinct fixture")
+ registry = EmbeddingRegistry(_make_mock_client([[1.0, 0.0], [0.0, 1.0]]))
+ assert registry.build_from_paths(tmp_path, [first, second]) == 2
+ catalog = tmp_path / "catalog.json"
+ registry.save_catalog(catalog)
+ data = json.loads(catalog.read_text())
+ assert {entry["path"] for entry in data["entries"]} == {"skills/alpha", ".agents/skills/alpha"}
+
+
+def test_build_explicit_paths_rejects_outside_root_before_embedding(tmp_path: Path, write_skill) -> None:
+ outside = write_skill(tmp_path / "outside", "alpha", description="Outside fixture")
+ root = tmp_path / "workspace"
+ root.mkdir()
+ client = _make_mock_client([[1.0, 0.0]])
+ with pytest.raises(ValueError, match="outside"):
+ EmbeddingRegistry(client).build_from_paths(root, [outside])
+ client.embed.assert_not_called()
+
+
class TestBuildFromDirectory:
def test_empty_collection_debug_logs_use_label_without_host_path(self, tmp_path: Path, monkeypatch) -> None:
collection = tmp_path / "nested" / "external-skills"
diff --git a/tests/golden/cli_surface.json b/tests/golden/cli_surface.json
index d7e1b5d9..50e338fe 100644
--- a/tests/golden/cli_surface.json
+++ b/tests/golden/cli_surface.json
@@ -4,6 +4,27 @@
"commands": {
"demo": {
"params": [
+ {
+ "choices": [
+ "auto",
+ "github",
+ "gitlab"
+ ],
+ "default": "auto",
+ "name": "platform",
+ "opts": [
+ "--platform"
+ ],
+ "param_type": "option"
+ },
+ {
+ "name": "tiers",
+ "opts": [
+ "--tiers"
+ ],
+ "param_type": "option",
+ "type": "text"
+ },
{
"default": "<callable pathlib.Path.cwd>",
"name": "repo",
@@ -27,6 +48,141 @@
},
"init": {
"params": [
+ {
+ "name": "tiers",
+ "opts": [
+ "--tiers"
+ ],
+ "param_type": "option",
+ "type": "text"
+ },
+ {
+ "choices": [
+ "auto",
+ "github",
+ "gitlab"
+ ],
+ "default": "auto",
+ "name": "platform",
+ "opts": [
+ "--platform"
+ ],
+ "param_type": "option"
+ },
+ {
+ "choices": [
+ "docker",
+ "local"
+ ],
+ "default": "docker",
+ "name": "env_mode",
+ "opts": [
+ "--env-mode"
+ ],
+ "param_type": "option"
+ },
+ {
+ "choices": [
+ "openai",
+ "anthropic",
+ "nv_build"
+ ],
+ "default": "openai",
+ "name": "provider",
+ "opts": [
+ "--provider"
+ ],
+ "param_type": "option"
+ },
+ {
+ "choices": [
+ "openai",
+ "nv_build"
+ ],
+ "name": "embedding_provider",
+ "opts": [
+ "--embedding-provider"
+ ],
+ "param_type": "option"
+ },
+ {
+ "name": "model",
+ "opts": [
+ "--model"
+ ],
+ "param_type": "option",
+ "type": "text"
+ },
+ {
+ "name": "embedding_model",
+ "opts": [
+ "--embedding-model"
+ ],
+ "param_type": "option",
+ "type": "text"
+ },
+ {
+ "name": "agents",
+ "opts": [
+ "--agents"
+ ],
+ "param_type": "option",
+ "type": "text"
+ },
+ {
+ "name": "runner",
+ "opts": [
+ "--runner"
+ ],
+ "param_type": "option",
+ "type": "text"
+ },
+ {
+ "default": "False",
+ "is_flag": true,
+ "name": "tier3_required",
+ "opts": [
+ "--tier3-required"
+ ],
+ "param_type": "option",
+ "type": "boolean"
+ },
+ {
+ "default": "1",
+ "name": "n_attempts",
+ "opts": [
+ "--n-attempts"
+ ],
+ "param_type": "option",
+ "type": "integer range"
+ },
+ {
+ "default": "1",
+ "name": "n_concurrent",
+ "opts": [
+ "--n-concurrent"
+ ],
+ "param_type": "option",
+ "type": "integer range"
+ },
+ {
+ "default": "300",
+ "name": "timeout_minutes",
+ "opts": [
+ "--timeout-minutes"
+ ],
+ "param_type": "option",
+ "type": "integer range"
+ },
+ {
+ "default": "skillevaluator",
+ "name": "environment",
+ "opts": [
+ "--environment"
+ ],
+ "param_type": "option",
+ "type": "text"
+ },
{
"default": "<callable pathlib.Path.cwd>",
"name": "repo",
@@ -144,6 +300,27 @@
},
"status": {
"params": [
+ {
+ "choices": [
+ "auto",
+ "github",
+ "gitlab"
+ ],
+ "default": "auto",
+ "name": "platform",
+ "opts": [
+ "--platform"
+ ],
+ "param_type": "option"
+ },
+ {
+ "name": "tiers",
+ "opts": [
+ "--tiers"
+ ],
+ "param_type": "option",
+ "type": "text"
+ },
{
"default": "<callable pathlib.Path.cwd>",
"name": "repo",
diff --git a/tests/reporting/test_retained_html.py b/tests/reporting/test_retained_html.py
index af31b971..b8020b90 100644
--- a/tests/reporting/test_retained_html.py
+++ b/tests/reporting/test_retained_html.py
@@ -143,7 +143,7 @@ def test_retained_finding_failure_cannot_claim_a_passing_result(payload):
retained_results(payload)
-def test_advisory_skip_keeps_required_gate_but_is_outside_retained_tier1_contract():
+def test_advisory_skip_keeps_required_gate_and_explicit_tier1_boundary():
from skillevaluator.evaluation.tier3_report import advisory_skip_result
from skillevaluator.reporting.base import is_cleanly_skipped, passes_required_gate
@@ -154,7 +154,8 @@ def test_advisory_skip_keeps_required_gate_but_is_outside_retained_tier1_contrac
assert emitted["overall_passed"] is True
assert emitted["results"][0]["status"] == "skipped"
with pytest.raises(RetainedReportError, match="Only retained Tier 1 reports are supported"):
- retained_results(emitted)
+ retained_results(emitted, allowed_tiers={1})
+ assert retained_results(emitted)[0].passed is False
@pytest.mark.parametrize(
diff --git a/tests/reporting/test_retained_tiers.py b/tests/reporting/test_retained_tiers.py
new file mode 100644
index 00000000..d5415e81
--- /dev/null
+++ b/tests/reporting/test_retained_tiers.py
@@ -0,0 +1,170 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Public Tier 2 and 3 JSON can be re-rendered without inventing evidence."""
+
+import json
+
+import pytest
+
+from skillevaluator.evaluation.tier3_report import advisory_skip_result, build_agent_eval_payload
+from skillevaluator.models import Finding, ValidationResult
+from skillevaluator.reporting.json_reporter import JSONReporter
+from skillevaluator.reporting.retained import RetainedReportError, retained_results
+from skillevaluator.tier3.harbor.metrics import DEFAULT_METRICS
+
+
+def emit(result):
+ return json.loads(JSONReporter(include_timestamp=False).render_all([result]))
+
+
+def tier3_result():
+ conditions = {
+ arm: {"execution_status": "succeeded", "execution_errors": [], "expected_attempts": 1, "scored_attempts": 1}
+ for arm in ("with_skill", "without_skill")
+ }
+ payload = build_agent_eval_payload(
+ "demo",
+ {
+ "opencode": {
+ "with_skill": dict.fromkeys(DEFAULT_METRICS, 0.8),
+ "without_skill": dict.fromkeys(DEFAULT_METRICS, 0.4),
+ "execution_status": "succeeded",
+ "execution_errors": [],
+ "expected_attempts": 2,
+ "scored_attempts": 2,
+ "conditions": conditions,
+ "num_trials": 1,
+ "num_trials_baseline": 1,
+ }
+ },
+ dataset=[{"id": "case-a"}],
+ attempt_policy={"max_attempts": 1, "stop_on_pass": False, "pass_threshold": 0.5},
+ use_llm_judge=False,
+ )
+ return ValidationResult(
+ validator_name="AGENT_EVAL", metadata={"agent_eval": payload, "gating": {"tier": 3, "blocking": False}}
+ )
+
+
+def test_tier2_retains_llm_and_work_limit_evidence():
+ result = ValidationResult(
+ validator_name="Context Optimization",
+ metadata={
+ "gating": {"tier": 2, "blocking": True},
+ "llm_analysis": {"completed_clusters": 2, "failed_clusters": 0},
+ "work_limit": {"reason": "cluster budget", "limit": 2},
+ },
+ )
+ result.add_finding(
+ Finding(
+ category="CONTENT_DEDUP",
+ severity="medium",
+ check_name="redundancy",
+ message="Repeated guidance",
+ file_path="SKILL.md",
+ )
+ )
+ payload = emit(result)
+ restored = retained_results(payload)
+ assert restored[0].metadata["work_limit"] == result.metadata["work_limit"]
+ assert emit(restored[0])["results"] == payload["results"]
+
+
+def test_tier3_roundtrip_keeps_canonical_agent_payload():
+ payload = emit(tier3_result())
+ restored = retained_results(payload)
+ assert restored[0].metadata["agent_eval"] == payload["results"][0]["tier3"]
+ assert emit(restored[0])["tier3"] == payload["tier3"]
+
+
+def test_completed_native_tier3_quality_failure_retains_execution_success():
+ from skillevaluator.evaluation.tier3_report import _validation_result_from_payload
+
+ payload = tier3_result().metadata["agent_eval"]
+ payload["verdict"] = payload["summary"]["verdict"] = "fail"
+ native = _validation_result_from_payload(payload)
+ native.metadata["gating"] = {"tier": 3, "blocking": False}
+ assert native.passed is True
+ document = emit(native)
+ assert document["results"][0]["status"] == "failed"
+ restored = retained_results(document)
+ assert restored[0].passed is True
+ assert emit(restored[0])["results"][0]["status"] == "failed"
+ assert document["overall_passed"] is True
+
+
+def test_advisory_incomplete_retains_gate_pass_and_result_failure():
+ result = tier3_result()
+ result.passed = False
+ result.mark_scan_incomplete("live-agent")
+ payload = emit(result)
+ assert payload["overall_passed"] is True
+ assert payload["results"][0]["status"] == "incomplete"
+ assert retained_results(payload)[0].is_incomplete
+
+
+def test_explicit_tier1_boundary_rejects_other_tiers():
+ payload = emit(advisory_skip_result("Unavailable", skill_name="demo"))
+ with pytest.raises(RetainedReportError, match=r"Tier 1|allowed"):
+ retained_results(payload, allowed_tiers={1})
+
+
+def test_gating_cannot_disguise_tier3_as_tier1():
+ payload = emit(tier3_result())
+ payload["results"][0]["gating"]["tier"] = 1
+ with pytest.raises(RetainedReportError, match="gating"):
+ retained_results(payload)
+
+
+def test_native_tier3_uses_trusted_render_for_dynamic_csp():
+ from ci.native_reports import render_native_retained_report
+
+ result = tier3_result()
+ result.metadata["agent_eval"]["suggestions"] = ["</script><img src=x onerror=alert(1)>"]
+ document = render_native_retained_report(emit(result), skill_name="skills/demo", expected_skill_name="demo")
+ assert "Content-Security-Policy" in document and "sha256-" in document
+ assert "showTier3SubTab" in document
+ assert "<img src=x onerror=alert(1)>" not in document
+ assert "<script src=" not in document
+ assert "unsafe-eval" not in document
+
+
+ "key,value", [("summary", []), ("agents", []), ("dataset", {}), ("dimensions", {}), ("execution_errors", {})]
+)
+def test_tier3_rejects_malformed_native_containers(key, value):
+ payload = emit(tier3_result())
+ payload["results"][0]["tier3"][key] = value
+ with pytest.raises(RetainedReportError, match="tier3"):
+ retained_results(payload)
+
+
+def test_native_tier3_links_reports_root_and_its_actual_json_filename():
+ from ci.native_reports import render_native_retained_report
+
+ document = render_native_retained_report(
+ emit(tier3_result()),
+ skill_name="skills/demo",
+ context={"report_index_url": "../../index.html", "canonical_json_url": "skillevaluator-tier3.json"},
+ )
+ assert 'href="../../index.html"' in document
+ assert 'href="skillevaluator-tier3.json"' in document
+ assert 'href="skillevaluator-tier1.json"' not in document
+
+
+def test_public_tier3_applicability_survives_retention():
+ result = tier3_result()
+ result.metadata["tier3_applicability"] = {"status": "not_applicable", "reason": "No live cases"}
+ payload = emit(result)
+ assert payload["tier3_applicability"] == result.metadata["tier3_applicability"]
+ assert retained_results(payload)[0].metadata["tier3_applicability"] == payload["tier3_applicability"]
+
+
+def test_advisory_failed_result_keeps_overall_required_gate_pass():
+ result = tier3_result()
+ result.passed = False
+ result.metadata["agent_eval"]["verdict"] = "fail"
+ result.metadata["agent_eval"]["summary"]["verdict"] = "fail"
+ payload = emit(result)
+ assert payload["overall_passed"] is True and payload["overall_status"] == "passed"
+ assert payload["results"][0]["status"] == "failed"
+ assert retained_results(payload)[0].passed is False
diff --git a/tests/test_ci_onboarding_all_tiers.py b/tests/test_ci_onboarding_all_tiers.py
new file mode 100644
index 00000000..a946d321
--- /dev/null
+++ b/tests/test_ci_onboarding_all_tiers.py
@@ -0,0 +1,1033 @@
+"""Opt-in all-tier consumer onboarding, separate from released Tier 1 callers."""
+
+import json
+import subprocess
+
+import pytest
+import yaml
+from click.testing import CliRunner
+
+from skillevaluator.cli import cli
+from test_ci_onboarding import RELEASE
+from test_ci_onboarding import release_file as _release_file
+from test_ci_onboarding import repository as _repository
+
+repository = _repository
+release_file = _release_file
+
+ALL_RELEASE = {
+ **RELEASE,
+ "schema_version": 2,
+ "capabilities": ["all-tiers-github", "all-tiers-gitlab"],
+ "feedback_ref": "d" * 40,
+ "gitlab_ref": "e" * 40,
+ "tools_ref": "f" * 40,
+}
+
+
+def all_release(tmp_path):
+ path = tmp_path / "candidate.json"
+ path.write_text(json.dumps(ALL_RELEASE))
+ return path
+
+
+def invoke(repo, release, *args):
+ return CliRunner().invoke(
+ cli, ["ci", "init", "--repo", str(repo), "--release", str(release), "--tiers", "1,2,3", "--no-input", *args]
+ )
+
+
+def test_all_tiers_save_github_is_minimal_pinned_and_idempotent(repository, all_release):
+ result = invoke(repository, all_release, "--mode", "save", "--paths", "skills")
+ assert result.exit_code == 0, result.output
+ scan_path = repository / ".github/workflows/skill-checks-all-tiers.yml"
+ scan = yaml.safe_load(scan_path.read_text())
+ job = scan["jobs"]["skills"]
+ assert job["uses"].endswith("/evaluate-all-tiers.yml@" + ALL_RELEASE["workflow_ref"])
+ assert job["with"]["env-mode"] == "docker"
+ assert job["with"]["tiers"] == "1,2,3"
+ assert "tier3-required" not in job["with"]
+ assert job["with"]["image"] == ALL_RELEASE["image"]
+ feedback = yaml.safe_load((repository / ".github/workflows/feedback-all-tiers.yml").read_text())
+ assert feedback["jobs"]["feedback"]["with"]["trusted-caller-blobs"]
+ assert feedback["jobs"]["feedback"]["uses"].endswith("@" + ALL_RELEASE["feedback_ref"])
+ assert not (repository / ".github/workflows/publish-skill-reports.yml").exists()
+ assert invoke(repository, all_release, "--mode", "save", "--paths", "skills").exit_code == 0
+
+
+def test_all_tiers_preview_offline_and_local_options(repository, all_release, monkeypatch):
+ monkeypatch.setenv("GH_HOST", "unrelated.example")
+ before = subprocess.check_output(["git", "-C", str(repository), "status", "--porcelain"])
+ result = invoke(
+ repository,
+ all_release,
+ "--mode",
+ "preview",
+ "--env-mode",
+ "local",
+ "--provider",
+ "anthropic",
+ "--embedding-provider",
+ "openai",
+ "--model",
+ "claude-test",
+ "--embedding-model",
+ "embed-test",
+ "--agents",
+ "native",
+ "--runner",
+ "self-hosted",
+ "--show-files",
+ )
+ assert result.exit_code == 0, result.output
+ assert "env-mode: local" in result.output
+ assert "embedding-provider: openai" in result.output
+ assert subprocess.check_output(["git", "-C", str(repository), "status", "--porcelain"]) == before
+
+
+def test_all_tiers_requires_capability_instead_of_using_legacy_refs(repository, release_file):
+ result = invoke(repository, release_file, "--mode", "preview")
+ assert result.exit_code != 0
+ assert "all-tier" in result.output.lower()
+ assert "release" in result.output.lower()
+
+
[email protected]("args", [("--embedding-provider", "anthropic"), ("--n-concurrent", "17")])
+def test_unsupported_runtime_configuration_is_rejected_before_files(repository, all_release, args):
+ before = subprocess.check_output(["git", "-C", str(repository), "status", "--porcelain"])
+ result = invoke(repository, all_release, "--mode", "save", *args)
+ assert result.exit_code != 0
+ assert subprocess.check_output(["git", "-C", str(repository), "status", "--porcelain"]) == before
+
+
+def test_all_tiers_conflict_does_not_partially_save(repository, all_release):
+ target = repository / ".github/workflows/feedback-all-tiers.yml"
+ target.write_text("name: Keep me\n")
+ result = invoke(repository, all_release, "--mode", "save")
+ assert result.exit_code != 0
+ assert not (repository / ".github/workflows/skill-checks-all-tiers.yml").exists()
+ assert target.read_text() == "name: Keep me\n"
+
+
+def test_gitlab_feedback_bootstrap_pins_are_literal_inputs(repository, all_release):
+ subprocess.run(
+ ["git", "-C", str(repository), "remote", "set-url", "origin", "[email protected]:group/consumer.git"],
+ check=True,
+ )
+ result = invoke(repository, all_release, "--mode", "save", "--paths", "skills")
+ assert result.exit_code == 0, result.output
+ feedback = yaml.safe_load((repository / ".gitlab/skill-feedback.yml").read_text())
+ inputs = feedback["include"][0]["inputs"]
+ assert inputs["tools-ref"] == ALL_RELEASE["tools_ref"]
+ assert inputs["tools-repository"] == "NVIDIA/SkillEvaluator"
+ assert inputs["api-url"] == "https://gitlab.example.test/api/v4"
+ assert inputs["project-id"] == "group/consumer"
+
+
+def test_gitlab_selfhosted_save_is_two_files_and_no_global_auth(repository, all_release):
+ subprocess.run(
+ [
+ "git",
+ "-C",
+ str(repository),
+ "remote",
+ "set-url",
+ "origin",
+ "[email protected]:group/nested/consumer.git",
+ ],
+ check=True,
+ )
+ result = invoke(repository, all_release, "--mode", "save", "--platform", "gitlab")
+ assert result.exit_code == 0, result.output
+ scan = yaml.safe_load((repository / ".gitlab-ci.yml").read_text())
+ assert ALL_RELEASE["gitlab_ref"] in scan["include"][0]["remote"]
+ assert scan["variables"]["SKILL_EVAL_ENV_MODE"] == "docker"
+ feedback = (repository / ".gitlab/skill-feedback.yml").read_text()
+ assert "feedback.yml" in feedback
+ assert "protected" in result.output.lower()
+
+
[email protected]("tiers", ["3", "1,4", "1,1,2,3"])
+def test_invalid_tier_selection_fails_before_writes(repository, all_release, tiers):
+ result = CliRunner().invoke(
+ cli,
+ [
+ "ci",
+ "init",
+ "--repo",
+ str(repository),
+ "--release",
+ str(all_release),
+ "--tiers",
+ tiers,
+ "--no-input",
+ "--mode",
+ "save",
+ ],
+ )
+ assert result.exit_code != 0
+ assert not (repository / ".github/workflows/skill-checks-all-tiers.yml").exists()
+
+
+def test_github_setup_pr_is_api_only_and_preserves_checkout(repository, all_release, monkeypatch):
+ from skillevaluator import ci_onboarding as wizard
+
+ mutations = []
+ before = subprocess.check_output(["git", "-C", str(repository), "status", "--porcelain"])
+
+ def api(method, endpoint, payload=None, **kwargs):
+ if method == "POST":
+ mutations.append((endpoint, payload))
+ if endpoint.endswith("/git/trees"):
+ return {"sha": "a" * 40}
+ if endpoint.endswith("/git/commits"):
+ return {"sha": "b" * 40}
+ if endpoint.endswith("/git/refs"):
+ return {}
+ if endpoint.endswith("/pulls"):
+ return {"html_url": "https://github.com/example-org/consumer/pull/1"}
+ raise AssertionError(endpoint)
+ if endpoint == "repos/example-org/consumer":
+ return {"default_branch": "trunk"}
+ if "/contents/" in endpoint or endpoint.endswith("/git/ref/heads/ci%2Fskillevaluator-all-tiers-setup"):
+ return None
+ if "/pulls?" in endpoint:
+ return []
+ if endpoint.endswith("/git/ref/heads/trunk"):
+ return {"object": {"sha": "c" * 40}}
+ if endpoint.endswith("/git/commits/" + "c" * 40):
+ return {"tree": {"sha": "d" * 40}}
+ raise AssertionError(endpoint)
+
+ 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")
+ assert result.exit_code == 0, result.output
+ assert "https://github.com/example-org/consumer/pull/1" in result.output
+ tree = next(payload for endpoint, payload in mutations if endpoint.endswith("/git/trees"))
+ assert {entry["path"] for entry in tree["tree"]} == {
+ ".github/workflows/skill-checks-all-tiers.yml",
+ ".github/workflows/feedback-all-tiers.yml",
+ }
+ texts = {entry["path"]: entry["content"] for entry in tree["tree"]}
+ feedback = yaml.safe_load(texts[".github/workflows/feedback-all-tiers.yml"])
+ 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 subprocess.check_output(["git", "-C", str(repository), "status", "--porcelain"]) == before
+
+
+def test_gitlab_token_api_rejects_host_mismatch_before_network(monkeypatch):
+ from skillevaluator import _ci_onboarding_all_tiers as all_tiers
+
+ monkeypatch.setenv("SKILLEVALUATOR_GITLAB_TOKEN", "private-test-value")
+ monkeypatch.setenv("SKILLEVALUATOR_GITLAB_API_URL", "https://different.example/api/v4")
+ with pytest.raises(Exception, match="origin host") as error:
+ all_tiers.gitlab_api("https://gitlab.example", "GET", "projects/test")
+ assert "private-test-value" not in str(error.value)
+
+
+def test_gitlab_demo_updates_existing_manifest_and_needs_merged_setup(repository, monkeypatch):
+ import base64
+
+ from skillevaluator import _ci_onboarding_all_tiers as all_tiers
+
+ subprocess.run(
+ ["git", "-C", str(repository), "remote", "set-url", "origin", "https://gitlab.example.test/group/consumer.git"],
+ check=True,
+ )
+ mutations = []
+
+ def api(origin, method, endpoint, payload=None, **kwargs):
+ if method == "POST":
+ mutations.append((endpoint, payload))
+ return (
+ {"web_url": "https://gitlab.example.test/group/consumer/-/merge_requests/2"}
+ if endpoint.endswith("/merge_requests")
+ else {}
+ )
+ if endpoint == "projects/group%2Fconsumer":
+ return {"default_branch": "trunk"}
+ if "/merge_requests?" in endpoint:
+ return []
+ if "/repository/branches/" in endpoint:
+ return None
+ if "/repository/tree?" in endpoint:
+ return [{"type": "blob", "path": "skills/a/SKILL.md"}]
+ if "/repository/files/" in endpoint:
+ content = (
+ "variables:\n SKILL_EVAL_PATHS: skills\n" if ".gitlab-ci.yml?" in endpoint else "# Example skill\n"
+ )
+ return {"encoding": "base64", "content": base64.b64encode(content.encode()).decode()}
+ raise AssertionError(endpoint)
+
+ monkeypatch.setattr(all_tiers, "gitlab_api", api)
+ result = CliRunner().invoke(cli, ["ci", "demo", "--repo", str(repository), "--no-input", "--tiers", "1,2,3"])
+ assert result.exit_code == 0, result.output
+ commit = next(payload for endpoint, payload in mutations if endpoint.endswith("/repository/commits"))
+ assert commit["actions"][0]["action"] == "update"
+ assert "automatic feedback" in commit["actions"][0]["content"]
+ review = next(payload for endpoint, payload in mutations if endpoint.endswith("/merge_requests"))
+ assert "required Tier 1" in review["description"]
+ assert "advisory Tier 2 and paired Tier 3" in review["description"]
+
+
+def test_existing_setup_branch_with_extra_files_is_not_reused(repository, all_release, monkeypatch):
+ from skillevaluator import _ci_onboarding_all_tiers as all_tiers
+ from skillevaluator import ci_onboarding as wizard
+
+ client = all_tiers.Client(wizard, "github", "https://github.com", "example-org/consumer")
+
+ def api(method, endpoint, payload=None, **kwargs):
+ assert method == "GET"
+ if "/pulls?" in endpoint:
+ return [{"html_url": "https://github.com/example-org/consumer/pull/1"}]
+ if "/git/ref/heads/" in endpoint:
+ return {"object": {"sha": "a" * 40}}
+ if "/contents/" in endpoint:
+ import base64
+
+ return {"encoding": "base64", "content": base64.b64encode(b"generated").decode()}
+ if "/compare/" in endpoint:
+ return {"files": [{"filename": "one.yml"}, {"filename": "unrelated.txt"}]}
+ raise AssertionError(endpoint)
+
+ monkeypatch.setattr(wizard, "github_api", api)
+ with pytest.raises(wizard.SetupError, match="other changes"):
+ client.create("setup", "trunk", {"one.yml": "generated"}, "title", "body", setup=True)
+
+
+def test_gitlab_local_render_sets_actual_runtime_inputs(repository, all_release):
+ subprocess.run(
+ ["git", "-C", str(repository), "remote", "set-url", "origin", "https://gitlab.example.test/group/consumer.git"],
+ check=True,
+ )
+ result = invoke(repository, all_release, "--mode", "save", "--env-mode", "local", "--timeout-minutes", "45")
+ assert result.exit_code == 0, result.output
+ scan = yaml.safe_load((repository / ".gitlab-ci.yml").read_text())
+ assert scan["variables"]["SKILL_EVAL_IMAGE"] == ALL_RELEASE["image"]
+ # 45 minutes minus min(20, 45 // 4) leaves time to retain evidence.
+ assert scan["variables"]["SKILL_EVAL_TIMEOUT_SECONDS"] == "2040"
+ assert "SKILL_EVAL_JOB_TIMEOUT" not in scan["variables"]
+ assert scan["skill-evaluation-native"]["timeout"] == "45 minutes"
+ assert scan["variables"]["SKILL_EVAL_RUNNER"] == "docker"
+ assert scan["skill-evaluation-native"]["services"] == []
+
+
+def test_github_feedback_identity_names_exact_reusable_workflow(repository, all_release):
+ result = invoke(repository, all_release, "--mode", "save")
+ assert result.exit_code == 0, result.output
+ feedback = yaml.safe_load((repository / ".github/workflows/feedback-all-tiers.yml").read_text())
+ expected = "NVIDIA/SkillEvaluator/.github/workflows/evaluate-all-tiers.yml@" + ALL_RELEASE["workflow_ref"]
+ assert feedback["jobs"]["feedback"]["with"]["trusted-workflow-ref"] == expected
+
+
+def test_live_all_tier_status_recognizes_scan_and_approval(repository, all_release, monkeypatch):
+ import base64
+
+ from skillevaluator import ci_onboarding as wizard
+
+ assert invoke(repository, all_release, "--mode", "save").exit_code == 0
+
+ def api(method, endpoint, payload=None, **kwargs):
+ assert method == "GET"
+ if endpoint == "repos/example-org/consumer":
+ return {"default_branch": "trunk"}
+ for path in [".github/workflows/skill-checks-all-tiers.yml", ".github/workflows/feedback-all-tiers.yml"]:
+ if "/contents/" + path + "?" in endpoint:
+ return {"encoding": "base64", "content": base64.b64encode((repository / path).read_bytes()).decode()}
+ if "/runs?" in endpoint:
+ return {"workflow_runs": []}
+ raise AssertionError(endpoint)
+
+ monkeypatch.setattr(wizard, "github_api", api)
+ result = CliRunner().invoke(cli, ["ci", "status", "--repo", str(repository)])
+ assert result.exit_code == 0, result.output
+ assert "matches exact workflow" in result.output
+ assert "not a verified scan" in result.output
+
+
+ ("component", "content"),
+ [
+ (
+ "checks",
+ "jobs:\n skills:\n uses: NVIDIA/SkillEvaluator/.github/workflows/evaluate.yml@"
+ + "a" * 40
+ + "\n with:\n tiers: '1,2,3'\n",
+ ),
+ (
+ "checks",
+ "jobs:\n skills:\n uses: NVIDIA/SkillEvaluator/.github/workflows/evaluate-all-tiers.yml@main"
+ "\n with:\n tiers: '1,2,3'\n",
+ ),
+ (
+ "checks",
+ "jobs:\n skills:\n uses: NVIDIA/SkillEvaluator/.github/workflows/evaluate-all-tiers.yml@"
+ + "a" * 40
+ + "\n with:\n tiers: '1'\n",
+ ),
+ ("checks", "jobs: ["),
+ ("checks", {}),
+ ("feedback", {}),
+ ("feedback", "null\n"),
+ ("feedback", "- not a workflow\n"),
+ ("feedback", "jobs: ["),
+ (
+ "feedback",
+ "jobs:\n feedback:\n uses: NVIDIA/SkillEvaluator/.github/workflows/feedback-all-tiers.yml@"
+ + "a" * 40
+ + "\n with: []\n",
+ ),
+ ],
+)
+def test_github_status_does_not_claim_invalid_workflows_are_configured(
+ repository, all_release, monkeypatch, component, content
+):
+ import base64
+
+ from skillevaluator import ci_onboarding as wizard
+
+ assert invoke(repository, all_release, "--mode", "save").exit_code == 0
+ texts = {
+ path: (repository / path).read_text()
+ for path in [".github/workflows/skill-checks-all-tiers.yml", ".github/workflows/feedback-all-tiers.yml"]
+ }
+ target = ".github/workflows/" + (
+ "skill-checks-all-tiers.yml" if component == "checks" else "feedback-all-tiers.yml"
+ )
+ if isinstance(content, dict):
+ document = yaml.safe_load(texts[target])
+ document["jobs"]["skills" if component == "checks" else "feedback"]["with"] = content
+ texts[target] = yaml.safe_dump(document)
+ else:
+ texts[target] = content
+
+ def api(method, endpoint, payload=None, **kwargs):
+ assert method == "GET"
+ if endpoint == "repos/example-org/consumer":
+ return {"default_branch": "trunk"}
+ for path, text in texts.items():
+ if "/contents/" + path + "?" in endpoint:
+ return {"encoding": "base64", "content": base64.b64encode(text.encode()).decode()}
+ if "/runs?" in endpoint:
+ return {"workflow_runs": []}
+ raise AssertionError(endpoint)
+
+ monkeypatch.setattr(wizard, "github_api", api)
+ result = CliRunner().invoke(cli, ["ci", "status", "--repo", str(repository), "--tiers", "1,2,3"])
+ assert result.exit_code == 0, result.output
+ label = "All-tier checks" if component == "checks" else "Trusted feedback"
+ assert label + ": configured" not in result.output
+ output = " ".join(result.output.split())
+ assert "not an all-tier configuration" in output or "not a trusted feedback configuration" in output
+
+
+def test_generated_github_caller_grants_every_reusable_job_permission(repository, all_release):
+ from pathlib import Path
+
+ assert invoke(repository, all_release, "--mode", "save").exit_code == 0
+ caller = yaml.safe_load((repository / ".github/workflows/skill-checks-all-tiers.yml").read_text())
+ reusable = yaml.safe_load((Path(__file__).parents[1] / ".github/workflows/evaluate-all-tiers.yml").read_text())
+ levels = {"none": 0, "read": 1, "write": 2}
+ grants = caller["permissions"]
+ for job in reusable["jobs"].values():
+ for permission, access in job.get("permissions", {}).items():
+ assert levels[grants.get(permission, "none")] >= levels[access], permission
+
+
+def test_generated_gitlab_root_is_accepted_by_trusted_feedback_and_has_root_rules(repository, all_release):
+ from ci.feedback import validate_gitlab_config
+
+ subprocess.run(
+ ["git", "-C", str(repository), "remote", "set-url", "origin", "https://gitlab.example.test/group/consumer.git"],
+ check=True,
+ )
+ assert invoke(repository, all_release, "--mode", "save").exit_code == 0
+ document = yaml.safe_load((repository / ".gitlab-ci.yml").read_text())
+ validate_gitlab_config(document)
+ assert len(document["include"]) == 2
+ root_rules = document["skill-evaluation"]["rules"]
+ assert {"if": '$SKILL_EVAL_FEEDBACK == "true"', "when": "never"} in root_rules
+ assert {"if": '$CI_PIPELINE_SOURCE == "merge_request_event"'} in root_rules
+ assert {"if": "$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH"} in root_rules
+ assert {"if": '$CI_PIPELINE_SOURCE == "web"'} in root_rules
+ workflow = document["workflow"]["rules"]
+ assert {
+ "if": '$CI_PIPELINE_SOURCE == "pipeline" && $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH && $SKILL_EVAL_FEEDBACK == "true"'
+ } in workflow
+
+
+def test_all_tiers_without_release_uses_packaged_candidate_descriptor(repository, tmp_path, monkeypatch):
+ from skillevaluator import ci_onboarding as wizard
+
+ package = tmp_path / "package"
+ package.mkdir()
+ (package / "ci-release-all-tiers.json").write_text(json.dumps(ALL_RELEASE))
+ (package / "ci-release.json").write_text(json.dumps(RELEASE))
+ monkeypatch.setattr(wizard, "__file__", str(package / "ci_onboarding.py"))
+ result = CliRunner().invoke(
+ cli, ["ci", "init", "--repo", str(repository), "--tiers", "1,2,3", "--mode", "preview", "--no-input"]
+ )
+ assert result.exit_code == 0, result.output
+ assert "Tier 1 required; Tiers 2 and 3 advisory" in result.output
+
+
[email protected]("platform", ["github", "gitlab"])
+def test_deprecated_tier3_required_flag_warns_and_never_changes_generated_policy(
+ repository, all_release, tmp_path, platform
+):
+ if platform == "gitlab":
+ subprocess.run(
+ [
+ "git",
+ "-C",
+ str(repository),
+ "remote",
+ "set-url",
+ "origin",
+ "https://gitlab.example.test/group/consumer.git",
+ ],
+ check=True,
+ )
+ receipt = tmp_path / "policy-receipt.json"
+ result = invoke(repository, all_release, "--mode", "save", "--tier3-required", "--output", str(receipt))
+ assert result.exit_code == 0, result.output
+ assert "deprecated" in result.output.lower() and "ignored" in result.output.lower()
+ assert "Tier 1 required; Tiers 2 and 3 advisory" in result.output
+ assert json.loads(receipt.read_text())["options"]["tier3_required"] is False
+ if platform == "github":
+ scan = yaml.safe_load((repository / ".github/workflows/skill-checks-all-tiers.yml").read_text())
+ assert "tier3-required" not in scan["jobs"]["skills"]["with"]
+ else:
+ scan = yaml.safe_load((repository / ".gitlab-ci.yml").read_text())
+ assert "SKILL_EVAL_TIER3_REQUIRED" not in scan["variables"]
+
+
+def test_candidate_descriptor_is_declared_as_package_data():
+ import tomllib
+ from pathlib import Path
+
+ project = tomllib.loads((Path(__file__).parents[1] / "pyproject.toml").read_text())
+ assert "ci-release-all-tiers.json" in project["tool"]["setuptools"]["package-data"]["skillevaluator"]
+
+
[email protected](("minutes", "seconds"), [(10, 480), (45, 2040), (80, 3600), (300, 16800)])
+def test_gitlab_docker_render_sets_a_literal_job_timeout(repository, all_release, minutes, seconds):
+ subprocess.run(
+ ["git", "-C", str(repository), "remote", "set-url", "origin", "https://gitlab.example.test/group/consumer.git"],
+ check=True,
+ )
+ result = invoke(repository, all_release, "--mode", "save", "--timeout-minutes", str(minutes))
+ assert result.exit_code == 0, result.output
+ scan = yaml.safe_load((repository / ".gitlab-ci.yml").read_text())
+ assert scan["skill-evaluation-native"] == {"timeout": f"{minutes} minutes"}
+ assert scan["variables"]["SKILL_EVAL_TIMEOUT_SECONDS"] == str(seconds)
+ assert "SKILL_EVAL_JOB_TIMEOUT" not in scan["variables"]
+
+
[email protected]("minutes", [1, 3, 9])
+def test_job_timeouts_without_an_evidence_reserve_are_rejected(repository, all_release, minutes):
+ subprocess.run(
+ ["git", "-C", str(repository), "remote", "set-url", "origin", "https://gitlab.example.test/group/consumer.git"],
+ check=True,
+ )
+ # Below ten minutes the reserve min(20, minutes // 4) is under two minutes, or none.
+ result = invoke(repository, all_release, "--mode", "save", "--timeout-minutes", str(minutes))
+ assert result.exit_code == 2
+ assert "--timeout-minutes" in result.output
+ assert not (repository / ".gitlab-ci.yml").exists()
+
+
+def test_gitlab_variable_scalars_are_explicit_strings_for_gitlab_yaml_parser(repository, all_release):
+ subprocess.run(
+ ["git", "-C", str(repository), "remote", "set-url", "origin", "https://gitlab.example.test/group/consumer.git"],
+ check=True,
+ )
+ result = invoke(repository, all_release, "--mode", "save")
+ assert result.exit_code == 0, result.output
+ source = (repository / ".gitlab-ci.yml").read_text()
+ document = yaml.compose(source)
+ variables = next(value for key, value in document.value if key.value == "variables")
+ assert all(value.style in {"'", '"'} for _key, value in variables.value)
+ parsed = yaml.safe_load(source)
+ assert parsed["variables"]["SKILL_EVAL_TIERS"] == "1,2,3"
+ assert parsed["skill-evaluation-native"]["timeout"] == "300 minutes"
+ feedback = yaml.safe_load((repository / ".gitlab/skill-feedback.yml").read_text())
+ assert isinstance(feedback["include"][0]["inputs"]["tools-ref"], str)
+
+
+ "version,required",
+ [
+ ("17.8.7-ee", True),
+ ("18.3.0", True),
+ ("18.4.0-ee", False),
+ ("19.0.1", False),
+ ("unknown", None),
+ (None, None),
+ (123, None),
+ (True, None),
+ ],
+)
+def test_gitlab_admission_prerequisite_checks_server_version(monkeypatch, version, required):
+ from skillevaluator import _ci_onboarding_all_tiers as all_tiers
+
+ monkeypatch.setattr(all_tiers, "gitlab_api", lambda *_args, **_kwargs: {"version": version})
+ result = all_tiers.gitlab_admission_prerequisite("https://gitlab.example.test", online=True)
+ assert result["read_token_required"] is required
+ assert result["verified"] is (required is not None)
+
+
+def test_gitlab_offline_admission_prerequisite_does_not_call_api(monkeypatch):
+ from skillevaluator import _ci_onboarding_all_tiers as all_tiers
+
+ monkeypatch.setattr(
+ all_tiers, "gitlab_api", lambda *_args, **_kwargs: pytest.fail("Offline setup must remain offline")
+ )
+ result = all_tiers.gitlab_admission_prerequisite("https://gitlab.example.test", online=False)
+ assert result["verified"] is False and result["read_token_required"] is None
+
+
+ "version,phrase",
+ [
+ ("17.8.7-ee", "requires SKILLEVALUATOR_GITLAB_READ_TOKEN"),
+ ("18.4.0", "supports CI_JOB_TOKEN"),
+ ("unknown", "admission readiness is unverified"),
+ ],
+)
+def test_gitlab_status_reports_admission_version_prerequisite(repository, monkeypatch, version, phrase):
+ from skillevaluator import _ci_onboarding_all_tiers as all_tiers
+
+ subprocess.run(
+ ["git", "-C", str(repository), "remote", "set-url", "origin", "https://gitlab.example.test/group/consumer.git"],
+ check=True,
+ )
+
+ def api(_origin, method, endpoint, payload=None, **_kwargs):
+ assert method == "GET"
+ if endpoint == "version":
+ return {"version": version}
+ if endpoint == "projects/group%2Fconsumer":
+ return {"default_branch": "trunk"}
+ if "/repository/files/" in endpoint:
+ return None
+ if "/pipelines?" in endpoint:
+ return []
+ raise AssertionError(endpoint)
+
+ monkeypatch.setattr(all_tiers, "gitlab_api", api)
+ result = CliRunner().invoke(
+ cli, ["ci", "status", "--repo", str(repository), "--platform", "gitlab", "--tiers", "1,2,3"]
+ )
+ assert result.exit_code == 0, result.output
+ assert phrase in result.output
+ assert "credential validity is not verified" in result.output
+
+
[email protected]("tiers", [None, "1,2,3"])
+def test_preview_ignores_user_insteadof_rewrite_of_a_supported_origin(
+ repository, release_file, all_release, tmp_path, monkeypatch, tiers
+):
+ # A developer-level rewrite to ssh:// must not hide the configured github.com origin.
+ home = tmp_path / "home"
+ home.mkdir()
+ (home / ".gitconfig").write_text('[url "ssh://[email protected]/"]\n\tinsteadOf = https://github.com/\n')
+ monkeypatch.setenv("HOME", str(home))
+ rewritten = subprocess.check_output(["git", "-C", str(repository), "remote", "get-url", "origin"], text=True)
+ assert rewritten.startswith("ssh://")
+ args = ["ci", "init", "--repo", str(repository), "--no-input", "--mode", "preview"]
+ args += ["--release", str(release_file)] if tiers is None else ["--release", str(all_release), "--tiers", tiers]
+ result = CliRunner().invoke(cli, args)
+ assert result.exit_code == 0, result.output
+
+
+def test_alias_origin_parses_after_insteadof_rewrite(repository, all_release):
+ subprocess.run(["git", "-C", str(repository), "remote", "set-url", "origin", "gh:example-org/consumer"], check=True)
+ subprocess.run(
+ ["git", "-C", str(repository), "config", "url.https://github.com/.insteadOf", "gh:"],
+ check=True,
+ )
+ result = invoke(repository, all_release, "--mode", "preview")
+ assert result.exit_code == 0, result.output
+
+
[email protected]("command", [["status"], ["demo", "--no-input"]])
+def test_unrecognized_origin_never_receives_generic_gitlab_token(repository, monkeypatch, command):
+ import urllib.request
+
+ subprocess.run(
+ ["git", "-C", str(repository), "remote", "set-url", "origin", "https://codeberg.org/someone/skills.git"],
+ check=True,
+ )
+ monkeypatch.setenv("GITLAB_TOKEN", "glpat-ambient-test-value")
+ monkeypatch.delenv("SKILLEVALUATOR_GITLAB_TOKEN", raising=False)
+ requests = []
+ monkeypatch.setattr(urllib.request, "build_opener", lambda *a: requests.append(a) or pytest.fail("network"))
+ result = CliRunner().invoke(cli, ["ci", *command, "--repo", str(repository)])
+ assert result.exit_code != 0
+ assert "--tiers 1,2,3" in result.output
+ assert requests == []
+ # An explicit GitLab opt-in still refuses the generic token.
+ result = CliRunner().invoke(cli, ["ci", *command, "--repo", str(repository), "--platform", "gitlab"])
+ assert result.exit_code != 0
+ assert "SKILLEVALUATOR_GITLAB_TOKEN" in result.output
+ assert "glpat-ambient-test-value" not in result.output
+ assert requests == []
+
+
+def _gitlab_status(repository, monkeypatch, root_config):
+ import base64
+
+ from skillevaluator import _ci_onboarding_all_tiers as all_tiers
+
+ subprocess.run(
+ ["git", "-C", str(repository), "remote", "set-url", "origin", "https://gitlab.example.test/group/consumer.git"],
+ check=True,
+ )
+ calls = []
+
+ def api(origin, method, endpoint, payload=None, **kwargs):
+ assert method == "GET"
+ calls.append(endpoint)
+ if endpoint == "version":
+ return {"version": "18.4.0"}
+ if endpoint == "projects/group%2Fconsumer":
+ return {"default_branch": "trunk"}
+ if "/repository/files/" in endpoint:
+ content = root_config if ".gitlab-ci.yml?" in endpoint else "include: []\n"
+ return {"encoding": "base64", "content": base64.b64encode(content.encode()).decode()}
+ if "/pipelines?" in endpoint:
+ return [{"status": "success", "web_url": "https://gitlab.example.test/p/1"}]
+ raise AssertionError(endpoint)
+
+ monkeypatch.setattr(all_tiers, "gitlab_api", api)
+ result = CliRunner().invoke(cli, ["ci", "status", "--repo", str(repository), "--tiers", "1,2,3"])
+ assert result.exit_code == 0, result.output
+ return result.output, calls
+
+
+def test_gitlab_status_requires_trusted_all_tier_root_config(repository, monkeypatch):
+ output, calls = _gitlab_status(repository, monkeypatch, "build:\n script: make\n")
+ assert "All-tier checks: configured" not in output
+ assert "not an all-tier configuration" in output
+ assert not any("/pipelines" in call for call in calls)
+
+
+def test_gitlab_status_accepts_generated_root_and_filters_default_branch(repository, all_release, monkeypatch):
+ subprocess.run(
+ ["git", "-C", str(repository), "remote", "set-url", "origin", "https://gitlab.example.test/group/consumer.git"],
+ check=True,
+ )
+ assert invoke(repository, all_release, "--mode", "save").exit_code == 0
+ output, calls = _gitlab_status(repository, monkeypatch, (repository / ".gitlab-ci.yml").read_text())
+ assert "All-tier checks: configured" in output
+ assert any("/pipelines?ref=trunk" in call for call in calls)
+
+
+ "document",
+ [
+ "build:\n script: make\n",
+ "include:\n - remote: https://raw.githubusercontent.com/NVIDIA/SkillEvaluator/main/ci/gitlab/all-tiers.yml\n"
+ " - local: .gitlab/skill-feedback.yml\n",
+ "include:\n - remote: https://raw.githubusercontent.com/NVIDIA/SkillEvaluator/"
+ + "a" * 40
+ + "/ci/gitlab/all-tiers.yml\n"
+ " - local: .gitlab/other.yml\n",
+ "- not a mapping\n",
+ ],
+)
+def test_status_gitlab_validation_matches_trusted_feedback(document):
+ from ci.feedback import FeedbackError, validate_gitlab_config
+
+ from skillevaluator import _ci_onboarding_all_tiers as all_tiers
+
+ with pytest.raises(FeedbackError):
+ validate_gitlab_config(document.encode())
+ assert all_tiers.gitlab_config_problem(document) is not None
+
+
+ ("separator", "expected"),
+ [(",", "matches exact workflow"), ("\n", "matches exact workflow"), (" ", "Malformed approval list")],
+)
+def test_status_parses_caller_blobs_like_trusted_feedback(repository, all_release, monkeypatch, separator, expected):
+ import base64
+
+ from skillevaluator import ci_onboarding as wizard
+
+ assert invoke(repository, all_release, "--mode", "save").exit_code == 0
+ scan = (repository / ".github/workflows/skill-checks-all-tiers.yml").read_bytes()
+ feedback = yaml.safe_load((repository / ".github/workflows/feedback-all-tiers.yml").read_text())
+ feedback["jobs"]["feedback"]["with"]["trusted-caller-blobs"] = "1" * 40 + separator + wizard.blob_id(scan.decode())
+ texts = {
+ ".github/workflows/skill-checks-all-tiers.yml": scan,
+ ".github/workflows/feedback-all-tiers.yml": yaml.safe_dump(feedback).encode(),
+ }
+
+ def api(method, endpoint, payload=None, **kwargs):
+ if endpoint == "repos/example-org/consumer":
+ return {"default_branch": "trunk"}
+ for path, text in texts.items():
+ if "/contents/" + path + "?" in endpoint:
+ return {"encoding": "base64", "content": base64.b64encode(text).decode()}
+ if "/runs?" in endpoint:
+ return {"workflow_runs": []}
+ raise AssertionError(endpoint)
+
+ monkeypatch.setattr(wizard, "github_api", api)
+ result = CliRunner().invoke(cli, ["ci", "status", "--repo", str(repository)])
+ assert result.exit_code == 0, result.output
+ assert expected in result.output
+
+
+def test_setup_pr_next_steps_name_the_all_tier_demo(repository, all_release, monkeypatch):
+ from skillevaluator import ci_onboarding as wizard
+
+ bodies = []
+
+ def api(method, endpoint, payload=None, **kwargs):
+ if method == "POST":
+ if endpoint.endswith("/pulls"):
+ bodies.append(payload["body"])
+ return {"html_url": "https://github.com/example-org/consumer/pull/1"}
+ return {"sha": "a" * 40}
+ if endpoint == "repos/example-org/consumer":
+ return {"default_branch": "trunk"}
+ if "/contents/" in endpoint or endpoint.endswith("/git/ref/heads/ci%2Fskillevaluator-all-tiers-setup"):
+ return None
+ if "/pulls?" in endpoint:
+ return []
+ if endpoint.endswith("/git/ref/heads/trunk"):
+ return {"object": {"sha": "c" * 40}}
+ if endpoint.endswith("/git/commits/" + "c" * 40):
+ return {"tree": {"sha": "d" * 40}}
+ raise AssertionError(endpoint)
+
+ monkeypatch.setattr(wizard, "github_api", api)
+ monkeypatch.setattr(wizard, "committed_blob", lambda *_args: "0" * 40)
+ result = invoke(repository, all_release, "--mode", "pr", "--paths", "skills")
+ assert result.exit_code == 0, result.output
+ assert "ci demo --tiers 1,2,3" in bodies[0]
+ assert "ci demo --tiers 1,2,3" in result.output
+
+
+def test_all_tier_only_init_options_require_tiers(repository, release_file):
+ before = subprocess.check_output(["git", "-C", str(repository), "status", "--porcelain"])
+ result = CliRunner().invoke(
+ cli,
+ [
+ "ci",
+ "init",
+ "--repo",
+ str(repository),
+ "--release",
+ str(release_file),
+ "--no-input",
+ "--mode",
+ "save",
+ "--checks-only",
+ "--paths",
+ "skills",
+ "--provider",
+ "anthropic",
+ "--timeout-minutes",
+ "45",
+ ],
+ )
+ assert result.exit_code != 0
+ assert "--provider" in result.output and "--timeout-minutes" in result.output
+ assert "--tiers 1,2,3" in result.output
+ assert subprocess.check_output(["git", "-C", str(repository), "status", "--porcelain"]) == before
+
+
+def test_all_tier_receipt_parent_is_created_before_saving(repository, all_release, tmp_path):
+ receipt = tmp_path / "receipts" / "nested" / "plan.json"
+ result = invoke(repository, all_release, "--mode", "save", "--paths", "skills", "--output", str(receipt))
+ assert result.exit_code == 0, result.output
+ assert json.loads(receipt.read_text())["action"] == "saved"
+
+
+def test_all_tier_preview_lists_proposed_files_without_show_files(repository, all_release):
+ result = invoke(repository, all_release, "--mode", "preview", "--paths", "skills")
+ assert result.exit_code == 0, result.output
+ assert ".github/workflows/skill-checks-all-tiers.yml" in result.output
+ assert ".github/workflows/feedback-all-tiers.yml" in result.output
+ assert "--show-files" in result.output
+ assert "jobs:" not in result.output
+
+
+def _gitlab_tier1_consumer(repository, extra=""):
+ from pathlib import Path
+
+ subprocess.run(
+ ["git", "-C", str(repository), "remote", "set-url", "origin", "https://gitlab.example.test/group/consumer.git"],
+ check=True,
+ )
+ released = (Path(__file__).parents[1] / "ci/bundles/0.7.2/gitlab-skill-checks.yml").read_text()
+ root = repository / ".gitlab-ci.yml"
+ root.write_text(released + extra)
+ subprocess.run(["git", "-C", str(repository), "add", "-A"], check=True)
+ subprocess.run(
+ ["git", "-C", str(repository), "-c", "commit.gpgsign=false", "commit", "-qm", "Tier 1"],
+ check=True,
+ )
+ return root, root.read_bytes()
+
+
+DEPLOY_JOB = "deploy:\n script: ./deploy.sh\n rules:\n - if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'\n"
+
+
+def test_gitlab_preview_prints_merge_steps_for_existing_root_config(repository, all_release):
+ root, before = _gitlab_tier1_consumer(repository, DEPLOY_JOB)
+ result = invoke(repository, all_release, "--mode", "preview", "--paths", "skills")
+ assert result.exit_code == 0, result.output
+ output = " ".join(result.output.split())
+ assert ".gitlab-ci.yml already exists; it will not be replaced" in output
+ assert "Remove the Tier 1 skill-evaluation.yml include" in output
+ assert "Jobs to guard: deploy." in output
+ assert "Merge the guards to the default branch first" in output
+ assert "- if: '$SKILL_EVAL_FEEDBACK == \"true\"' when: never" in output
+ # The rendered root and feedback files are printed even without --show-files.
+ assert ALL_RELEASE["gitlab_ref"] + "/ci/gitlab/all-tiers.yml" in output
+ assert "skill-evaluation-native: timeout: 300 minutes" in output
+ assert ".gitlab/skill-feedback.yml" in output and "/ci/gitlab/feedback.yml" in output
+ assert root.read_bytes() == before
+ assert not (repository / ".gitlab").exists()
+
+
+def test_gitlab_merge_steps_keep_the_test_stage_and_limit_extends_to_jobs_without_only(repository, all_release):
+ _gitlab_tier1_consumer(repository, "stages: [build, deploy]\nlegacy:\n script: ./legacy.sh\n only: [main]\n")
+ result = invoke(repository, all_release, "--mode", "preview", "--paths", "skills")
+ assert result.exit_code == 0, result.output
+ output = " ".join(result.output.split())
+ # Every included job uses stage test; a root stages list without it rejects the pipeline.
+ assert "If the root defines stages, keep test in the list" in output
+ # GitLab rejects only/except beside the rules a job would inherit from the hidden guard.
+ assert "a job without rules, only or except" in output
+ assert "Jobs to guard: legacy." in output
+ # Guards merge before the setup MR, when the hidden job is not yet defined.
+ assert "guard followed by - when: on_success" in output
+ assert "Write those guards as rules: extends: .skill-evaluation-not-feedback works only after" in output
+ # Feedback triggers pass pipeline variables, which GitLab can restrict per project.
+ assert "pass pipeline variables" in output
+
+
+def test_gitlab_jobs_keeping_only_or_except_are_never_counted_as_guarded():
+ from skillevaluator import _ci_onboarding_all_tiers as all_tiers
+
+ guard = " rules:\n - if: '$SKILL_EVAL_FEEDBACK == \"true\"'\n when: never\n"
+ root = "".join(
+ [
+ ".old:\n only: [main]\n",
+ "extended:\n script: a\n only: [main]\n extends: .skill-evaluation-not-feedback\n",
+ "inherited:\n script: b\n extends: [.old, .skill-evaluation-not-feedback]\n",
+ "ruled:\n script: c\n except: [tags]\n" + guard,
+ "guarded:\n script: d\n extends: .skill-evaluation-not-feedback\n",
+ "plain:\n script: e\n" + guard,
+ # A null value drops an inherited key, and GitLab ignores null only/except beside rules.
+ ".mid:\n extends: .old\n only: null\n",
+ "dropped:\n script: f\n extends: .old\n only: null\n" + guard + " - when: on_success\n",
+ "nulled:\n script: g\n except: null\n" + guard + " - when: on_success\n",
+ "middle:\n script: h\n extends: [.mid, .skill-evaluation-not-feedback]\n",
+ # The last parent defining a key wins, so a later .old restores only.
+ "restored:\n script: i\n extends: [.mid, .old, .skill-evaluation-not-feedback]\n",
+ ]
+ )
+ assert all_tiers.gitlab_unguarded_jobs(root) == ["extended", "inherited", "ruled", "restored"]
+
+
+def test_gitlab_pr_remote_root_conflict_points_to_an_updated_checkout(repository, all_release, monkeypatch):
+ import base64
+
+ from skillevaluator import _ci_onboarding_all_tiers as all_tiers
+
+ subprocess.run(
+ ["git", "-C", str(repository), "remote", "set-url", "origin", "https://gitlab.example.test/group/consumer.git"],
+ check=True,
+ )
+ remote_root = "build:\n script: make\n"
+
+ def api(origin, method, endpoint, payload=None, **kwargs):
+ assert method == "GET", "A conflicting remote root must stop before any mutation"
+ if endpoint == "version":
+ return {"version": "18.4.0"}
+ if endpoint == "projects/group%2Fconsumer":
+ return {"default_branch": "trunk"}
+ if endpoint == "projects/group%2Fconsumer/repository/files/.gitlab-ci.yml?ref=trunk":
+ return {"encoding": "base64", "content": base64.b64encode(remote_root.encode()).decode()}
+ raise AssertionError(endpoint)
+
+ monkeypatch.setattr(all_tiers, "gitlab_api", api)
+ # The stale checkout has no root, so preview alone would print no merge steps.
+ result = invoke(repository, all_release, "--mode", "pr", "--paths", "skills")
+ assert result.exit_code != 0
+ output = " ".join(result.output.split())
+ assert ".gitlab-ci.yml differs on the default branch; it will not be replaced" in output
+ assert "Update your checkout to the default branch, then run --mode preview" in output
+ assert not (repository / ".gitlab-ci.yml").exists()
+ # Following the hint reaches the merge steps.
+ (repository / ".gitlab-ci.yml").write_text(remote_root)
+ preview = invoke(repository, all_release, "--mode", "preview", "--paths", "skills")
+ assert preview.exit_code == 0, preview.output
+ assert "Merge the rendered files below by hand" in " ".join(preview.output.split())
+
+
[email protected]("mode", ["save", "pr"])
+def test_gitlab_save_and_pr_refuse_to_replace_existing_root_config(repository, all_release, monkeypatch, mode):
+ from skillevaluator import _ci_onboarding_all_tiers as all_tiers
+
+ monkeypatch.setattr(all_tiers, "gitlab_api", lambda *_a, **_k: pytest.fail("refused before any API call"))
+ root, before = _gitlab_tier1_consumer(repository)
+ result = invoke(repository, all_release, "--mode", mode, "--paths", "skills")
+ assert result.exit_code != 0
+ output = " ".join(result.output.split())
+ assert ".gitlab-ci.yml already exists with different content; it will not be replaced" in output
+ assert "--mode preview" in output and "merge" in output
+ assert root.read_bytes() == before
+ assert not (repository / ".gitlab").exists()
+
+
+def test_gitlab_interactive_save_refuses_existing_root_config(repository, all_release):
+ root, before = _gitlab_tier1_consumer(repository)
+ result = CliRunner().invoke(
+ cli,
+ ["ci", "init", "--repo", str(repository), "--release", str(all_release), "--tiers", "1,2,3"],
+ input="2\nsave\n",
+ )
+ assert result.exit_code != 0
+ assert "it will not be replaced" in result.output
+ assert root.read_bytes() == before
+ assert not (repository / ".gitlab").exists()
+
+
+def test_gitlab_status_warns_about_root_jobs_without_feedback_guard(repository, all_release, monkeypatch):
+ subprocess.run(
+ ["git", "-C", str(repository), "remote", "set-url", "origin", "https://gitlab.example.test/group/consumer.git"],
+ check=True,
+ )
+ assert invoke(repository, all_release, "--mode", "save").exit_code == 0
+ generated = (repository / ".gitlab-ci.yml").read_text()
+ output, _calls = _gitlab_status(repository, monkeypatch, generated)
+ assert "Warning" not in output
+ guarded = (
+ "lint:\n script: make lint\n rules:\n - if: \"$SKILL_EVAL_FEEDBACK == 'true'\"\n when: never\n"
+ " - when: on_success\n"
+ "docs:\n script: make docs\n extends: .skill-evaluation-not-feedback\n"
+ ".base:\n rules:\n - if: '$SKILL_EVAL_FEEDBACK == \"true\"'\n when: never\n"
+ " - if: $CI_COMMIT_BRANCH\n"
+ "package:\n script: make package\n extends: [.base]\n"
+ )
+ output, _calls = _gitlab_status(repository, monkeypatch, generated + guarded + DEPLOY_JOB + "test:\n script: t\n")
+ assert "All-tier checks: configured" in output
+ normalized = " ".join(output.split())
+ assert "also run deploy, test." in normalized
+ assert "SKILL_EVAL_FEEDBACK" in normalized and ".skill-evaluation-not-feedback" in normalized
+ assert "a job without rules, only or except can extend" in normalized
diff --git a/tests/test_harbor_compose_readiness.py b/tests/test_harbor_compose_readiness.py
new file mode 100644
index 00000000..44cd1d8a
--- /dev/null
+++ b/tests/test_harbor_compose_readiness.py
@@ -0,0 +1,85 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Staged main images remain compatible with Compose 2 health-based waits."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+import yaml
+
+from skillevaluator.tier3.harbor.adapter import generate_harbor_tasks, stage_native_harbor_tasks
+
+
+def _assert_safe_readiness_check(dockerfile: Path) -> None:
+ instructions = [line for line in dockerfile.read_text().splitlines() if line.startswith("HEALTHCHECK ")]
+ # Docker keeps only the final HEALTHCHECK. NONE suppresses the authored
+ # image check, but Compose 2 needs a real evaluator-owned check afterward.
+ assert "HEALTHCHECK NONE" in instructions
+ _options, separator, command = instructions[-1].partition(" CMD ")
+ assert separator
+ assert json.loads(command) == ["/bin/true"]
+
+
[email protected]("image_mode", ["generated", "base", "preserve", "rebase"])
+def test_generated_main_image_replaces_authored_healthcheck_with_constant_readiness(
+ tmp_path: Path, image_mode: str
+) -> None:
+ skill = tmp_path / "skill"
+ authored = skill / "evals/environment"
+ authored.mkdir(parents=True)
+ (skill / "SKILL.md").write_text("# Test skill\n")
+ (skill / "evals/evals.json").write_text(
+ json.dumps([{"id": "case-001", "question": "Run the test", "expected_skill": "skill"}])
+ )
+ if image_mode in {"preserve", "rebase"}:
+ (authored / "Dockerfile").write_text(
+ 'FROM python:3.12-slim\nHEALTHCHECK CMD ["sh", "-c", "touch /tmp/authored-probe"]\n'
+ )
+ task = generate_harbor_tasks(
+ skill,
+ tmp_path / "tasks",
+ base_image="fixture-base:latest" if image_mode in {"base", "rebase"} else "",
+ custom_dockerfile_mode="rebase" if image_mode == "rebase" else "preserve",
+ )[0]
+ _assert_safe_readiness_check(task / "environment/Dockerfile")
+
+
+def test_native_main_image_replaces_authored_healthcheck_with_constant_readiness(tmp_path: Path) -> None:
+ skill = tmp_path / "native-skill"
+ task = skill / "evals/harbor/case-001"
+ environment = task / "environment"
+ environment.mkdir(parents=True)
+ (task / "tests").mkdir()
+ (skill / "SKILL.md").write_text("# Native test skill\n")
+ (task / "task.toml").write_text('schema_version = "1.3"\n[task]\nname = "nvidia/case-001"\n[environment]\n')
+ (task / "instruction.md").write_text("Run the test.\n")
+ (task / "tests/test.sh").write_text("#!/bin/sh\nexit 0\n")
+ (environment / "Dockerfile").write_text(
+ 'FROM python:3.12-slim\nHEALTHCHECK CMD ["sh", "-c", "touch /tmp/authored-probe"]\n'
+ )
+ staged = stage_native_harbor_tasks(skill, tmp_path / "native-tasks", grading_mode="custom_only")[0]
+ _assert_safe_readiness_check(staged / "environment/Dockerfile")
+
+
+def test_custom_compose_service_healthchecks_keep_their_readiness_policy(tmp_path: Path) -> None:
+ skill = tmp_path / "skill"
+ authored = skill / "evals/environment"
+ authored.mkdir(parents=True)
+ (skill / "SKILL.md").write_text("# Test skill\n")
+ (skill / "evals/evals.json").write_text(json.dumps([{"id": "case-001", "question": "Run the test"}]))
+ services = {
+ "main": {
+ "depends_on": {"database": {"condition": "service_healthy"}},
+ },
+ "database": {
+ "image": "postgres:16",
+ "healthcheck": {"test": ["CMD-SHELL", "pg_isready -U postgres"]},
+ },
+ }
+ (authored / "docker-compose.yaml").write_text(yaml.safe_dump({"services": services}))
+ staged = generate_harbor_tasks(skill, tmp_path / "tasks")[0]
+ compose = yaml.safe_load((staged / "environment/docker-compose.yaml").read_text())
+ assert compose["services"]["main"] == services["main"]
+ assert compose["services"]["database"]["healthcheck"] == services["database"]["healthcheck"]
diff --git a/tests/test_harbor_local_mode.py b/tests/test_harbor_local_mode.py
index 0878bbb5..96fbf265 100644
--- a/tests/test_harbor_local_mode.py
+++ b/tests/test_harbor_local_mode.py
@@ -3424,9 +3424,12 @@ def test_streamed_exec_escalates_after_launcher_exits_with_term_ignoring_descend
environment = _initialized_local_environment(tmp_path)
environment._local_command_guardrail_reason = lambda *_args: "" # type: ignore[method-assign]
child_pid_path = environment._workspace / f"term-ignoring-{lifecycle}.pid"
+ child_pid_tmp_path = child_pid_path.with_name(f"{child_pid_path.name}.tmp")
command = (
"(trap '' TERM; exec >/dev/null 2>&1; sleep 30) & "
- f"printf '%s' \"$!\" > {shlex.quote(child_pid_path.name)}; "
+ # Existence signals readiness, so publish only the complete PID.
+ f"printf '%s' \"$!\" > {shlex.quote(child_pid_tmp_path.name)} && "
+ f"mv {shlex.quote(child_pid_tmp_path.name)} {shlex.quote(child_pid_path.name)}; "
"printf ready; wait"
)
diff --git a/tests/test_nvidia_build_bridge.py b/tests/test_nvidia_build_bridge.py
index f38f51b3..fcfd98bb 100644
--- a/tests/test_nvidia_build_bridge.py
+++ b/tests/test_nvidia_build_bridge.py
@@ -457,6 +457,9 @@ def bridge_services(tmp_path: Path) -> _BridgeServices:
# read; tests that count workers must start from an idle server.
assert servers[0].wait_for_workers(timeout=2)
+ # Receiving the health response does not mean its worker has exited yet.
+ assert servers[0].wait_for_workers(timeout=2), "bridge readiness worker did not finish"
+
yield _BridgeServices(
base_url,
build,
diff --git a/tests/test_tier3_public_runtime.py b/tests/test_tier3_public_runtime.py
index 10c9ce0c..762511c0 100644
--- a/tests/test_tier3_public_runtime.py
+++ b/tests/test_tier3_public_runtime.py
@@ -2899,6 +2899,7 @@ def test_documented_agent_cli_versions_match_the_pins() -> None:
for page, text in pages.items():
assert f"Codex {runner._CODEX_VERSION}" in text, page
assert f"Claude Code {runner._CLAUDE_CODE_VERSION}" in text, page
+ assert f"OpenCode {runner.OPENCODE_VERSION}" in text, page
for name, minimum in (
("Claude Code", local_agents._CLAUDE_CODE_MIN_VERSION_FOR_CLAUDE_5_5),
("Codex", local_agents._CODEX_MIN_VERSION_FOR_GPT_6),
@@ -2906,16 +2907,21 @@ def test_documented_agent_cli_versions_match_the_pins() -> None:
assert f"{name} {'.'.join(map(str, minimum))} or newer" in pages["agents-and-sandboxes.mdx"]
-def test_opencode_runs_pass_no_agent_kwargs() -> None:
[email protected]("env_mode", ["docker", "local"])
+def test_opencode_runs_pass_only_the_pinned_cli_version(env_mode: str) -> None:
+ from skillevaluator.tier3.harbor import runner
+
command = build_harbor_run_command(
dataset_path="/tmp/dataset",
agent="opencode",
job_name="effort",
- env_mode="docker",
+ env_mode=env_mode,
model="anthropic/claude-opus-5-5",
)
- assert "--ak" not in command
+ # Without a version Harbor installs opencode-ai@latest; local mode runs the installed CLI.
+ # OpenCode never receives a reasoning-effort override.
+ assert _harbor_agent_kwargs(command) == ({} if env_mode == "local" else {"version": runner.OPENCODE_VERSION})
def test_codex_agents_render_the_pinned_reasoning_effort(tmp_path: Path) -> None: