Multi-tier framework for evaluating AI agent skills and plugins with quality gates, security scanning, harness compatibility checks, semantic overlap detection, synthetic evaluation dataset generation, and live agent evaluation that measures how skills affect agent behavior. Ships reusable CI templates that bring every check to any repository.
Python agent-evaluationagent-pluginsagent-securityagent-skillsagentic-aibenchmarkci-templatesclaude-codecodexevaluateevaluationharnesspluginplugin-evaluationsecurity-scannerskill-evalskill-evaluationskill-evaluatorskill-gap-analysisskills
feat(ci): ship guided GitHub onboarding in SkillEvaluator 0.7.1 (#327)
Christopher Kevin3da8c573ff1a
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 7d677ae8..ea0a9661 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -224,6 +224,33 @@ jobs:run: python scripts/check_oss_boundary.py --root . --allowlist config/oss_boundary_allowlist.json --archive dist/*.whl --archive dist/*.tar.gz- name: Validate distribution metadatarun: uvx --from twine==6.2.0 twine check --strict dist/*+ - name: Verify onboarding from the base wheel+ shell: bash+ run: |+ uv venv --python 3.12 "$RUNNER_TEMP/skillevaluator-base"+ uv pip install --python "$RUNNER_TEMP/skillevaluator-base/bin/python" dist/*.whl+ "$RUNNER_TEMP/skillevaluator-base/bin/python" - <<'PY'+ import json+ import subprocess+ import sys+ import tempfile+ from importlib.resources import files+ from pathlib import Path++ release = json.loads(files("skillevaluator").joinpath("ci-release.json").read_text())+ assert release["repository"] == "NVIDIA/SkillEvaluator"+ command = [str(Path(sys.executable).with_name("skillevaluator"))]+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ subprocess.run(["git", "init", "-b", "main", directory], check=True)+ subprocess.run(["git", "-C", directory, "remote", "add", "origin", "https://github.com/example/skills.git"], check=True)+ (root / "skills" / "smoke-check").mkdir(parents=True)+ (root / "skills" / "smoke-check" / "SKILL.md").write_text("---\nname: smoke-check\ndescription: Smoke check skill\n---\n# Smoke check\n")+ subprocess.run(["git", "-C", directory, "add", "skills"], check=True)+ for feedback in ("--checks-only", "--full"):+ subprocess.run(command + ["ci", "init", "--repo", directory, "--default-branch", "main", "--mode", "preview", "--no-input", feedback], check=True)+ assert not (root / ".github").exists(), "Preview changed the consumer checkout"+ PY- name: Install and smoke-test the wheel on Python 3.12, 3.13, and 3.14shell: bashrun: |@@ -240,6 +267,7 @@ jobs:"$venv/bin/skillevaluator" --version"$venv/bin/skillevaluator" --help >/dev/null"$venv/bin/skillevaluator" models --help >/dev/null+ "$venv/bin/skillevaluator" ci --help >/dev/nullSKILL_EVAL_LLM_PROVIDER=nv_build NVIDIA_API_KEY=nvapi-ci-placeholder \"$venv/bin/skillevaluator" doctor --agents opencode --env-mode docker >/dev/null"$venv/bin/python" -c 'import io; from skillevaluator.tier3.harbor.progress import PlainProgressReporter,ProgressEvent,Tier3RunPlan; s=io.StringIO(); r=PlainProgressReporter(stream=s,refresh_interval=60); r.start(Tier3RunPlan(skill_name="wheel-smoke",environment="docker",agents=("opencode",))); r.emit(ProgressEvent(stage="configuration",state="complete")); r.close(); assert "configuration: complete" in s.getvalue()'diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 23d2004c..4dc81b9b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,16 @@ All notable changes to SkillEvaluator are documented in this file.### Added+- Include `skillevaluator ci init`, `ci status` and `ci demo` in the Python+ package. Guided GitHub onboarding discovers skills, configures checks and+ optional public hosted reports, and opens a reviewable setup PR. An optional+ test PR demonstrates the results. Existing Pages sites and organization+ action restrictions are preserved; private repositories can use checks only.+- Add a visual CLI onboarding guide under GitHub Actions, alongside the manual+ template path. Keep GitHub and GitLab as the two repository-integration choices.+- Allow CI release templates to pin the reviewed report publisher separately+ from the verified scanner workflow and image.+- In local mode (`--env-mode local`), a missing Claude Code, Codex, or OpenCodeCLI is offered as a pinned npm install into the SkillEvaluator runtime folder;without a terminal, the command is printed instead.diff --git a/CITATION.cff b/CITATION.cffindex 4eff2429..bcc739a8 100644--- a/CITATION.cff+++ b/CITATION.cff@@ -2,7 +2,7 @@ cff-version: 1.2.0message: "If you use SkillEvaluator in academic or technical work, please cite the methodology paper under preferred-citation and record the SkillEvaluator version used for reproducibility."title: "SkillEvaluator"type: software-version: "0.7.0"+version: "0.7.1"authors:- name: "NVIDIA Corporation"license: Apache-2.0diff --git a/README.md b/README.mdindex 62cedf55..6978e399 100644--- a/README.md+++ b/README.md@@ -19,20 +19,31 @@ the [NVIDIA Verified Skills pipeline](https://github.com/NVIDIA/skills).## Bring skill evaluation to your repository-Automatically check changed skills in GitHub pull requests or GitLab merge-requests, with Tier 1 quality checks, SkillSpector security scanning and retained-reports. Choose your skill folders and minimum score. No evaluation code, local-installation or onboarding CLI is required: [copy a template](ci/templates/README.md).+Check changed skills in GitHub or GitLab with Tier 1 quality checks, SkillSpector+security scanning and reports. Choose folders and thresholds; no evaluator code+to import.-| Your repository | Source template | Copy destination |+**GitHub guided setup:** run inside your checked-out repository:++```bash+pip install --upgrade skillevaluator+skillevaluator ci init+```++Choose checks and optional hosted feedback, then review the setup PR.+[CLI setup guide](docs/cli-onboarding.mdx).++**Manual setup:** copy a filled-in template from+[ci-0.7.1](https://github.com/NVIDIA/SkillEvaluator/releases/tag/ci-0.7.1). No local CLI needed.++| Your repository | Ready-to-use template | Copy destination || --- | --- | --- |-| GitHub | [Skill checks](ci/templates/skill-checks.yml) | `.github/workflows/skill-checks.yml` |-| GitLab | [Skill checks](ci/templates/gitlab-skill-checks.yml) | `.gitlab-ci.yml`, or merge into your existing pipeline |-| GitHub reports and PR comments | [Optional publisher](ci/templates/publish-skill-reports.yml) | Add a second workflow; complete publisher setup |+| GitHub | [Skill checks](https://github.com/NVIDIA/SkillEvaluator/releases/download/ci-0.7.1/skill-checks.yml) | `.github/workflows/skill-checks.yml` |+| GitLab | [Skill checks](https://github.com/NVIDIA/SkillEvaluator/releases/download/ci-0.7.1/gitlab-skill-checks.yml) | `.gitlab-ci.yml`, or merge into your existing pipeline |+| GitHub reports and PR comments | [Optional publisher](https://github.com/NVIDIA/SkillEvaluator/releases/download/ci-0.7.1/publish-skill-reports.yml) | Second workflow; complete publisher setup |-Source templates contain release placeholders; use the filled-in copies from an-official CI image release. See [setup and availability](docs/repository-integration.mdx)-and [public report, log and comment examples](ci/examples/README.md).+See [GitHub](docs/github-actions.mdx) and [GitLab](docs/gitlab-ci.mdx) setup,+[template reference](ci/templates/README.md) and [report examples](ci/examples/README.md).## Quickstartdiff --git a/ci/render_templates.py b/ci/render_templates.pyindex e0aab3c2..efd722d9 100644--- a/ci/render_templates.py+++ b/ci/render_templates.py@@ -19,9 +19,19 @@ TEMPLATES = Path(__file__).parent / "templates"IMAGE_PLACEHOLDER = "ghcr.io/nvidia/skillevaluator-tier1@sha256:RELEASE_IMAGE_DIGEST"-def render_templates(output: Path, workflow_ref: str, image: str, repository: str = "NVIDIA/SkillEvaluator") -> dict:+def render_templates(+ output: Path,+ workflow_ref: str,+ image: str,+ repository: str = "NVIDIA/SkillEvaluator",+ *,+ publisher_ref: str | None = None,+) -> dict:if not github_api.COMMIT_SHA.fullmatch(workflow_ref):raise ValueError("A full reviewed workflow commit SHA is required.")+ publisher_ref = workflow_ref if publisher_ref is None else publisher_ref+ if not github_api.COMMIT_SHA.fullmatch(publisher_ref):+ raise ValueError("A full reviewed publisher commit SHA is required.")if not github_api.GHCR_DIGEST.fullmatch(image):raise ValueError("A published GHCR image digest is required.")if not github_api.REPOSITORY.fullmatch(repository):@@ -32,6 +42,8 @@ def render_templates(output: Path, workflow_ref: str, image: str, repository: stfor source in sorted(TEMPLATES.glob("*.yml")):rendered[source.name] = (source.read_text(encoding="utf-8")+ .replace("publish-skill-reports.yml@RELEASE_WORKFLOW_SHA", f"publish-skill-reports.yml@{publisher_ref}")+ .replace("tools-ref: RELEASE_WORKFLOW_SHA", f"tools-ref: {publisher_ref}").replace("RELEASE_WORKFLOW_SHA", workflow_ref).replace(IMAGE_PLACEHOLDER, image).replace("RELEASE_IMAGE_DIGEST", image.rsplit(":", 1)[1])@@ -46,7 +58,13 @@ def render_templates(output: Path, workflow_ref: str, image: str, repository: stoutput.mkdir(parents=True)for name, text in rendered.items():(output / name).write_text(text, encoding="utf-8")- receipt = {"repository": repository, "workflow_ref": workflow_ref, "image": image, "caller_blob": blob}+ receipt = {+ "repository": repository,+ "workflow_ref": workflow_ref,+ "publisher_ref": publisher_ref,+ "image": image,+ "caller_blob": blob,+ }(output / "release.json").write_text(json.dumps(receipt, indent=2) + "\n", encoding="utf-8")(output / "README.md").write_text("# Repository CI onboarding\n\n"@@ -75,7 +93,7 @@ def render_templates(output: Path, workflow_ref: str, image: str, repository: st"and comment-only operation are not supported by this publisher.\n\n""Without the signing permission, ordinary scans and downloadable reports still run; hosting is skipped. ""Commit the setup and trigger a new scan; rerunning an old job keeps its original workflow.\n\n"- f"[Full publisher setup](https://github.com/{repository}/blob/{workflow_ref}/ci/README.md"+ f"[Full publisher setup](https://github.com/{repository}/blob/{publisher_ref}/ci/README.md""#optional-hosted-reports-and-pr-feedback).\n\n""## GitLab\n\n""For GitLab, merge gitlab-skill-checks.yml into your root .gitlab-ci.yml and set "@@ -88,11 +106,15 @@ def render_templates(output: Path, workflow_ref: str, image: str, repository: stdef main() -> None:parser = argparse.ArgumentParser(description=__doc__)parser.add_argument("--workflow-ref", required=True)+ parser.add_argument(+ "--publisher-ref",+ help="Reviewed publisher workflow and tools SHA; defaults to --workflow-ref. Does not change the scanner pin.",+ )parser.add_argument("--image", required=True)parser.add_argument("--repository", default="NVIDIA/SkillEvaluator")parser.add_argument("--output", type=Path, required=True)args = parser.parse_args()- render_templates(args.output, args.workflow_ref, args.image, args.repository)+ render_templates(args.output, args.workflow_ref, args.image, args.repository, publisher_ref=args.publisher_ref)if __name__ == "__main__":diff --git a/ci/templates/README.md b/ci/templates/README.mdindex 6bc7742e..b68f7f6a 100644--- a/ci/templates/README.md+++ b/ci/templates/README.md@@ -30,6 +30,12 @@ image digest. If you copy a source template instead, replace`RELEASE_WORKFLOW_SHA` and `RELEASE_IMAGE_DIGEST` with the values recorded in thatCI release. Do not leave placeholders or substitute `main` or `latest`.+Maintainers can release a reviewed publisher update while keeping the verified+scanner workflow and image unchanged. Pass its full commit SHA as+`--publisher-ref` to `ci/render_templates.py`; otherwise it uses `--workflow-ref`.+The release receipt records both revisions. This changes the publisher workflow+and tools only; the scanner pin and approved evaluator identity stay unchanged.+## Customize and commit- **GitHub:** set `paths` and optionally `min-score` (default `70`). Changediff --git a/docs/README.md b/docs/README.mdindex 89814b00..ff081336 100644--- a/docs/README.md+++ b/docs/README.md@@ -25,6 +25,7 @@ contributors making non-trivial edits.- `performance-dashboard.mdx` — compare saved Tier 3 scores and resource use- `benchmark-rollout.mdx` — regenerating and promoting `BENCHMARK.md` cards- `github-actions.mdx` — reusable Tier 1 onboarding and optional hosted PR feedback+- `cli-onboarding.mdx` — install the CLI, automate GitHub setup and open an optional test PR- `ci-integration.mdx` — exit codes, GitHub Actions recipe, progressive adoption- `cli-reference.mdx` — every command and flag- `environment-variables.mdx` — variable-by-variable inventory@@ -58,8 +59,13 @@ to `.mdx` files or `fern/docs.yml`.- New pages must be added to the `navigation` section of[`../fern/docs.yml`](../fern/docs.yml); otherwise they will not appear in thesite.-- Use relative links between MDX pages (`./configuration.mdx`) and relative repo- links (`../README.md`) for files outside `docs/`.+- In published MDX pages, use site paths such as+ `/skills/skillevaluator/configuration` for other documentation pages. File-relative+ `.mdx` links are not resolved by Fern; see the+ [official link format](https://buildwithfern.com/learn/docs/writing-content/markdown-basics#link-format).+ The Fern 5.121.0 local preview returned HTTP 400 for those `.mdx` page URLs.+ Keep images, YAML `path:` values and+ repository-only Markdown links relative to their source files.- The Fern version is pinned in[`../fern/fern.config.json`](../fern/fern.config.json); bump it intentionallyrather than as a side effect.diff --git a/docs/cli-onboarding.mdx b/docs/cli-onboarding.mdxnew file mode 100644index 00000000..abd17161--- /dev/null+++ b/docs/cli-onboarding.mdx@@ -0,0 +1,195 @@+---+title: "Set Up CI with the CLI"+description: "Install SkillEvaluator, answer a few questions and bring automatic skill checks to your GitHub repository."+---++Bring skill evaluation to your GitHub repository in one guided setup.+SkillEvaluator finds your skills, prepares the workflows and opens a setup PR.+Your CI gets **Tier 1 checks, including SkillSpector security scanning**.++```bash title="Run inside your checked-out GitHub repository"+pip install --upgrade skillevaluator+skillevaluator ci init+```++<CardGroup cols={3}>+ <Card title="1. Choose" icon="terminal" href="#run-the-wizard">+ Select skill folders, a score threshold and feedback.+ </Card>+ <Card title="2. Merge" icon="code-pull-request" href="#review-your-setup">+ Review the setup PR and merge it when ready.+ </Card>+ <Card title="3. See results" icon="chart-simple" href="#try-a-test-pr">+ Open a skill PR and follow its check, comment and report.+ </Card>+</CardGroup>++No evaluation code to copy into your repository. No CI scanners to install+locally. The shared container supplies the runtime; you control the configuration.++<Accordion title="What do I need before I start?">+ Use Python 3.12–3.14, Git and the [GitHub CLI](https://cli.github.com/).+ Start from a clean checkout with a GitHub `origin` remote. Sign in with+ `gh auth login --scopes workflow` if you have not already done so. The login+ needs permission to add workflow files as well as access to the repository.++ Automatic GitHub setup requires repository admin access. GitHub Actions and+ the referenced reusable workflows must be allowed. Checks-only setup supports+ public and private repositories. Hosted feedback uses a public repository's+ GitHub Pages site; choose checks only when public report hosting is unsuitable.+ This wizard supports GitHub. For GitLab, use the+ [GitLab template](/skills/skillevaluator/gitlab-ci).+</Accordion>++## Run the wizard++The wizard discovers folders containing `SKILL.md`. Answer five short questions;+press **Enter** to keep a default.++| Question | Your choice |+| --- | --- |+| **Skill folders** | Use the displayed numbers: `1,2` or `1 2` selects two folders. |+| **Minimum score** | `70` by default; a lower quality score fails the check. |+| **PR scope** | `auto` checks changed skills; `all` checks the selected collection. |+| **Hosted feedback** | Add public HTML reports and one PR comment that updates with new results. |+| **Apply setup** | Choose `pr`, review the summary, then confirm. |++<Frame caption="Shortened example interview. Folder names and counts come from your repository.">+```text+╭─ 1/5 Which skill folders? ───────────╮+│ 1 skills 12 │+│ 2 .agents/skills 3 │+│ Use folder numbers: 1,2 or 1 2. │+╰─────────────────────────────────────╯+Folders [1]: 1,2+✓ Selected: skills, .agents/skills (15 skills)+```+</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.++## Review your setup++After confirmation, the CLI configures your selected GitHub settings and opens+a PR with the workflow files:++```text title="What changes in your repository"+.github/workflows/+├── skill-checks.yml Checks + downloadable reports+└── publish-skill-reports.yml Optional hosting + PR comments+```++<Frame caption="Example completion screen. Your CLI prints the real setup PR link.">+```text+╭─ ✓ Setup PR ready ───────────────────╮+│ Merge this PR to enable checks. │+╰─────────────────────────────────────╯+https://github.com/your-org/skills/pull/12++After merging, optionally create a test PR:+ skillevaluator ci demo+```+</Frame>++**Review and merge the setup PR yourself.** The CLI does not merge it.+A setup-only run may say **Skipped** because no skill changed.++## Try a test PR++After merging setup, run:++```bash+skillevaluator ci demo+```++The CLI asks before adding a small Markdown comment to one selected `SKILL.md`+on a new branch. Type `y` to create the test PR, or press Enter to skip.+You can also make a small skill edit and open a PR yourself.++<Frame caption="Example test PR output with hosted feedback enabled. Checks-only setups link to the downloadable report.">+```text+╭─ ✓ Test PR created ──────────────────────────────╮+│ Checks → Skill checks │+│ Bot comment → Open full report │+│ Comment follows publication. Close PR when done. │+╰─────────────────────────────────────────────────╯+https://github.com/your-org/skills/pull/13+```+</Frame>++Close the test PR when you finish; **you do not need to merge it**.++## See the result on your PR++<Frame caption="Illustrative bot comment. Each run supplies its own verdict, score and report links.">+<div style={{ padding: "16px", width: "100%", minWidth: 0 }}>++**github-actions[bot]**++**Tier 1 scan result: PASSED**++1 skill · 1 passed · 0 failed · 0 incomplete++| Skill | Status | Quality / 100 |+| --- | --- | --- |+| `skills/evidence-table` | PASS | 98.2 / A |++**Open full report** · **View workflow run**++</div>+</Frame>++| Where to look | What you get |+| --- | --- |+| **PR → Checks** | The scan result for the current commit. |+| **PR → Conversation**, with publishing enabled | One bot comment, updated when a new scan is published. |+| **Open full report** in that comment | Detailed HTML findings and scores. |++**Checks only:** open the scan in **Actions**, download its report artifact,+extract it and open `index.html`. Failed scans retain their available reports too.++<AccordionGroup>+ <Accordion title="GitHub says my login cannot add workflow files">+ For an existing GitHub CLI login, run+ `gh auth refresh --hostname github.com --scopes workflow`, then retry setup.+ If you supply a token yourself, it must permit workflow-file writes.+ See [GitHub's workflow scope](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/scopes-for-oauth-apps).+ </Accordion>+ <Accordion title="Can I inspect the setup before applying it?">+ Choose the read-only option in the wizard to see the plan without changing+ files or GitHub settings. The `save` option writes only the local workflow+ files; choose `pr` for automatic GitHub setup.+ </Accordion>+ <Accordion title="Will this change my other workflows or branch rules?">+ Existing workflows remain separate. The CLI does not automatically make+ the scan a required merge check. After the first run, select its emitted+ check in GitHub branch rules if a failed or incomplete result should block+ merging; the current template emits `skills / Tier 1 scan`.+ Organization action restrictions are preserved. Repositories using an+ Actions allowlist must use the wizard's `save` option, even when the required+ actions are already allowed. Review the saved files and complete setup through+ your normal repository process.+ </Accordion>+ <Accordion title="A scan ran, but I cannot find the comment">+ Confirm that setup is merged, the PR is open and its branch is in the same+ repository. Wait for **Publish skill reports** to finish; open that run if+ publication failed. Fork-origin PRs retain their available results in+ Actions. Checks-only setups do not post comments.+ </Accordion>+ <Accordion title="The check failed. Did onboarding fail?">+ Read the reported issue. A failed scan can still publish feedback: the+ result may identify a skill issue or a scanner that did not finish. Merging+ setup is not a passing evaluation. Push a fix to the same PR to rerun its+ checks and update the published feedback.+ </Accordion>+</AccordionGroup>++<CardGroup cols={2}>+ <Card title="Prefer to copy a template?" icon="file-code" href="/skills/skillevaluator/github-actions#get-started">+ Add the GitHub workflows yourself using the release files.+ </Card>+ <Card title="Using GitLab?" icon="code-branch" href="/skills/skillevaluator/gitlab-ci">+ Add the shared scanner to your GitLab pipeline.+ </Card>+</CardGroup>diff --git a/docs/developer-guide.mdx b/docs/developer-guide.mdxindex 9483a277..b00c0b70 100644--- a/docs/developer-guide.mdx+++ b/docs/developer-guide.mdx@@ -146,7 +146,7 @@ SkillEvaluator version you used for reproducibility:cff-version: 1.2.0title: "SkillEvaluator"type: software-version: "0.7.0"+version: "0.7.1"preferred-citation:type: articletitle: "Evaluating Skills, Not Just Agents: Agentic Continuous Evaluation of Skills"diff --git a/docs/github-actions.mdx b/docs/github-actions.mdxindex 8ad0a881..f3faf1dc 100644--- a/docs/github-actions.mdx+++ b/docs/github-actions.mdx@@ -1,111 +1,95 @@---title: "GitHub Actions"-description: "Bring SkillEvaluator checks and reports to your GitHub repository with a reusable workflow."+description: "Bring SkillEvaluator to your GitHub repository with a reusable workflow, clear results and optional PR feedback."----Bring skill evaluation to your GitHub repository with one workflow file. Point-it at your skill directories; pull requests check changed skills automatically.-The shared container includes Tier 1 and SkillSpector security scanning.+Bring skill evaluation to your GitHub repository with one workflow file.+Choose your skill folders; pull requests check changed skills automatically.+The shared image includes **Tier 1 and SkillSpector security scanning**.-<Note>- Use the generated workflow from an official CI image release. Until that- release is available, the source template contains placeholders and is not- runnable.-</Note>--## Choose what to add--The release bundle provides these two GitHub templates. Copy them into-`.github/workflows/`; you do not need to copy evaluator code or build an image.--| You want | Add this file | Setup |-| --- | --- | --- |-| Automatic checks and downloadable reports | [skill-checks.yml](https://github.com/NVIDIA/SkillEvaluator/blob/main/ci/templates/skill-checks.yml) | Choose your skill folders and score threshold. |-| Hosted reports and an updated PR comment | Also add [publish-skill-reports.yml](https://github.com/NVIDIA/SkillEvaluator/blob/main/ci/templates/publish-skill-reports.yml) | Complete the [one-time publisher setup](#enable-pr-comments). |--These links open the source templates in NVIDIA/SkillEvaluator. The-[template catalog](https://github.com/NVIDIA/SkillEvaluator/blob/main/ci/templates/README.md)-explains how to get release-generated copies from an official CI image release.-You can copy the files directly; no local installation or onboarding CLI is-required.--The release fills in the workflow and image versions. Both templates use-GitHub's automatic token; the default checks need no model key or paid LLM.+<CardGroup cols={2}>+ <Card title="Use the CLI" icon="terminal" href="/skills/skillevaluator/cli-onboarding">+ Answer a few questions. The CLI prepares checks, optional hosted feedback and a setup PR.+ </Card>+ <Card title="Copy the workflows" icon="file-code" href="#get-started">+ Add the release templates yourself. No local CLI installation required.+ </Card>+</CardGroup>## Get started<Steps>-### Add the workflow+### Download the released template-Copy the release-generated `skill-checks.yml` to-`.github/workflows/skill-checks.yml`. It pins the shared workflow and image.+Download [skill-checks.yml](https://github.com/NVIDIA/SkillEvaluator/releases/download/ci-0.7.1/skill-checks.yml)+from the [CI 0.7.1 release](https://github.com/NVIDIA/SkillEvaluator/releases/tag/ci-0.7.1).+Put it in `.github/workflows/skill-checks.yml` in your repository.+The release supplies the pinned workflow and image versions.-### Choose your skills and score+### Point it at your skills-Set `paths` to your skill directory and `min-score` to the minimum quality score-from 0 to 100 (default 70). For multiple roots, use a YAML multiline string.-Change `branches: [main]` if your default branch has a different name.+Edit these inputs in the downloaded file:-### Open a pull request+```yaml title="Your choices in skill-checks.yml"+with:+ paths: |-+ skills+ .agents/skills+ min-score: 70+ scan-mode: auto+ llm: false+```-GitHub Actions evaluates changed skills and provides a concise result. Open the-run and download its report artifact for details. Enable GitHub Actions and-allow the external reusable workflow and its actions in your organization.+Use your own skill folders. Keep `auto` to scan changed skills in PRs;+`all` checks the configured collection. If your default branch is not `main`,+update the template's push branch.-</Steps>+### Commit the workflow and open a skill PR-The generated job has this shape; the release fills in the immutable pins:--```yaml title=".github/workflows/skill-checks.yml"-jobs:- skills:- uses: NVIDIA/SkillEvaluator/.github/workflows/evaluate-skills.yml@RELEASE_WORKFLOW_SHA- with:- image: ghcr.io/nvidia/skillevaluator-tier1@sha256:RELEASE_IMAGE_DIGEST- paths: skills- min-score: 70- scan-mode: auto- llm: false-```+Merge the workflow onto your default branch, then open a PR changing a selected+skill. GitHub Actions must be enabled and allowed to use the referenced+reusable workflow and actions.-## See the results--Open **Actions → Skill checks** for the result and suggested next step. Download-`skill-evaluator-tier1-attempt-N` for `index.html`, per-skill HTML and JSON,-Markdown, SARIF and available scanner logs. Failed and incomplete scans retain-their available reports. The smaller `skill-evaluator-tier1-evidence-attempt-N`-artifact contains only the JSON used by the optional report publisher.+</Steps>-The HTML index and reports use four verdicts: **Passed**, **Changes required**,-**Incomplete** and **Skipped**. A quality score below your minimum fails the-Quality score check and blocks the verdict.+<Note>+ The released template provides **checks and downloadable reports**.+ Hosted reports and PR comments need the [optional publisher setup](#enable-pr-comments).+ The same release also includes the optional publisher template.+</Note>-<Frame caption="Example: a Tier 1 report shows the verdict and quality score separately. This example was captured from a GitLab demo using the same report renderer.">- <img src="./assets/repository-ci-results-example.png" alt="Example results table showing a failed skill, its quality score, and a link to its report" />-</Frame>+<Accordion title="I prefer to inspect the source templates">+ Browse the public [template catalog](https://github.com/NVIDIA/SkillEvaluator/blob/main/ci/templates/README.md)+ and [skill-checks.yml source](https://github.com/NVIDIA/SkillEvaluator/blob/main/ci/templates/skill-checks.yml).+ Source templates contain placeholders. Use the release-generated file when+ onboarding; do not substitute `main` or `latest` for its immutable versions.+</Accordion>-### In the Actions summary+## See what happened-A failed skill is identified with a reason and suggested fix. Open its report-for all findings. The quality score is separate from the scan verdict.+| Start here | Then open |+| --- | --- |+| **PR → Checks** | The `skills / Tier 1 scan` result and its short summary. |+| **Actions → Skill checks** | The run and downloadable report artifact. |+| **PR → Conversation**, with publishing enabled | The updated bot comment and **Open full report** link. |-```text-Tier 1 scan result: FAILED-1 skill · 0 passed · 1 failed-Problem: Quality score 98.2/100 is below the required 100/100-```+Download `skill-evaluator-tier1-attempt-N`, extract it, and open `index.html`.+Failed scans retain their available reports too. The HTML separates the+**verdict** from the **quality score**: a high score does not override a failed+required security or schema check.-This is an illustrative summary; the actual findings depend on the run.+<Frame caption="Report example: the skill scored 98.2 but did not meet a configured 100-point threshold. The shared renderer is used by both GitHub and GitLab.">+ <img src="./assets/repository-ci-results-example.png" alt="SkillEvaluator report table showing the skill verdict, score and link to its detailed report" />+</Frame>### On the pull request-The optional publisher posts one bot comment and updates it for new results.-Reviewers can see the failed skill, its score, and what to fix without opening-the Actions logs.+With publishing enabled, one bot comment is updated for new results. Reviewers+see the issue and next step without reading the full Actions log.-<Frame caption="Shortened illustrative PR comment. This example is included in the public SkillEvaluator documentation; no demo-repository access is needed.">-<div style={{ width: "100%", minWidth: 0, padding: "16px" }}>+<Frame caption="Shortened illustrative PR comment. Real comments link to your report and workflow run.">+<div style={{ padding: "16px", width: "100%", minWidth: 0 }}>**github-actions[bot]**@@ -119,131 +103,110 @@ the Actions logs.**Problem:** Quality score 98.2/100 is below the required 100/100.-**Suggested fix:** Open the skill report and address the quality findings.+**Next step:** Open the skill report and address its quality findings.**Open full report** · **View workflow run**</div></Frame>-The last line shows link labels. In a real comment, they open your repository's-hosted report and workflow run. Browse the-[public examples](https://github.com/NVIDIA/SkillEvaluator/blob/main/ci/examples/README.md)-for the report preview and log excerpts. With `scan-mode: auto`, a pull request-evaluates only affected skills in the configured folders.+Browse the [public report and log examples](https://github.com/NVIDIA/SkillEvaluator/blob/main/ci/examples/README.md)+for more detail. No personal demo-repository access is needed.## Enable PR comments-Add the second template for **hosted reports and PR comments together**.-The current publisher posts the comment after the report site deploys-successfully, so copying the second file alone is not enough.--<Steps>--### Enable report hosting once+The optional publisher hosts the HTML and posts a comment **after deployment+succeeds**. It needs a second workflow plus one-time hosting and approval settings.-Select **Settings → Pages → Source: GitHub Actions**. Create a new `gh-pages`-history branch containing an empty `.nojekyll` file and `history.json` with-`[]`. Keep any existing site or report history intact.+<Card title="Try the guided setup" icon="terminal" href="/skills/skillevaluator/cli-onboarding">+ The CLI prepares those settings and both workflow files, then opens a setup+ PR for you to review.+</Card>-### Configure the publisher template+Download [publish-skill-reports.yml](https://github.com/NVIDIA/SkillEvaluator/releases/download/ci-0.7.1/publish-skill-reports.yml)+from the same release as your scan workflow. Complete the one-time setup below,+or let the [CLI](/skills/skillevaluator/cli-onboarding) handle it.-Copy the release-generated `publish-skill-reports.yml` into-`.github/workflows/`. Replace `YOUR_REPORT_BASE_URL` with your repository's-Pages URL, for example `https://your-org.github.io/your-repo`.--In `skill-checks.yml`, uncomment the permission for signed report receipts:--```yaml-permissions:- contents: read- id-token: write-```--GitHub uses this to prove which workflow ran. No personal token or cloud account-is needed. After choosing your skill folders and other scan options, run:--```bash-git hash-object .github/workflows/skill-checks.yml-```--Paste the output into `trusted-caller-blobs` in the publisher file. This-approves that exact scan configuration; refresh it whenever you edit the scan-file. The release supplies the evaluator and publisher version pins.--### Merge the setup and open a skill PR--Put both workflow files on your default branch. Keep the **Skill checks**-workflow name, `skill-checks.yml` filename, and default artifact name.-The publisher template already includes the needed permissions; your-organization must allow them and the referenced actions. No extra token is-required.--The next eligible PR scan triggers publication automatically. After deployment,-the bot posts or updates its comment. Only open, current-head PRs from branches-in the same repository receive comments; fork PRs retain their scan results in-Actions.--</Steps>--<Note>- Reports can include source excerpts and unmerged findings. Pages is public- unless explicitly configured as private; a private repository alone does not- make its Pages site private. This publisher owns the report site's root, so- coordinate an existing Pages site before enabling it. Use downloadable- artifacts if hosting is unsuitable.-</Note>+<AccordionGroup>+ <Accordion title="What does manual publisher setup involve?">+ Start with the release-generated publisher template and follow the+ [publisher setup guide](https://github.com/NVIDIA/SkillEvaluator/blob/main/ci/README.md#optional-hosted-reports-and-pr-feedback).+ The main steps are:++ 1. Enable **Settings → Pages → Source: GitHub Actions** and initialize the+ `gh-pages` report-history branch. Preserve any existing site or history.+ 2. Add `publish-skill-reports.yml` with your Pages URL. Keep the evaluator+ and publisher versions supplied by the release.+ 3. Grant the scan workflow `id-token: write`, then approve its exact contents+ in the publisher's `trusted-caller-blobs` input. Compute the value with+ `git hash-object .github/workflows/skill-checks.yml`; refresh it whenever+ that scan file changes.+ 4. Merge both workflow files into the default branch. Open a new skill PR+ to test checks, hosting and feedback together.++ Keep the **Skill checks** workflow name, scan filename and default artifact+ name. The publisher uses GitHub's automatic token; organization policies+ must allow its permissions and referenced actions. Copying a second file+ alone does not finish setup.+ </Accordion>+ <Accordion title="Who receives a comment, and who can read the report?">+ Comments are posted on open, current-head PRs from branches in the same+ repository. Fork-origin PRs keep their available reports in Actions.+ Pages is public unless explicitly configured as private; repository privacy+ alone does not make its Pages site private. Reports may contain source+ excerpts and unmerged findings. Use downloadable artifacts when public+ hosting is unsuitable.+ </Accordion>+</AccordionGroup>-For history initialization, permission details and troubleshooting, follow the-[publisher setup guide](https://github.com/NVIDIA/SkillEvaluator/blob/main/ci/README.md#optional-hosted-reports-and-pr-feedback).+## Fit it into your workflow<AccordionGroup>- <Accordion title="When does it run?">- `scan-mode: auto` evaluates skills affected by a pull request and the full- configured collection on pushes and manual runs. `all` evaluates the whole- collection each time. No changed skills is a successful skip, not a scanner- pass. Completely deleted skills are listed as skipped; removing `SKILL.md`- while leaving tracked files is an error. Shared files outside skill roots are- not inferred dependencies; use `all` when they should trigger a full scan.- The 100-skill cap is a selection limit, not a runtime guarantee. Timed-out- scans retain completed results and mark the remainder incomplete. The workflow- scans up to four skills at once. Set `scan-workers` from 1 to 16 to change- this; `1` scans one skill at a time. Results and logs keep the same skill- order either way.+ <Accordion title="Will this wait for my existing workflows?">+ This workflow runs independently. Existing workflows remain separate; it+ does not automatically wait for them to finish. Configure explicit workflow+ dependencies if your pipeline needs that ordering.+ </Accordion>+ <Accordion title="Which changes trigger a scan?">+ `auto` selects affected skills on pull requests. Pushes to the default+ branch and manual runs scan the configured collection. `all` scans that+ collection each time. No changed skills is a successful **Skipped** result,+ not a scanner pass. Changes to shared files outside the skill roots are not+ inferred dependencies; use `all` when they should trigger a full scan.+ Selection is capped at 100 skills. Timeouts retain completed results and+ mark unfinished work incomplete. The workflow scans up to four skills at+ once; `scan-workers` accepts 1–16.</Accordion>- <Accordion title="Control whether it blocks merging">- The workflow runs independently of existing workflows; it does not wait for- them automatically. Configure a required check in GitHub branch rules if a- failed or incomplete result should block merging. `min-score` controls the- quality threshold and also applies to the rubric when LLM checks are enabled;- required security, schema and other checks remain independent. Tier 2 and- Tier 3 are not run.+ <Accordion title="How do I make this a merge gate?">+ After the first run, select its scan check in GitHub branch rules. The+ current template emits `skills / Tier 1 scan`; use the actual check name+ shown in your repository. `min-score` sets the quality threshold; required+ security, schema and other checks remain independent. This integration+ runs Tier 1 only.</Accordion>- <Accordion title="A scan finished, but hosting was skipped">- Check that the scan workflow grants `id-token: write` and refresh- `trusted-caller-blobs` after editing that file. Commit the setup and start- a new scan; rerunning an old job keeps its original workflow and cannot add- a missing receipt. GitHub can withhold this permission under fork- policies; the downloadable report remains available. Signing receipts are- separate artifacts and are never published on the report site.+ <Accordion title="The scan finished, but the comment is missing">+ Confirm setup is on the default branch and the PR is eligible for comments.+ Open **Publish skill reports** to see whether deployment completed. If+ hosting was skipped, check the scan's `id-token: write` permission and+ `trusted-caller-blobs` value. A new scan must use the updated workflow;+ rerunning an old job keeps its original workflow. The scan's downloadable+ report remains a separate way to inspect available findings.</Accordion>- <Accordion title="Privacy, dependencies, and optional LLM checks">- Static Tier 1 needs no model key, but dependency checks can contact- vulnerability services and submit package metadata. Dependencies are audited- without installing packages or running build scripts; unpinned or unresolved- requirements are incomplete. Known credential values detected by the PII- patterns, NVIDIA API keys, and unquoted `KEY=value` and `Bearer` credentials- are redacted from CI reports, including parts that scanners cut or escape.- Not every credential or transformed value is detectable. Raw scanner logs- are withheld when a credential or LLM key is present.- Remove and rotate exposed credentials; old reports and Git history are not- rewritten. Optional model-backed checks use the separate trusted manual- [LLM template](https://github.com/NVIDIA/SkillEvaluator/blob/main/ci/templates/skill-checks-llm.yml),- a provider key and provider charges; they send selected content to that- provider and are not included in the default publisher allowlist.+ <Accordion title="Do the checks need an LLM key or network access?">+ Default Tier 1 checks use no model key. Dependency audits can contact+ vulnerability services and submit package metadata; packages are not+ installed and build scripts are not run. Optional LLM checks use a separate+ [manual workflow](https://github.com/NVIDIA/SkillEvaluator/blob/main/ci/templates/skill-checks-llm.yml),+ your provider key and provider charges. They send selected content to that+ provider and are outside the default publisher allowlist.</Accordion></AccordionGroup>-See [Repository Integration](repository-integration.mdx) for GitLab and other-CI options, or the [maintainer guide](https://github.com/NVIDIA/SkillEvaluator/blob/main/ci/README.md)-for the release and runtime details.+<CardGroup cols={2}>+ <Card title="Set up with the CLI" icon="terminal" href="/skills/skillevaluator/cli-onboarding">+ See the guided setup and try your first test PR.+ </Card>+ <Card title="GitLab CI/CD" icon="code-branch" href="/skills/skillevaluator/gitlab-ci">+ Use the shared scanner image with a GitLab pipeline.+ </Card>+</CardGroup>diff --git a/docs/gitlab-ci.mdx b/docs/gitlab-ci.mdxindex 308f7754..e090c2d3 100644--- a/docs/gitlab-ci.mdx+++ b/docs/gitlab-ci.mdx@@ -8,20 +8,18 @@ and choose a quality threshold; merge requests evaluate changed skillswithout installing scanners or adding evaluation code to your repository.The shared container includes SkillSpector security scanning.-<Note>- Use the generated configuration from an official CI image release. Until- that release is available, the source template contains placeholders and is- not runnable.-</Note>-## Get started-Open the [GitLab source template](https://github.com/NVIDIA/SkillEvaluator/blob/main/ci/templates/gitlab-skill-checks.yml)-in the public NVIDIA/SkillEvaluator repository. It is maintained alongside the-GitHub templates; you do not need a GitLab mirror or a local onboarding CLI.-The [template catalog](https://github.com/NVIDIA/SkillEvaluator/blob/main/ci/templates/README.md)-explains how to get the release-generated version with the workflow and image-versions filled in.+Download [gitlab-skill-checks.yml](https://github.com/NVIDIA/SkillEvaluator/releases/download/ci-0.7.1/gitlab-skill-checks.yml)+from the [CI 0.7.1 release](https://github.com/NVIDIA/SkillEvaluator/releases/tag/ci-0.7.1).+It includes the pinned shared configuration and scanner image. You do not need+a GitLab mirror or a local onboarding CLI.++<Accordion title="I prefer to inspect the source template">+ Browse the [GitLab source template](https://github.com/NVIDIA/SkillEvaluator/blob/main/ci/templates/gitlab-skill-checks.yml)+ and [template catalog](https://github.com/NVIDIA/SkillEvaluator/blob/main/ci/templates/README.md).+ Source files contain placeholders; use the filled-in release file when onboarding.+</Accordion><Steps>@@ -133,4 +131,4 @@ Skill result: "skills/glossary-builder" — FAILED</Accordion></AccordionGroup>-For GitHub and other CI systems, see [Repository Integration](repository-integration.mdx).+For GitHub and other CI systems, see [Repository Integration](/skills/skillevaluator/repository-integration).diff --git a/docs/repository-integration.mdx b/docs/repository-integration.mdxindex f0584541..047742b8 100644--- a/docs/repository-integration.mdx+++ b/docs/repository-integration.mdx@@ -3,9 +3,8 @@ title: "Bring Skill Evaluation to Your Repository"description: "Evaluate changed skills automatically with reusable GitHub and GitLab CI configurations."----Bring SkillEvaluator to the repository where your team builds skills. Add a-reusable CI configuration, point it at your skill directories, and get-results automatically when skills change.+Bring SkillEvaluator to the repository where your team builds skills. Choose+your skill folders and get results automatically when skills change.No evaluation code to write. No scanner installations to manage. The sharedcontainer brings the Tier 1 runtime to your CI runner, including SkillSpector@@ -25,29 +24,31 @@ The job reads your skills, checks the changes, and saves a report. It does notrequire copying SkillEvaluator or SkillSpector source code into your repository.<CardGroup cols={2}>- <Card title="GitHub Actions" href="github-actions.mdx">- Add one workflow file to evaluate changed skills in pull requests and open the results in GitHub Actions.+ <Card title="GitHub Actions" icon="file-code" href="/skills/skillevaluator/github-actions">+ Use the guided CLI or copy a workflow to check skills in pull requests, with optional hosted reports and comments.</Card>- <Card title="GitLab CI/CD" href="gitlab-ci.mdx">+ <Card title="GitLab CI/CD" icon="code-branch" href="/skills/skillevaluator/gitlab-ci">Include the reusable job in your pipeline to evaluate changed skills in merge requests and download the report.</Card></CardGroup>## Copy a template-No local installation or onboarding CLI is required. Both platforms' templates+No local installation is required for the template route. Both platforms' templateslive in the public NVIDIA/SkillEvaluator repository. Open the file, copy therelease-generated version, and set your skill folders and score threshold.-| Your platform | Source template | Put it in your repository |+| Your platform | Ready-to-use template | Put it in your repository || --- | --- | --- |-| GitHub | [skill-checks.yml](https://github.com/NVIDIA/SkillEvaluator/blob/main/ci/templates/skill-checks.yml) | `.github/workflows/skill-checks.yml` |-| GitLab | [gitlab-skill-checks.yml](https://github.com/NVIDIA/SkillEvaluator/blob/main/ci/templates/gitlab-skill-checks.yml) | `.gitlab-ci.yml`, or merge into your existing root configuration |+| GitHub | [skill-checks.yml](https://github.com/NVIDIA/SkillEvaluator/releases/download/ci-0.7.1/skill-checks.yml) | `.github/workflows/skill-checks.yml` |+| GitLab | [gitlab-skill-checks.yml](https://github.com/NVIDIA/SkillEvaluator/releases/download/ci-0.7.1/gitlab-skill-checks.yml) | `.gitlab-ci.yml`, or merge into your existing root configuration |+Download the filled-in GitHub or GitLab scan template from the+[CI 0.7.1 release](https://github.com/NVIDIA/SkillEvaluator/releases/tag/ci-0.7.1).The [template catalog](https://github.com/NVIDIA/SkillEvaluator/blob/main/ci/templates/README.md)-explains release availability and includes the optional GitHub publisher and-manual LLM workflow. Source files contain placeholders; official CI releases-provide copies with the workflow and image versions filled in.+also contains source templates for optional GitHub publishing and LLM checks.+Source files contain placeholders. The release bundle includes filled-in scan+templates and the optional GitHub publisher template.## What you get@@ -64,15 +65,15 @@ Browse [report, log and PR comment examples](https://github.com/NVIDIA/SkillEvalin the public repository. No demo-repository access is needed.<Note>- The first release covers Tier 1. It does not run Tier 2 or Tier 3. An official- CI image release is required before the release-generated configurations can- be used. The source templates contain placeholders until then.+ The released CI image runs Tier 1, including SkillSpector. It does not run+ Tier 2 or Tier 3. GitHub and GitLab use the same scanner image with+ platform-specific workflow files.</Note>## Other CI systemsThe container contains the same evaluator runtime, and the CLI can also run in-other CI systems. The [CI integration guide](ci-integration.mdx) covers the CLI,+other CI systems. The [CI integration guide](/skills/skillevaluator/ci-integration) covers the CLI,exit codes and report formats. The GitHub and GitLab integrations above haveseparate platform-specific configurations; another platform needs its ownintegration and validation.diff --git a/fern/docs.yml b/fern/docs.ymlindex 13fe8779..97125cd5 100644--- a/fern/docs.yml+++ b/fern/docs.yml@@ -77,6 +77,9 @@ navigation:- page: GitHub Actionspath: ../docs/github-actions.mdxslug: github-actions+ - page: GitHub CLI Setup+ path: ../docs/cli-onboarding.mdx+ slug: cli-onboarding- page: GitLab CI/CDpath: ../docs/gitlab-ci.mdxslug: gitlab-cidiff --git a/pyproject.toml b/pyproject.tomlindex 599ecffc..9a637054 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -7,7 +7,7 @@ requires = ["setuptools >= 77", "wheel"][project]name = "skillevaluator"-version = "0.7.0"+version = "0.7.1"description = "Multi-tier framework for evaluating AI agent skills with quality gates, semantic overlap detection, synthetic evaluation dataset generation, and live agent evaluation."authors = [{ name = "NVIDIA Corporation" }]readme = "README.md"@@ -120,6 +120,7 @@ where = ["src"]include = ["skillevaluator*"][tool.setuptools.package-data]+"skillevaluator" = ["ci-release.json"]"skillevaluator.config" = ["*.yaml", "profiles/*.yaml"]"skillevaluator.reporting" = ["templates/*.j2"]"skillevaluator.tier3.harbor" = [diff --git a/src/skillevaluator/__init__.py b/src/skillevaluator/__init__.pyindex fc8f012b..3705e54e 100644--- a/src/skillevaluator/__init__.py+++ b/src/skillevaluator/__init__.py@@ -10,6 +10,6 @@ from importlib.metadata import PackageNotFoundError, versiontry:__version__ = version("skillevaluator")except PackageNotFoundError:- __version__ = "0.7.0"+ __version__ = "0.7.1"__all__ = ["__version__"]diff --git a/src/skillevaluator/_ci_onboarding_git.py b/src/skillevaluator/_ci_onboarding_git.pynew file mode 100644index 00000000..d7e6ee85--- /dev/null+++ b/src/skillevaluator/_ci_onboarding_git.py@@ -0,0 +1,223 @@+# SPDX-License-Identifier: Apache-2.0+"""Git discovery and subprocess helpers for repository onboarding."""++from __future__ import annotations++import os+import re+import subprocess+from collections import Counter+from pathlib import Path, PurePosixPath+from urllib.parse import urlsplit++import yaml++EXCLUDED = {+ "test",+ "tests",+ "fixture",+ "fixtures",+ "example",+ "examples",+ "vendor",+ "vendored",+ "node_modules",+ ".venv",+}++OWNER_REPO = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]*/[A-Za-z0-9][A-Za-z0-9_.-]*")+++class SetupError(Exception):+ """A safely described setup failure."""+++def run(args: list[str], *, cwd: Path | None = None, optional: bool = False, timeout: int = 60) -> str:+ env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}+ env["GIT_TERMINAL_PROMPT"] = "0"+ if args[0] in {"gh", "git"}:+ env["GH_HOST"] = "github.com"+ env.pop("GH_REPO", None)+ try:+ result = subprocess.run(args, cwd=cwd, env=env, text=True, capture_output=True, timeout=timeout)+ except (OSError, subprocess.TimeoutExpired) as exc:+ raise SetupError(f"Could not run {args[0]}; check that it is installed and responsive.") from exc+ if result.returncode and not optional:+ # Do not echo subprocess stderr: authentication helpers can include credentials.+ raise SetupError(f"{args[0]} could not complete this step. Check authentication, access and repository state.")+ return result.stdout if not result.returncode else ""+++def git(repo: Path, *args: str, optional: bool = False, network: bool = False) -> str:+ command = ["git", "-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false"]+ if not network:+ command += ["-c", "protocol.allow=never"]+ else:+ # Accepted SSH origins are normalized to HTTPS for API and push parity.+ # Use the authenticated gh account without changing the user's Git config.+ command += [+ "-c",+ "credential.helper=",+ "-c",+ "credential.https://github.com.helper=!gh auth git-credential",+ ]+ try:+ return run([*command, *args], cwd=repo, optional=optional)+ except SetupError as exc:+ if network and args and args[0] == "push":+ raise SetupError(+ f"{exc} Pushing workflow files also requires workflow write permission. "+ "For a GitHub CLI OAuth login, run: gh auth refresh -h github.com -s workflow"+ ) from exc+ raise+++def repository_root(path: Path) -> Path:+ repo = path.resolve(strict=True)+ top = Path(git(repo, "rev-parse", "--show-toplevel").strip()).resolve(strict=True)+ if top != repo:+ raise SetupError("Run from the Git repository root, or pass that root using --repo.")+ return repo+++def parse_remote(value: str) -> str:+ if value.startswith("[email protected]:"):+ name = value.removeprefix("[email protected]:")+ else:+ parts = urlsplit(value)+ if (+ parts.scheme != "https"+ or parts.hostname != "github.com"+ or parts.username+ or parts.password+ or parts.port+ or parts.query+ or parts.fragment+ ):+ raise SetupError(+ "CI onboarding supports a credential-free github.com HTTPS or [email protected] SSH origin only."+ )+ name = parts.path.removeprefix("/")+ name = name.removesuffix(".git")+ if not OWNER_REPO.fullmatch(name):+ raise SetupError("The origin does not identify a supported GitHub repository.")+ return name+++def safe_relative(value: str) -> str:+ if value == ".":+ return value+ p = PurePosixPath(value)+ if (+ not value+ or p.is_absolute()+ or any(x in {"", ".", ".."} for x in value.split("/"))+ or "\\" in value+ or ":" in value+ or any(ord(c) < 32 or ord(c) == 127 for c in value)+ ):+ raise SetupError("Skill paths must be plain repository-relative directories.")+ return p.as_posix()+++def no_symlinks(repo: Path, relative: str) -> None:+ current = repo+ for part in PurePosixPath(relative).parts:+ current /= part+ if current.is_symlink():+ raise SetupError("Symlink paths are not supported by CI onboarding.")+++def discover(repo: Path) -> list[dict]:+ output = git(repo, "ls-files", "-z", "--cached")+ if len(output.encode()) > 16 * 1024 * 1024:+ raise SetupError("Repository discovery exceeded the discovery size limit.")+ manifests = []+ for path in output.split("\0"):+ if not path or PurePosixPath(path).name != "SKILL.md":+ continue+ safe_relative(path)+ no_symlinks(repo, path)+ if not (repo / path).is_file():+ raise SetupError("A tracked skill manifest is missing. Restore it before onboarding.")+ parents = PurePosixPath(path).parent.parts+ group = None+ for i, part in enumerate(parents):+ if part == "skills" or part.endswith("-skills"):+ group = PurePosixPath(*parents[: i + 1]).as_posix()+ break+ if group is None:+ group = PurePosixPath(*parents[:-1]).as_posix() if len(parents) > 1 else "."+ skill_dir = PurePosixPath(path).parent.as_posix()+ if group == ".":+ group = skill_dir+ manifests.append((skill_dir, group, not bool(set(parents) & EXCLUDED)))+ if not manifests:+ raise SetupError("No tracked SKILL.md files were found. Commit your skills first.")+ if len(manifests) > 1 and any(skill == "." for skill, _, _ in manifests):+ raise SetupError(+ "A root-level SKILL.md together with nested skills cannot be safely isolated by CI onboarding."+ )+ # If fixtures are nested inside a broad skill root, use individual skill+ # directories so recursive CI discovery cannot silently include them.+ mixed_roots = {+ group for _, group, default in manifests if not default and not (set(PurePosixPath(group).parts) & EXCLUDED)+ }+ counts: Counter[str] = Counter()+ defaults = {}+ for skill_dir, group, default in manifests:+ root = skill_dir if group in mixed_roots else group+ counts[root] += 1+ defaults[root] = default+ if any(other != root and (root == "." or other.startswith(root + "/")) for root in counts for other in counts):+ raise SetupError(+ "Overlapping discovered skill roots cannot be isolated safely by CI onboarding. Choose a non-overlapping skill layout."+ )+ return [{"root": root, "count": count, "default": defaults[root]} for root, count in sorted(counts.items())]+++def infer_branch(repo: Path, explicit: str | None) -> str:+ branch = explicit+ if branch is None:+ remote_head = git(repo, "symbolic-ref", "--short", "refs/remotes/origin/HEAD", optional=True).strip()+ branch = remote_head.removeprefix("origin/") if remote_head else None+ if branch is None:+ branch = git(repo, "config", "--local", "--get", "init.defaultBranch", optional=True).strip() or None+ if branch is None:+ branch = git(repo, "symbolic-ref", "--short", "HEAD", optional=True).strip() or None+ if not branch or branch.startswith("-") or any(ord(c) < 32 for c in branch):+ raise SetupError("Cannot infer a default branch. Provide --default-branch.")+ # check-ref-format has no stdout on success, so check it without optional mode.+ git(repo, "check-ref-format", f"refs/heads/{branch}")+ return branch+++class WorkflowDumper(yaml.SafeDumper):+ pass+++def represent_string(dumper, value):+ return dumper.represent_scalar("tag:yaml.org,2002:str", value, style="|" if "\n" in value else None)+++def require_clean(repo: Path) -> None:+ if git(repo, "status", "--porcelain=v1", "--untracked-files=all"):+ raise SetupError("Save or commit existing changes first. Onboarding requires a clean checkout.")+++def require_identity(repo: Path) -> None:+ """Fail before changing GitHub settings if setup cannot create commits."""+ try:+ for key in ("user.name", "user.email"):+ if not git(repo, "config", "--get", key).strip():+ raise SetupError("Missing Git identity")+ for variable in ("GIT_AUTHOR_IDENT", "GIT_COMMITTER_IDENT"):+ git(repo, "var", variable)+ except SetupError as exc:+ raise SetupError(+ "Set your Git commit identity in this repository first: "+ 'git config user.name "Your Name" and git config user.email "[email protected]".'+ ) from exc+++WorkflowDumper.add_representer(str, represent_string)diff --git a/src/skillevaluator/ci-release.json b/src/skillevaluator/ci-release.jsonnew file mode 100644index 00000000..6651a372--- /dev/null+++ b/src/skillevaluator/ci-release.json@@ -0,0 +1,7 @@+{+ "repository": "NVIDIA/SkillEvaluator",+ "workflow_ref": "46a8cf269257d1ec56a0285c508ac9ee48010930",+ "publisher_ref": "46a8cf269257d1ec56a0285c508ac9ee48010930",+ "image": "ghcr.io/nvidia/skillevaluator-tier1@sha256:a3baec51f48145cdf9de05a5ab054d9576f62f1de0f5276b788410f5c17747d4",+ "schema_version": 1+}diff --git a/src/skillevaluator/ci_onboarding.py b/src/skillevaluator/ci_onboarding.pynew file mode 100644index 00000000..3f80794f--- /dev/null+++ b/src/skillevaluator/ci_onboarding.py@@ -0,0 +1,954 @@+# SPDX-License-Identifier: Apache-2.0+"""Interactive GitHub CI onboarding with pinned workflows and optional hosted reports."""++from __future__ import annotations++import base64+import hashlib+import json+import os+import re+import shlex+import subprocess+import sys+import tempfile+from pathlib import Path, PurePosixPath+from urllib.parse import quote, urlsplit++import click+import yaml+from rich.console import Console, Group+from rich.panel import Panel+from rich.table import Table+from rich.text import Text++from skillevaluator import _ci_onboarding_git as git_helpers++SCAN = ".github/workflows/skill-checks.yml"+PUBLISH = ".github/workflows/publish-skill-reports.yml"+BRANCH = "ci/skillevaluator-setup"+DEMO_BRANCH = "ci/skillevaluator-test"+MARKER = ".skillevaluator-report-site.json"+console = Console(highlight=False)+SetupError = git_helpers.SetupError+++def symbol(value: str, fallback: str) -> str:+ """Keep status labels readable in terminals without Unicode support."""+ try:+ value.encode(console.encoding)+ except (UnicodeError, LookupError):+ return fallback+ return value+++def question(number: int, title: str, *content) -> None:+ console.print(+ Panel(+ Group(*(Text(item) if isinstance(item, str) else item for item in content)),+ title=Text(f"{number}/5 {title}", style="bold cyan"),+ title_align="left",+ border_style="cyan",+ width=min(console.width, 92),+ )+ )+++def print_link(url: str) -> None:+ # Keep a literal, untruncated URL in captured output, even on narrow screens.+ console.print(Text(url, style=f"link {url}"), soft_wrap=True)+++def results_help(name: str, full: bool) -> str:+ text = f"Checks {symbol('→', '>')} Skill checks"+ if full:+ text += f" | Bot comment {symbol('→', '>')} Open full report"+ else:+ text += f" | Actions {symbol('→', '>')} Download report"+ return text+++def cli_command(repo: Path, *arguments: str) -> str:+ """Reuse this interpreter's CLI; Windows output targets PowerShell."""+ # Do not resolve the interpreter symlink: that would leave its virtualenv.+ windows = sys.platform == "win32"+ entrypoint = Path(sys.executable).parent / ("skillevaluator.exe" if windows else "skillevaluator")+ if entrypoint.is_file():+ try:+ command = str(entrypoint.relative_to(repo.resolve()))+ if windows:+ command = ".\\" + command+ elif "/" not in command:+ command = "./" + command+ except ValueError:+ command = str(entrypoint)+ parts = [command, *arguments]+ else:+ parts = [sys.executable, "-m", "skillevaluator.cli", *arguments]+ if windows:+ return "& " + " ".join("'" + part.replace("'", "''") + "'" for part in parts)+ return shlex.join(parts)+++def show_next_steps(name: str, full: bool, setup_url: str | None = None, *, repo: Path | None = None) -> None:+ if setup_url:+ heading = f"{symbol('✓', '[OK]')} Setup PR ready"+ body = "Merge this PR to enable checks."+ else:+ heading = f"{symbol('✓', '[OK]')} Setup is configured"+ body = "Ready for your first skill-change PR."+ console.print(+ Panel(Text(body), title=Text(heading), title_align="left", border_style="green", width=min(console.width, 92))+ )+ if setup_url:+ print_link(setup_url)+ console.print("After merging, optionally create a test PR:" if setup_url else "Optional: create a test PR:")+ if sys.platform == "win32":+ console.print("Run in PowerShell:")+ console.print(Text(" " + cli_command(repo or Path.cwd(), "ci", "demo")), soft_wrap=True)+++def show_test_pr(name: str, url: str, *, existing: bool = False, full: bool = True) -> None:+ heading = f"{symbol('✓', '[OK]')} " + ("Test PR already exists" if existing else "Test PR created")+ body = results_help(name, full) + (+ "\nComment follows publication. Close this PR when done."+ if full+ else "\nClose this PR when done; no merge needed."+ )+ console.print(+ Panel(Text(body), title=Text(heading), title_align="left", border_style="green", width=min(console.width, 92))+ )+ print_link(url)+++def load_release(path: Path) -> dict:+ data = json.loads(path.read_text())+ 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":+ raise SetupError("The CI release must use NVIDIA/SkillEvaluator as its workflow provider.")+ for field in ("workflow_ref", "publisher_ref"):+ if not re.fullmatch(r"[0-9a-f]{40}", str(data.get(field, ""))):+ raise SetupError(f"{field} must be an immutable full commit SHA.")+ if not re.fullmatch(r"ghcr\.io/nvidia/skillevaluator-tier1@sha256:[0-9a-f]{64}", str(data.get("image", ""))):+ raise SetupError("The image must use the official immutable digest.")+ return data+++def report_url(name: str, custom: str | None = None) -> str:+ owner, repo_name = name.split("/")+ expected = f"https://{owner.lower()}.github.io/{repo_name}/"+ value = custom or expected+ parts = urlsplit(value)+ if (+ parts.scheme != "https"+ or parts.username+ or parts.password+ or parts.port+ or parts.query+ or parts.fragment+ or value.rstrip("/") != expected.rstrip("/")+ ):+ raise SetupError("The report URL must be this repository's default HTTPS GitHub Pages URL.")+ return expected+++def blob_id(content: str) -> str:+ data = content.encode("utf-8")+ return hashlib.sha1(f"blob {len(data)}\0".encode() + data).hexdigest()+++def yaml_text(value: dict) -> str:+ return yaml.dump(value, Dumper=git_helpers.WorkflowDumper, sort_keys=False, allow_unicode=True, width=1000)+++def render_files(+ release: dict,+ roots: list[str],+ score: int,+ scan_mode: str,+ branch: str,+ name: str,+ full: bool = True,+ url: str | None = None,+) -> dict[str, str]:+ url = report_url(name, url) if full else None+ scan = {+ "name": "Skill checks",+ "on": {"pull_request": None, "push": {"branches": [branch]}, "workflow_dispatch": None},+ "permissions": {"contents": "read"},+ "jobs": {+ "skills": {+ "uses": f"{release['repository']}/.github/workflows/evaluate-skills.yml@{release['workflow_ref']}",+ "with": {+ "image": release["image"],+ "paths": "\n".join(roots),+ "min-score": score,+ "scan-mode": scan_mode,+ "llm": False,+ },+ }+ },+ }+ if full:+ scan["permissions"]["id-token"] = "write"+ scan["jobs"]["skills"]["with"]["report-base-url"] = url+ scan_text = "# Generated by SkillEvaluator CI onboarding.\n" + yaml_text(scan)+ files = {SCAN: scan_text}+ if full:+ publisher = {+ "name": "Publish skill reports",+ "on": {+ "workflow_run": {"workflows": ["Skill checks"], "types": ["completed"]},+ "workflow_dispatch": {+ "inputs": {+ "run-id": {"description": "Completed Skill checks run", "required": True, "type": "string"},+ "run-attempt": {"description": "Completed run attempt", "required": True, "type": "string"},+ }+ },+ },+ "permissions": {+ "contents": "write",+ "actions": "read",+ "pages": "write",+ "id-token": "write",+ "pull-requests": "write",+ },+ "jobs": {+ "reports": {+ "uses": f"{release['repository']}/.github/workflows/publish-skill-reports.yml@{release['publisher_ref']}",+ "with": {+ "run-id": "${{ format('{0}', github.event.workflow_run.id || inputs.run-id) }}",+ "run-attempt": "${{ format('{0}', github.event.workflow_run.run_attempt || inputs.run-attempt) }}",+ "report-base-url": url,+ "trusted-evaluator-shas": release["workflow_ref"],+ "trusted-caller-blobs": blob_id(scan_text),+ "tools-ref": release["publisher_ref"],+ "tools-repository": release["repository"],+ },+ }+ },+ }+ files[PUBLISH] = (+ "# Generated by SkillEvaluator CI onboarding; publisher pinned to a verified commit.\n"+ + yaml_text(publisher)+ )+ return files+++def check_files(repo: Path, files: dict[str, str]) -> list[str]:+ changed = []+ for name, content in files.items():+ git_helpers.no_symlinks(repo, name)+ target = repo / name+ if target.exists():+ if not target.is_file() or target.read_bytes() != content.encode():+ raise SetupError(f"{name} already exists with different content; it will not be replaced.")+ else:+ changed.append(name)+ return changed+++def save_files(repo: Path, files: dict[str, str]) -> None:+ missing = check_files(repo, files)+ if not missing:+ return+ git_helpers.require_clean(repo)+ written = []+ try:+ for name in missing:+ target = repo / name+ target.parent.mkdir(parents=True, exist_ok=True)+ with target.open("x", encoding="utf-8", newline="\n") as stream:+ stream.write(files[name])+ written.append(target)+ except OSError:+ # Undo only files exclusively created by this invocation.+ for target in written:+ target.unlink()+ raise+++def github_api(method: str, endpoint: str, payload: dict | None = None, *, missing_ok=False):+ args = [+ "gh",+ "api",+ "--hostname",+ "github.com",+ "--include",+ "--method",+ method,+ endpoint,+ "--header",+ "Accept: application/vnd.github+json",+ ]+ env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_") and k != "GH_REPO"}+ env["GH_HOST"] = "github.com"+ with tempfile.TemporaryDirectory(prefix="skill-setup-api-") as temporary:+ if payload is not None:+ path = Path(temporary) / "request.json"+ path.write_text(json.dumps(payload))+ args += ["--input", str(path)]+ result = subprocess.run(args, env=env, capture_output=True, text=True, timeout=90)+ response = result.stdout.replace("\r\n", "\n")+ match = re.search(r"^HTTP/[\d.]+\s+(\d+)", response)+ status = int(match[1]) if match else 0+ if missing_ok and status == 404:+ return None+ if result.returncode or not 200 <= status < 300:+ raise SetupError(+ f"GitHub {method} {endpoint} failed (HTTP {status or 'unknown'}). "+ "Check your gh login and repository permissions. No credential was printed."+ )+ body = response.partition("\n\n")[2].strip()+ return json.loads(body) if body else {}+++def decode_content(value: dict) -> bytes:+ if value.get("encoding") != "base64" or not isinstance(value.get("content"), str):+ raise SetupError("GitHub did not return the expected bounded file content.")+ return base64.b64decode(value["content"], validate=False)+++def workflow_inputs(value: dict, job: str) -> dict:+ """Validate the small workflow interface that status and demo consume."""+ try:+ content = yaml.safe_load(decode_content(value))+ inputs = content["jobs"][job]["with"]+ except (KeyError, TypeError, ValueError, yaml.YAMLError) as exc:+ raise SetupError("The existing workflow does not match SkillEvaluator's expected setup.") from exc+ if not isinstance(inputs, dict):+ raise SetupError("The existing workflow has invalid SkillEvaluator inputs.")+ return inputs+++def history_preflight(name: str) -> bool:+ prefix = f"repos/{name}"+ ref = github_api("GET", prefix + "/git/ref/heads/gh-pages", missing_ok=True)+ if ref is None:+ return False+ marker = github_api("GET", prefix + f"/contents/{MARKER}?ref=gh-pages", missing_ok=True)+ if marker is None or json.loads(decode_content(marker)) != {+ "purpose": "skillevaluator-reports",+ "repository": name,+ }:+ raise SetupError(+ "An existing gh-pages branch is not owned by SkillEvaluator. Its site/history will not be overwritten."+ )+ history = github_api("GET", prefix + "/contents/history.json?ref=gh-pages")+ if not isinstance(json.loads(decode_content(history)), list):+ raise SetupError("Existing report history is invalid; inspect it before continuing.")+ return True+++def remote_preflight(repo: Path, name: str, branch: str, full: bool) -> dict:+ git_helpers.require_clean(repo)+ info = github_api("GET", f"repos/{name}")+ if info.get("archived") or not info.get("permissions", {}).get("admin"):+ raise SetupError(+ "Automatic GitHub setup requires repository admin access. Use --mode save to prepare files for an owner."+ )+ if full and (info.get("private") is not False or info.get("visibility", "public") != "public"):+ raise SetupError(+ "Automatic hosted reports support public repositories only. Use --checks-only for private or internal repositories; their reports stay in Actions artifacts."+ )+ if info["default_branch"] != branch:+ raise SetupError("The selected branch differs from GitHub's default branch. Use --default-branch.")+ canonical = f"https://github.com/{name}.git"+ git_helpers.git(+ repo, "fetch", "--no-tags", canonical, f"refs/heads/{branch}:refs/remotes/origin/{branch}", network=True+ )+ if (+ git_helpers.git(repo, "rev-parse", "HEAD").strip()+ != git_helpers.git(repo, "rev-parse", f"origin/{branch}").strip()+ ):+ raise SetupError("Update your checkout to the current remote default branch before creating the setup PR.")+ actions = github_api("GET", f"repos/{name}/actions/permissions")+ if actions.get("allowed_actions") != "all":+ raise SetupError(+ "This repository restricts external actions. Automatic setup preserves that policy; use --mode save and have an owner review the workflow allowlist."+ )+ state = {"info": info, "actions": actions, "history_exists": False, "pages": None}+ if full:+ state["history_exists"] = history_preflight(name)+ state["pages"] = github_api("GET", f"repos/{name}/pages", missing_ok=True)+ if state["pages"] is not None and (+ not state["history_exists"]+ or state["pages"].get("build_type") not in {"workflow", "legacy"}+ or state["pages"].get("cname")+ ):+ raise SetupError("An existing Pages site is outside SkillEvaluator's setup. It will not be replaced.")+ return state+++def branch_preflight(+ repo: Path, name: str, branch: str, files: dict[str, str], changed_files: list[str]+) -> dict | None:+ canonical = f"https://github.com/{name}.git"+ remote = git_helpers.git(repo, "ls-remote", "--heads", canonical, f"refs/heads/{BRANCH}", network=True).strip()+ prs = json.loads(+ git_helpers.run(+ ["gh", "pr", "list", "--repo", name, "--head", BRANCH, "--state", "open", "--json", "url,baseRefName"]+ )+ )+ if len(prs) > 1 or (prs and prs[0]["baseRefName"] != branch):+ raise SetupError("An unexpected onboarding PR exists. Inspect it before continuing.")+ if not remote:+ if prs:+ raise SetupError("The onboarding PR has no matching branch. Inspect it manually.")+ return None+ git_helpers.git(repo, "fetch", "--no-tags", canonical, f"refs/heads/{BRANCH}", network=True)+ changed = git_helpers.git(repo, "diff", "--name-only", f"origin/{branch}...FETCH_HEAD").splitlines()+ if sorted(changed) != sorted(changed_files):+ raise SetupError("The existing setup branch has other changes; it will not be reused.")+ for path, content in files.items():+ if git_helpers.git(repo, "show", f"FETCH_HEAD:{path}") != content:+ raise SetupError("The existing setup branch has a different configuration; it will not be replaced.")+ return {"pr_url": prs[0]["url"] if prs else None}+++def initialize_history(repo: Path, name: str) -> None:+ with tempfile.TemporaryDirectory(prefix="skill-report-history-") as temporary:+ work = Path(temporary)+ git_helpers.git(work, "init", "-b", "gh-pages")+ for key in ("user.name", "user.email"):+ value = git_helpers.git(repo, "config", "--get", key).strip()+ git_helpers.git(work, "config", "--local", key, value)+ (work / ".nojekyll").write_text("")+ (work / "history.json").write_text("[]\n")+ (work / MARKER).write_text(json.dumps({"purpose": "skillevaluator-reports", "repository": name}) + "\n")+ git_helpers.git(work, "add", "--", ".nojekyll", "history.json", MARKER)+ git_helpers.git(+ work,+ "-c",+ "commit.gpgsign=false",+ "commit",+ "--signoff",+ "-m",+ "ci: initialize SkillEvaluator report history",+ )+ git_helpers.git(work, "push", f"https://github.com/{name}.git", "HEAD:refs/heads/gh-pages", network=True)+++def ensure_environment(name: str, branch: str) -> None:+ endpoint = f"repos/{name}/environments/github-pages"+ env = github_api("GET", endpoint, missing_ok=True)+ if env:+ for rule in env.get("protection_rules", []):+ if rule.get("type") in {"required_reviewers", "custom_deployment_protection_rule"} or rule.get(+ "wait_timer", 0+ ):+ raise SetupError(+ "The Pages environment requires approval. Existing protection was preserved; configure it manually."+ )+ policy = env.get("deployment_branch_policy")+ if policy and policy.get("protected_branches"):+ if not github_api("GET", f"repos/{name}/branches/{quote(branch, safe='')}").get("protected"):+ raise SetupError("The Pages environment allows protected branches only; its restriction was preserved.")+ return+ else:+ policy = None+ if not policy:+ github_api(+ "PUT", endpoint, {"deployment_branch_policy": {"protected_branches": False, "custom_branch_policies": True}}+ )+ rules = github_api("GET", endpoint + "/deployment-branch-policies")+ if not any(+ item.get("name") == branch and item.get("type", "branch") == "branch"+ for item in rules.get("branch_policies", [])+ ):+ github_api("POST", endpoint + "/deployment-branch-policies", {"name": branch, "type": "branch"})+++def enable_hosting(repo: Path, name: str, branch: str, state: dict, progress: list[str]) -> None:+ if not state["actions"].get("enabled"):+ github_api("PUT", f"repos/{name}/actions/permissions", {"enabled": True, "allowed_actions": "all"})+ progress.append("GitHub Actions enabled")+ # Creating gh-pages first can auto-enable GitHub's legacy publishing source.+ # Enable the intended workflow source before that branch exists.+ if state["pages"] is None:+ github_api("POST", f"repos/{name}/pages", {"build_type": "workflow"})+ progress.append("GitHub Pages enabled with Actions source")+ elif state["pages"].get("build_type") == "legacy":+ # Preflight requires SkillEvaluator's ownership marker, so an unrelated+ # pre-existing website is never converted or taken over here.+ github_api("PUT", f"repos/{name}/pages", {"build_type": "workflow"})+ progress.append("Owned report site switched to Actions source")+ pages = github_api("GET", f"repos/{name}/pages")+ if (+ pages.get("build_type") != "workflow"+ or pages.get("cname")+ or report_url(name, pages.get("html_url")) != report_url(name)+ ):+ raise SetupError("Pages readback does not match the requested workflow report site.")+ if not state["history_exists"]:+ initialize_history(repo, name)+ progress.append("Report history branch initialized")+ ensure_environment(name, branch)+ progress.append("Pages deployment allowed from the default branch")+++def create_setup(repo: Path, name: str, branch: str, files: dict[str, str], full: bool, plan: dict) -> str | None:+ git_helpers.require_identity(repo)+ state = remote_preflight(repo, name, branch, full)+ existing = branch_preflight(repo, name, branch, files, plan["changed_files"]) if plan["changed_files"] else None+ progress = plan.setdefault("completed_steps", [])+ if full:+ enable_hosting(repo, name, branch, state, progress)+ elif not state["actions"].get("enabled"):+ github_api("PUT", f"repos/{name}/actions/permissions", {"enabled": True, "allowed_actions": "all"})+ progress.append("GitHub Actions enabled")+ if not plan["changed_files"]:+ plan["action"] = "configured"+ return None+ if existing and existing["pr_url"]:+ plan["action"] = "existing-pr"+ return existing["pr_url"]+ canonical = f"https://github.com/{name}.git"+ if not existing:+ temporary = Path(tempfile.mkdtemp(prefix="skill-onboarding-"))+ work = temporary / "checkout"+ added = False+ try:+ git_helpers.git(repo, "worktree", "add", "--detach", str(work), f"origin/{branch}")+ added = True+ save_files(work, files)+ git_helpers.git(work, "add", "--", *files)+ git_helpers.git(+ work,+ "-c",+ "commit.gpgsign=false",+ "commit",+ "--signoff",+ "-m",+ "ci: onboard SkillEvaluator checks and reports",+ )+ git_helpers.git(work, "push", canonical, f"HEAD:refs/heads/{BRANCH}", network=True)+ progress.append("Setup branch pushed")+ finally:+ if added:+ git_helpers.git(repo, "worktree", "remove", str(work), optional=True)+ if not work.exists():+ temporary.rmdir()+ with tempfile.TemporaryDirectory(prefix="skill-setup-pr-") as temporary:+ body = Path(temporary) / "body.md"+ outputs = "downloadable HTML reports" if not full else "hosted HTML reports and one updated PR comment"+ body.write_text(+ f"Bring SkillEvaluator Tier 1 checks, including SkillSpector, to this repository with {outputs}.\n\n"+ f"Skill folders: `{', '.join(plan['selected_roots'])}`. Minimum score: **{plan['min_score']}**. "+ f"PR scan selection: **{plan['scan_mode']}**. No model key is used.\n\n"+ "**After merging:** open a new PR changing a selected skill. The check runs automatically. "+ + (+ "The publisher then deploys the HTML and posts or updates its PR comment.\n\n"+ if full+ else "Download the HTML from Actions.\n\n"+ )+ + "Generated by SkillEvaluator CI onboarding with immutable workflow and image versions. "+ "This setup PR is not an evaluation pass. Existing workflows and merge rules are preserved.\n",+ )+ url = git_helpers.run(+ [+ "gh",+ "pr",+ "create",+ "--repo",+ name,+ "--base",+ branch,+ "--head",+ BRANCH,+ "--title",+ "Set up SkillEvaluator checks and reports",+ "--body-file",+ str(body),+ ]+ ).strip()+ if not re.fullmatch(r"https://github\.com/" + re.escape(name) + r"/pull/[1-9][0-9]*", url):+ raise SetupError("The setup branch was pushed, but the PR URL needs manual inspection.")+ plan["action"] = "created-pr"+ return url+++def select_roots(roots: list[dict], explicit: tuple[str, ...], no_input: bool) -> list[str]:+ suggested = [item for item in roots if item["default"]]+ defaults = [str(roots.index(item) + 1) for item in suggested]+ known = {item["root"]: item["count"] for item in roots}+ if explicit:+ selected = list(dict.fromkeys(git_helpers.safe_relative(value) for value in explicit))+ elif no_input:+ selected = [item["root"] for item in suggested]+ else:+ while True:+ answer = click.prompt("Folders", default=",".join(defaults) or None).strip()+ if not re.fullmatch(r"\d+(?:(?:\s*,\s*|\s+)\d+)*", answer):+ console.print("Use listed numbers: 1,2 or 1 2.", style="yellow")+ continue+ try:+ indices = list(dict.fromkeys(int(value) for value in re.split(r"[,\s]+", answer)))+ except ValueError:+ console.print("Use the short folder numbers shown above.", style="yellow")+ continue+ if any(i < 1 or i > len(roots) for i in indices):+ console.print(f"Choose folder numbers from 1 to {len(roots)}.", style="yellow")+ continue+ selected = [roots[i - 1]["root"] for i in indices]+ if sum(known[value] for value in selected) > 100:+ console.print("Choose fewer folders: 100 skills maximum.", style="yellow")+ continue+ break+ if not selected or any(value not in known for value in selected):+ raise SetupError("Select at least one displayed skill folder.")+ if sum(known[value] for value in selected) > 100:+ raise SetupError("Select at most 100 skills for one CI workflow.")+ return selected+++def ci():+ """Set up checks, HTML reports and PR comments."""++[email protected]("init")[email protected]("--repo", type=click.Path(path_type=Path, exists=True, file_okay=False), default=Path.cwd)+ "--release",+ "release_path",+ default=None,+ help="Pinned CI release descriptor; defaults to the bundled release.",+ type=click.Path(path_type=Path, exists=True, dir_okay=False),+)[email protected]("--paths", multiple=True)[email protected]("--min-score", type=click.IntRange(0, 100), default=None)[email protected]("--scan-mode", type=click.Choice(["auto", "all"]), default=None)[email protected]("--default-branch", default=None)[email protected]("--full/--checks-only", default=None, help="Full setup includes hosted reports and PR comments.")[email protected]("--report-url", "custom_url", default=None)[email protected]("--mode", type=click.Choice(["preview", "save", "pr"]), default=None)+ "--no-input", is_flag=True, help="Use defaults; requires --mode. --mode pr authorizes the displayed setup."+)[email protected]("--show-files", is_flag=True)+ "--output",+ type=click.Path(path_type=Path),+ default=None,+ help="Optional new receipt outside the consumer checkout.",+)+def init(+ repo,+ release_path,+ paths,+ min_score,+ scan_mode,+ default_branch,+ full,+ custom_url,+ mode,+ no_input,+ show_files,+ output,+):+ plan = None+ try:+ repo = git_helpers.repository_root(repo)+ if output:+ output = output.resolve()+ if output.exists() or output.is_relative_to(repo):+ raise SetupError("Choose a new receipt path outside the consumer checkout.")+ 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())+ branch = git_helpers.infer_branch(repo, default_branch)+ roots = git_helpers.discover(repo)+ console.print("Bring SkillEvaluator to your repository", style="bold green")+ console.print("GitHub | Tier 1 + SkillSpector | no model key", style="dim")+ console.print(f"{name} | {branch}", markup=False)+ table = Table("#", "Skill folder", "Skills", "Suggested")+ for i, item in enumerate(roots, 1):+ suggested = item["default"]+ table.add_row(str(i), Text(item["root"]), str(item["count"]), "Yes" if suggested else "Optional")+ selection_hint = "Use folder numbers: 1 or 1,2. Spaces work too."+ if len(roots) == 1:+ selection_hint = "Use folder number 1."+ if any(item["default"] for item in roots):+ selection_hint += " Enter accepts the default."+ else:+ selection_hint += "\nNo default: enter a number to continue."+ question(1, "Which skill folders?", table, selection_hint)+ selected = select_roots(roots, paths, no_input)+ selected_count = sum(item["count"] for item in roots if item["root"] in selected)+ console.print(f"{symbol('✓', '[OK]')} Selected: {', '.join(selected)} ({selected_count} skills)", markup=False)+ question(2, "Minimum quality score?", "Fail below this score (0-100). Other required checks also apply.")+ score = (+ min_score+ if min_score is not None+ else (70 if no_input else click.prompt("Score", default=70, type=click.IntRange(0, 100)))+ )+ question(+ 3,+ "What should PRs check?",+ "auto = changed skills (recommended)\nall = every skill in your selected folders",+ )+ scan = (+ scan_mode+ if scan_mode is not None+ else ("auto" if no_input else click.prompt("PR scope", default="auto", type=click.Choice(["auto", "all"])))+ )+ question(+ 4,+ "Add hosted reports and PR comments?",+ "Always included: checks + downloadable HTML.\nOptional: a public report site + one updated PR comment.",+ )+ if full is None:+ full = True if no_input else click.confirm("Add hosted feedback?", default=True)+ url = report_url(name, custom_url) if full else None+ files = render_files(release, selected, score, scan, branch, name, full, url)+ changed = check_files(repo, files)+ plan = {+ "repository": name,+ "default_branch": branch,+ "selected_roots": selected,+ "min_score": score,+ "scan_mode": scan,+ "full": full,+ "report_url": url,+ "changed_files": changed,+ "scan_blob": blob_id(files[SCAN]),+ "workflow_ref": release["workflow_ref"],+ "publisher_ref": release["publisher_ref"] if full else None,+ "image": release["image"],+ "completed_steps": [],+ }+ summary = Table.grid(padding=(0, 2))+ summary.add_row("Skills", Text(f"{selected_count} in {', '.join(selected)}"))+ summary.add_row("Quality gate", f"{score}/100")+ summary.add_row("PR checks", "Changed skills" if scan == "auto" else "All selected skills")+ if full:+ summary.add_row("Feedback", "Public HTML + updated PR comment")+ summary.add_row("Setup", "2 workflow files + GitHub Pages")+ else:+ summary.add_row("Feedback", "Check + downloadable HTML")+ summary.add_row("Setup", "1 workflow file")+ question(+ 5, "Ready to set up?", summary, "pr = set up GitHub + open PR | preview = no changes | save = files only"+ )+ if show_files:+ for path, content in files.items():+ console.print(f"\n{path}\n{content}", markup=False)+ if not changed:+ console.print("Workflow files already match.")+ if mode is None:+ mode = click.prompt("Next", default="pr", type=click.Choice(["preview", "save", "pr"]))+ plan["requested_action"] = mode+ if mode == "preview":+ plan["action"] = "preview"+ console.print("No changes applied. Preview needs no login.")+ elif mode == "save":+ if not no_input and changed and not click.confirm("Save these workflow files locally?", default=False):+ plan["action"] = "cancelled"+ console.print("Cancelled. No changes applied.")+ else:+ save_files(repo, files)+ plan["action"] = "saved" if changed else "unchanged"+ console.print("Files saved. Remote settings were not changed. Use PR mode for automatic GitHub setup.")+ elif 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.")+ else:+ console.print("Checking GitHub access…")+ url_pr = create_setup(repo, name, branch, files, full, plan)+ if url_pr:+ plan["pr_url"] = url_pr+ show_next_steps(name, full, url_pr, repo=repo)+ else:+ show_next_steps(name, full, repo=repo)+ if output:+ output.parent.mkdir(parents=True, exist_ok=True)+ with output.open("x", encoding="utf-8") as stream:+ json.dump(plan, stream, indent=2)+ stream.write("\n")+ except (SetupError, OSError, ValueError, subprocess.TimeoutExpired) as exc:+ if plan and plan.get("completed_steps"):+ console.print("Completed before the interruption: " + "; ".join(plan["completed_steps"]), markup=False)+ console.print("Rerun the same setup to resume; existing files/history will be preserved.")+ raise click.ClickException(str(exc)) from exc++[email protected]("status")[email protected]("--repo", type=click.Path(path_type=Path, exists=True, file_okay=False), default=Path.cwd)+def status(repo):+ """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())+ info = github_api("GET", f"repos/{name}")+ branch = info["default_branch"]+ pages = github_api("GET", f"repos/{name}/pages", missing_ok=True)+ scan = github_api("GET", f"repos/{name}/contents/{SCAN}?ref={quote(branch, safe='')}", missing_ok=True)+ publisher = github_api("GET", f"repos/{name}/contents/{PUBLISH}?ref={quote(branch, safe='')}", missing_ok=True)+ table = Table("Component", "Live state")+ table.add_row("Checks", "Configured on default branch" if scan else "Awaiting setup PR merge")+ table.add_row("Publisher", "Configured on default branch" if publisher else "Not enabled (optional)")+ table.add_row("Pages", pages["html_url"] if pages else "Not enabled")+ if scan and publisher:+ scan_bytes = decode_content(scan)+ blob = hashlib.sha1(f"blob {len(scan_bytes)}\0".encode() + scan_bytes).hexdigest()+ inputs = workflow_inputs(publisher, "reports")+ approved = inputs.get("trusted-caller-blobs")+ if not isinstance(approved, str):+ raise SetupError("The publisher workflow is missing its scan-file approval.")+ trusted = re.split(r"[,\s]+", approved)+ table.add_row(+ "Scan approval",+ "Matches exact workflow" if blob in trusted else "Needs refresh; publisher will reject it",+ )+ console.print(table)+ for filename, label in [+ ("skill-checks.yml", "Latest scan"),+ ("publish-skill-reports.yml", "Latest publication"),+ ]:+ value = github_api("GET", f"repos/{name}/actions/workflows/{filename}/runs?per_page=1", missing_ok=True)+ if value and value.get("workflow_runs"):+ item = value["workflow_runs"][0]+ console.print(f"{label}: {item.get('conclusion') or item['status']}\n{item['html_url']}", markup=False)+ console.print(+ "Configuration alone is not a verified scan. Open a skill PR to inspect its check, comment and report."+ )+ except (SetupError, OSError, ValueError, subprocess.TimeoutExpired) as exc:+ raise click.ClickException(str(exc)) from exc++[email protected]("demo")[email protected]("--repo", type=click.Path(path_type=Path, exists=True, file_okay=False), default=Path.cwd)[email protected]("--no-input", is_flag=True, help="Authorize opening one small skill-change PR.")+def demo(repo, no_input):+ """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())+ info = github_api("GET", f"repos/{name}")+ permissions = info.get("permissions", {})+ if info.get("archived") or not (permissions.get("push") or permissions.get("admin")):+ raise SetupError("Your GitHub login needs write access to create a test PR.")+ branch = info["default_branch"]+ scan_file = github_api("GET", f"repos/{name}/contents/{SCAN}?ref={quote(branch, safe='')}", missing_ok=True)+ if scan_file is None:+ raise SetupError("Merge the setup PR first. The scan workflow is not on the default branch yet.")+ publisher_file = github_api(+ "GET", f"repos/{name}/contents/{PUBLISH}?ref={quote(branch, safe='')}", missing_ok=True+ )+ full = publisher_file is not None+ inputs = workflow_inputs(scan_file, "skills")+ paths = inputs.get("paths")+ if not isinstance(paths, str):+ raise SetupError("The scan workflow is missing its configured skill paths.")+ roots = [git_helpers.safe_relative(value.strip()) for value in paths.splitlines() if value.strip()]+ if not roots:+ raise SetupError("No skill roots are configured on the default branch.")+ demo_branch = DEMO_BRANCH+ existing = json.loads(+ git_helpers.run(+ ["gh", "pr", "list", "--repo", name, "--head", demo_branch, "--state", "open", "--json", "url"]+ )+ )+ if existing:+ show_test_pr(name, existing[0]["url"], existing=True, full=full)+ return+ 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(+ "A previous demo branch exists without an open PR. Inspect it manually; it will not be replaced."+ )+ console.print(+ Panel(+ Text(+ "Add a Markdown comment to one selected skill on a new branch.\nClose the test PR afterward; no merge needed."+ ),+ title="Create a test PR?",+ title_align="left",+ border_style="cyan",+ width=min(console.width, 92),+ )+ )+ if not no_input and not click.confirm("Create test PR?", default=False):+ console.print("Cancelled. No changes applied.")+ return+ git_helpers.require_identity(repo)+ git_helpers.git(+ repo, "fetch", "--no-tags", canonical, f"refs/heads/{branch}:refs/remotes/origin/{branch}", network=True+ )+ temporary = Path(tempfile.mkdtemp(prefix="skill-feedback-demo-"))+ work = temporary / "checkout"+ added = False+ try:+ git_helpers.git(repo, "worktree", "add", "--detach", str(work), f"origin/{branch}")+ added = True+ manifests = git_helpers.git(work, "ls-files", "-z").split("\0")+ candidates = sorted(+ path+ for path in manifests+ if PurePosixPath(path).name == "SKILL.md"+ and any(root == "." or path.startswith(root + "/") for root in roots)+ )+ if not candidates:+ raise SetupError("No tracked skill manifest matches the configured roots.")+ target = candidates[0]+ git_helpers.no_symlinks(work, target)+ path = work / target+ if not path.is_file():+ raise SetupError("The demonstration manifest is missing.")+ with path.open("a", encoding="utf-8", newline="\n") as stream:+ stream.write("\n<!-- SkillEvaluator onboarding demo: exercise automatic PR feedback. -->\n")+ git_helpers.git(work, "add", "--", target)+ git_helpers.git(+ work,+ "-c",+ "commit.gpgsign=false",+ "commit",+ "--signoff",+ "-m",+ "test: try automatic SkillEvaluator PR feedback",+ )+ git_helpers.git(work, "push", canonical, f"HEAD:refs/heads/{demo_branch}", network=True)+ body = temporary / "body.md"+ feedback = (+ "Its bot comment links to the HTML report after publication."+ if full+ else "Download the HTML report from the Skill checks run."+ )+ body.write_text(+ f"Make a small Markdown-comment change to `{target}` to try SkillEvaluator.\n\nThe check evaluates this changed skill. {feedback}\n"+ )+ url = git_helpers.run(+ [+ "gh",+ "pr",+ "create",+ "--repo",+ name,+ "--base",+ branch,+ "--head",+ demo_branch,+ "--title",+ "Try automatic SkillEvaluator PR feedback",+ "--body-file",+ str(body),+ ]+ ).strip()+ if not re.fullmatch(r"https://github\.com/" + re.escape(name) + r"/pull/[1-9][0-9]*", url):+ raise SetupError("The test branch was pushed, but its PR URL needs manual inspection.")+ show_test_pr(name, url, full=full)+ finally:+ if added:+ git_helpers.git(repo, "worktree", "remove", str(work), optional=True)+ if not work.exists():+ for child in temporary.iterdir():+ if child.is_file():+ child.unlink()+ temporary.rmdir()+ except (SetupError, OSError, ValueError, subprocess.TimeoutExpired) as exc:+ raise click.ClickException(str(exc)) from excdiff --git a/src/skillevaluator/cli.py b/src/skillevaluator/cli.pyindex 178e2b7c..80d27425 100644--- a/src/skillevaluator/cli.py+++ b/src/skillevaluator/cli.py@@ -209,6 +209,7 @@ Examples:_TOP_LEVEL_COMMAND_HELP_GROUPS = (("Tier workflows", ("tier1", "tier2", "tier3")),("Core workflows", ("validate", "health-check", "doctor", "models", "dashboard")),+ ("Repository CI", ("ci",)),("Tier 1 · Static and security",("quality-check", "rubric-eval", "security-scan", "pii-scan", "lint-scripts"),@@ -3622,6 +3623,10 @@ from skillevaluator.tier3.workflow import build_tier3_workflowtier3.workflow = build_tier3_workflow(evaluate)cli.add_command(harbor_view, "harbor-view")+from skillevaluator.ci_onboarding import ci as ci_onboarding_group++cli.add_command(ci_onboarding_group)+if __name__ == "__main__":cli()diff --git a/tests/ci/test_render_templates.py b/tests/ci/test_render_templates.pyindex 58f3ffd6..e71c3e95 100644--- a/tests/ci/test_render_templates.py+++ b/tests/ci/test_render_templates.py@@ -2,7 +2,9 @@# SPDX-License-Identifier: Apache-2.0import importlib.util+import jsonimport subprocess+import sysfrom pathlib import Pathimport pytest@@ -20,6 +22,7 @@ def test_release_templates_are_copyable_and_bind_the_actual_caller(tmp_path):scan_path = output / "skill-checks.yml"blob = subprocess.check_output(["git", "hash-object", str(scan_path)], text=True).strip()assert receipt["caller_blob"] == blob+ assert receipt["publisher_ref"] == receipt["workflow_ref"] == "b" * 40scan = yaml.load(scan_path.read_text(), Loader=yaml.BaseLoader)assert scan["jobs"]["skills"]["with"]["image"] == imageassert scan["jobs"]["skills"]["uses"].endswith("@" + "b" * 40)@@ -31,6 +34,55 @@ def test_release_templates_are_copyable_and_bind_the_actual_caller(tmp_path):assert "YOUR_REPORT_BASE_URL" in (output / "publish-skill-reports.yml").read_text()+def test_separate_publisher_revision_preserves_scanner_and_caller_trust(tmp_path):+ output = tmp_path / "onboarding"+ scanner_ref, publisher_ref = "b" * 40, "c" * 40+ image = "ghcr.io/nvidia/skillevaluator-tier1@sha256:" + "a" * 64+ subprocess.run(+ [+ sys.executable,+ str(SPEC.origin),+ "--workflow-ref",+ scanner_ref,+ "--publisher-ref",+ publisher_ref,+ "--image",+ image,+ "--output",+ str(output),+ ],+ check=True,+ capture_output=True,+ )+ receipt = json.loads((output / "release.json").read_text())+ assert receipt["workflow_ref"] == scanner_ref+ assert receipt["publisher_ref"] == publisher_ref+ assert receipt["image"] == image+ blob = subprocess.check_output(["git", "hash-object", str(output / "skill-checks.yml")], text=True).strip()+ assert receipt["caller_blob"] == blob+ publisher = yaml.load((output / "publish-skill-reports.yml").read_text(), Loader=yaml.BaseLoader)["jobs"]["reports"]+ assert publisher["uses"].endswith("@" + publisher_ref)+ assert publisher["with"]["tools-ref"] == publisher_ref+ assert publisher["with"]["trusted-evaluator-shas"] == scanner_ref+ assert publisher["with"]["trusted-caller-blobs"] == blob+ assert publisher_ref in (output / "README.md").read_text()+ for name in ("skill-checks.yml", "skill-checks-llm.yml", "gitlab-skill-checks.yml"):+ content = (output / name).read_text()+ assert scanner_ref in content and image in content+ assert publisher_ref not in content+ assert "RELEASE_" not in content++[email protected]("publisher_ref", ["", "main", "a" * 39, "a" * 41])+def test_invalid_publisher_revision_is_rejected_before_writing(tmp_path, publisher_ref):+ output = tmp_path / "onboarding"+ with pytest.raises(ValueError, match="publisher commit SHA"):+ release.render_templates(+ output, "b" * 40, "ghcr.io/nvidia/scan@sha256:" + "a" * 64, publisher_ref=publisher_ref+ )+ assert not output.exists()++@pytest.mark.parametrize("ref,image,repository",[diff --git a/tests/golden/_cli_surface.py b/tests/golden/_cli_surface.pyindex c1ddb6d4..02c2827d 100644--- a/tests/golden/_cli_surface.py+++ b/tests/golden/_cli_surface.py@@ -10,11 +10,24 @@ change *names* and not the command structure.from __future__ import annotations+from pathlib import Pathfrom typing import Anyimport click+def _default_to_string(value: Any) -> str:+ if not callable(value):+ return str(value)+ # pathlib moved this classmethod between private implementations in 3.13.+ # Keep its public identity, without evaluating the current working directory.+ if value == Path.cwd:+ return "<callable pathlib.Path.cwd>"+ module = getattr(value, "__module__", type(value).__module__)+ name = getattr(value, "__qualname__", type(value).__qualname__)+ return f"<callable {module}.{name}>"++def _param_to_dict(param: click.Parameter) -> dict[str, Any]:data: dict[str, Any] = {"name": param.name,@@ -34,7 +47,7 @@ def _param_to_dict(param: click.Parameter) -> dict[str, Any]:data["required"] = Truedefault = getattr(param, "default", None)if default is not None and default is not getattr(click.core, "UNSET", None):- data["default"] = str(default)+ data["default"] = _default_to_string(default)param_type = getattr(param, "type", None)if isinstance(param_type, click.Choice):data["choices"] = list(param_type.choices)diff --git a/tests/golden/cli_surface.json b/tests/golden/cli_surface.jsonindex ca2603d5..816c14ee 100644--- a/tests/golden/cli_surface.json+++ b/tests/golden/cli_surface.json@@ -1,5 +1,163 @@{"commands": {+ "ci": {+ "commands": {+ "demo": {+ "params": [+ {+ "default": "<callable pathlib.Path.cwd>",+ "name": "repo",+ "opts": [+ "--repo"+ ],+ "param_type": "option",+ "type": "directory"+ },+ {+ "default": "False",+ "is_flag": true,+ "name": "no_input",+ "opts": [+ "--no-input"+ ],+ "param_type": "option",+ "type": "boolean"+ }+ ]+ },+ "init": {+ "params": [+ {+ "default": "<callable pathlib.Path.cwd>",+ "name": "repo",+ "opts": [+ "--repo"+ ],+ "param_type": "option",+ "type": "directory"+ },+ {+ "name": "release_path",+ "opts": [+ "--release"+ ],+ "param_type": "option",+ "type": "file"+ },+ {+ "multiple": true,+ "name": "paths",+ "opts": [+ "--paths"+ ],+ "param_type": "option",+ "type": "text"+ },+ {+ "name": "min_score",+ "opts": [+ "--min-score"+ ],+ "param_type": "option",+ "type": "integer range"+ },+ {+ "choices": [+ "auto",+ "all"+ ],+ "name": "scan_mode",+ "opts": [+ "--scan-mode"+ ],+ "param_type": "option"+ },+ {+ "name": "default_branch",+ "opts": [+ "--default-branch"+ ],+ "param_type": "option",+ "type": "text"+ },+ {+ "is_flag": true,+ "name": "full",+ "opts": [+ "--full"+ ],+ "param_type": "option",+ "secondary_opts": [+ "--checks-only"+ ],+ "type": "boolean"+ },+ {+ "name": "custom_url",+ "opts": [+ "--report-url"+ ],+ "param_type": "option",+ "type": "text"+ },+ {+ "choices": [+ "preview",+ "save",+ "pr"+ ],+ "name": "mode",+ "opts": [+ "--mode"+ ],+ "param_type": "option"+ },+ {+ "default": "False",+ "is_flag": true,+ "name": "no_input",+ "opts": [+ "--no-input"+ ],+ "param_type": "option",+ "type": "boolean"+ },+ {+ "default": "False",+ "is_flag": true,+ "name": "show_files",+ "opts": [+ "--show-files"+ ],+ "param_type": "option",+ "type": "boolean"+ },+ {+ "name": "output",+ "opts": [+ "--output"+ ],+ "param_type": "option",+ "type": "path"+ }+ ]+ },+ "status": {+ "params": [+ {+ "default": "<callable pathlib.Path.cwd>",+ "name": "repo",+ "opts": [+ "--repo"+ ],+ "param_type": "option",+ "type": "directory"+ }+ ]+ }+ },+ "params": []+ },"compare": {"params": [{diff --git a/tests/golden/test_cli_surface.py b/tests/golden/test_cli_surface.pyindex f400f8bd..0934c795 100644--- a/tests/golden/test_cli_surface.py+++ b/tests/golden/test_cli_surface.py@@ -15,6 +15,8 @@ import jsonimport sysfrom pathlib import Path+import click+sys.path.insert(0, str(Path(__file__).resolve().parent))from _cli_surface import build_cli_surface@@ -24,6 +26,27 @@ from skillevaluator.cli import cliGOLDEN = Path(__file__).resolve().parent / "cli_surface.json"+def test_callable_defaults_are_named_without_evaluation() -> None:+ def first_default():+ raise AssertionError("Golden serialization must not call a dynamic default")++ def second_default():+ raise AssertionError("Golden serialization must not call a dynamic default")++ group = click.Group(+ params=[click.Option(["--first"], default=first_default), click.Option(["--second"], default=second_default)]+ )+ defaults = [param["default"] for param in build_cli_surface(group)["params"]]+ assert defaults[0] != defaults[1]+ assert "first_default" in defaults[0] and "second_default" in defaults[1]+ assert all(value.startswith("<callable ") and "0x" not in value for value in defaults)+++def test_cwd_default_uses_its_stable_public_identity() -> None:+ group = click.Group(params=[click.Option(["--repo"], default=Path.cwd)])+ assert build_cli_surface(group)["params"][0]["default"] == "<callable pathlib.Path.cwd>"++def test_cli_surface_matches_golden() -> None:expected = json.loads(GOLDEN.read_text(encoding="utf-8"))actual = build_cli_surface(cli)diff --git a/tests/test_ci_onboarding.py b/tests/test_ci_onboarding.pynew file mode 100644index 00000000..89501ce6--- /dev/null+++ b/tests/test_ci_onboarding.py@@ -0,0 +1,583 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++"""Behavioral safety and output checks; live GitHub is verified separately."""++import hashlib+import json+import subprocess++import pytest+import yaml+from click.testing import CliRunner++from skillevaluator import ci_onboarding as wizard+from skillevaluator.cli import cli++RELEASE = {+ "schema_version": 1,+ "repository": "NVIDIA/SkillEvaluator",+ "workflow_ref": "e4cda13a85f34fa7a112b3529feaf24cfe587caf",+ "publisher_ref": "1f3c98cf1b178d5446e31cc187c97a6a697d599a",+ "image": "ghcr.io/nvidia/skillevaluator-tier1@sha256:" + "c" * 64,+}+++def repository(tmp_path):+ repo = tmp_path / "consumer"+ repo.mkdir()++ def git(*args):+ return subprocess.check_output(+ ["git", "-c", "core.hooksPath=/dev/null", "-c", "commit.gpgsign=false", "-C", str(repo), *args],+ text=True,+ )++ git("init", "-b", "trunk")+ git("config", "user.name", "Onboarding tests")+ git("config", "user.email", "[email protected]")+ git("remote", "add", "origin", "https://github.com/example-org/consumer.git")+ for name in [+ "skills/a/SKILL.md",+ "skills/b/SKILL.md",+ ".agents/skills/c/SKILL.md",+ "tests/fixtures/invalid/SKILL.md",+ ]:+ path = repo / name+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text("---\nname: example\n---\n")+ existing = repo / ".github/workflows/existing.yml"+ existing.parent.mkdir(parents=True)+ existing.write_text("name: Preserve me\n")+ git("add", ".")+ git("commit", "-m", "Create test skills")+ return repo+++def release_file(tmp_path):+ path = tmp_path / "release.json"+ path.write_text(json.dumps(RELEASE))+ return path+++def invoke(repository, release_file, *args, input_text=None):+ return CliRunner().invoke(+ cli, ["ci", "init", "--repo", str(repository), "--release", str(release_file), *args], input=input_text+ )+++def test_full_preview_needs_no_login_and_leaves_checkout_unchanged(repository, release_file, monkeypatch):+ # A preview accidentally calling GitHub or writing workflows must fail this test.+ monkeypatch.setenv("GH_HOST", "wrong.example")++ def no_api(*args, **kwargs):+ raise AssertionError("Preview must not use GitHub")++ monkeypatch.setattr(wizard, "github_api", no_api)+ before = subprocess.check_output(["git", "-C", str(repository), "status", "--porcelain"])+ result = invoke(repository, release_file, "--no-input", "--mode", "preview")+ assert result.exit_code == 0, result.output+ assert "PR comment" in result.output+ assert "Pages" in result.output+ assert "No changes applied" in result.output+ assert not (repository / ".github/workflows/skill-checks.yml").exists()+ assert not (repository / ".github/workflows/publish-skill-reports.yml").exists()+ assert subprocess.check_output(["git", "-C", str(repository), "status", "--porcelain"]) == before++[email protected]("answer", ["1,2", "1, 2", "1 2", "1, 2 1"])+def test_folder_input_accepts_commas_and_spaces(repository, release_file, tmp_path, answer):+ receipt = tmp_path / "selection.json"+ result = invoke(+ repository,+ release_file,+ "--mode",+ "preview",+ "--min-score",+ "70",+ "--scan-mode",+ "auto",+ "--full",+ "--output",+ str(receipt),+ input_text=answer + "\n",+ )+ assert result.exit_code == 0, result.output+ assert json.loads(receipt.read_text())["selected_roots"] == [".agents/skills", "skills"]+ assert not (repository / wizard.SCAN).exists()+++def test_invalid_folder_choice_can_be_corrected_in_same_interview(repository, release_file, tmp_path):+ receipt = tmp_path / "recovered.json"+ before = subprocess.check_output(["git", "-C", str(repository), "status", "--porcelain"])+ result = invoke(+ repository,+ release_file,+ "--mode",+ "preview",+ "--min-score",+ "70",+ "--scan-mode",+ "auto",+ "--full",+ "--output",+ str(receipt),+ input_text="0\n1,,2\n9\n1 2\n",+ )+ assert result.exit_code == 0, result.output+ assert json.loads(receipt.read_text())["selected_roots"] == [".agents/skills", "skills"]+ assert subprocess.check_output(["git", "-C", str(repository), "status", "--porcelain"]) == before+++def test_interactive_selection_can_recover_from_skill_limit(monkeypatch):+ answers = iter(["1 2", "1"])+ monkeypatch.setattr(wizard.click, "prompt", lambda *_args, **_kwargs: next(answers))+ roots = [{"root": "skills", "count": 100, "default": True}, {"root": "extra", "count": 1, "default": False}]+ assert wizard.select_roots(roots, (), False) == ["skills"]+ with pytest.raises(wizard.SetupError, match="at most 100"):+ wizard.select_roots(roots, ("skills", "extra"), True)++[email protected]("optional_folders", [1, 2])+def test_optional_only_roots_require_explicit_numbers(repository, release_file, optional_folders):+ def git(*args):+ return subprocess.check_output(+ ["git", "-c", "core.hooksPath=/dev/null", "-C", str(repository), *args], text=True+ )++ git("rm", "-r", "--cached", "skills", ".agents")+ if optional_folders == 2:+ sample = repository / "examples/demo/SKILL.md"+ sample.parent.mkdir(parents=True)+ sample.write_text("---\nname: demo\n---\n")+ git("add", "examples")+ assert not any(root["default"] for root in wizard.git_helpers.discover(repository))+ result = invoke(+ repository,+ release_file,+ "--mode",+ "preview",+ "--min-score",+ "70",+ "--scan-mode",+ "auto",+ "--checks-only",+ input_text="\n1\n",+ )+ assert result.exit_code == 0, result.output+ assert "No default: enter a number to continue." in result.output+ assert "Enter accepts" not in result.output+ assert "press Enter" not in result.output+ assert "Folders []" not in result.output+ assert "No changes applied" in result.output+ unattended = invoke(repository, release_file, "--mode", "preview", "--no-input")+ assert unattended.exit_code != 0+ assert "Select at least one displayed skill folder" in unattended.output++[email protected]("width", [80, 140])+def test_completion_keeps_long_pr_links_copyable(monkeypatch, tmp_path, width):+ from io import StringIO++ from rich.console import Console++ stream = StringIO()+ monkeypatch.setattr(wizard, "console", Console(file=stream, width=width, color_system=None))+ url = "https://github.com/example-org/skill-evaluator-example/pull/123456789"+ wizard.show_next_steps("example-org/skill-evaluator-example", True, url, repo=tmp_path)+ wizard.show_test_pr("example-org/skill-evaluator-example", url)+ assert stream.getvalue().count(url) == 2+++def test_full_save_approves_exact_scan_bytes_and_preserves_existing_workflow(repository, release_file):+ result = invoke(repository, release_file, "--no-input", "--mode", "save", "--paths", "skills")+ assert result.exit_code == 0, result.output+ scan_path = repository / ".github/workflows/skill-checks.yml"+ scan_bytes = scan_path.read_bytes()+ scan = yaml.safe_load(scan_bytes)+ publisher = yaml.safe_load((repository / ".github/workflows/publish-skill-reports.yml").read_text())+ inputs = publisher["jobs"]["reports"]["with"]+ # Git's blob identity, calculated independently from the renderer under test.+ expected = hashlib.sha1(f"blob {len(scan_bytes)}\0".encode() + scan_bytes).hexdigest()+ assert inputs["trusted-caller-blobs"] == expected+ assert scan["permissions"] == {"contents": "read", "id-token": "write"}+ assert scan["jobs"]["skills"]["with"]["paths"] == "skills"+ assert scan["jobs"]["skills"]["with"]["report-base-url"] == inputs["report-base-url"]+ assert publisher["jobs"]["reports"]["uses"].endswith("@" + RELEASE["publisher_ref"])+ assert inputs["tools-ref"] == RELEASE["publisher_ref"]+ assert inputs["trusted-evaluator-shas"] == RELEASE["workflow_ref"]+ assert (repository / ".github/workflows/existing.yml").read_text() == "name: Preserve me\n"+ assert "Remote settings were not changed" in result.output+++def test_scan_only_does_not_request_identity_or_generate_publisher(repository, release_file):+ result = invoke(repository, release_file, "--no-input", "--mode", "save", "--checks-only")+ assert result.exit_code == 0, result.output+ scan = yaml.safe_load((repository / ".github/workflows/skill-checks.yml").read_text())+ assert scan["permissions"] == {"contents": "read"}+ assert "report-base-url" not in scan["jobs"]["skills"]["with"]+ assert not (repository / ".github/workflows/publish-skill-reports.yml").exists()+++def test_conflicting_publisher_does_not_partially_write_scan(repository, release_file):+ target = repository / ".github/workflows/publish-skill-reports.yml"+ target.write_text("name: My existing publisher\n")+ result = invoke(repository, release_file, "--no-input", "--mode", "save")+ assert result.exit_code != 0+ assert "different content" in result.output+ assert not (repository / ".github/workflows/skill-checks.yml").exists()+ assert target.read_text() == "name: My existing publisher\n"+++def test_save_is_idempotent_even_before_files_are_committed(repository, release_file):+ first = invoke(repository, release_file, "--no-input", "--mode", "save")+ assert first.exit_code == 0, first.output+ before = (repository / ".github/workflows/skill-checks.yml").stat().st_mtime_ns+ second = invoke(repository, release_file, "--no-input", "--mode", "save")+ assert second.exit_code == 0, second.output+ assert "already match" in second.output+ assert (repository / ".github/workflows/skill-checks.yml").stat().st_mtime_ns == before+++ "url",+ [+ "http://example-org.github.io/example/",+ "https://evil.example/",+ "https://user:[email protected]/example/",+ "https://example-org.github.io/example/?x=1",+ ],+)+def test_report_url_rejects_external_or_credential_bearing_sites(repository, release_file, url):+ result = invoke(repository, release_file, "--no-input", "--mode", "preview", "--report-url", url)+ assert result.exit_code != 0+ assert "report URL" in result.output+++def test_invalid_release_pin_stops_before_writing(repository, release_file):+ data = dict(RELEASE, publisher_ref="main")+ release_file.write_text(json.dumps(data))+ result = invoke(repository, release_file, "--no-input", "--mode", "save")+ assert result.exit_code != 0+ assert "immutable" in result.output+ assert not (repository / ".github/workflows/skill-checks.yml").exists()+++def test_symlink_parent_is_refused_without_writing_outside(repository, release_file, tmp_path):+ old = repository / ".github/workflows/existing.yml"+ old.unlink()+ old.parent.rmdir()+ outside = tmp_path / "outside"+ outside.mkdir()+ old.parent.symlink_to(outside, target_is_directory=True)+ result = invoke(repository, release_file, "--no-input", "--mode", "save")+ assert result.exit_code != 0+ assert "Symlink" in result.output+ assert list(outside.iterdir()) == []+++def test_dirty_repository_is_refused_before_pr_setup(repository, release_file):+ (repository / "unrelated.txt").write_text("Keep my changes")+ result = invoke(repository, release_file, "--no-input", "--mode", "pr")+ assert result.exit_code != 0+ assert "existing changes" in result.output+ assert (repository / "unrelated.txt").read_text() == "Keep my changes"+++def test_declined_apply_is_read_only(repository, release_file):+ result = invoke(repository, release_file, "--mode", "pr", input_text="\n\n\n\nn\n")+ assert result.exit_code == 0, result.output+ assert "Cancelled" in result.output+ assert not (repository / ".github/workflows/skill-checks.yml").exists()+++def test_existing_history_requires_this_repositorys_ownership_marker(monkeypatch):+ marker = {"purpose": "skillevaluator-reports", "repository": "example-org/another-repo"}+ import base64++ def api(method, endpoint, **kwargs):+ if endpoint.endswith("/git/ref/heads/gh-pages"):+ return {"ref": "refs/heads/gh-pages", "object": {"sha": "a" * 40}}+ if "/contents/.skillevaluator-report-site.json" in endpoint:+ return {"encoding": "base64", "content": base64.b64encode(json.dumps(marker).encode()).decode()}+ raise AssertionError("Unowned history must not be accessed or changed")++ monkeypatch.setattr(wizard, "github_api", api)+ with pytest.raises(wizard.SetupError, match="not owned"):+ wizard.history_preflight("example-org/this-repo")+++def test_environment_approval_requirements_are_never_removed(monkeypatch):+ def api(method, endpoint, *args, **kwargs):+ if method != "GET":+ raise AssertionError("Never remove an existing approval requirement")+ return {+ "name": "github-pages",+ "protection_rules": [+ {"type": "required_reviewers", "reviewers": [{"type": "User", "reviewer": {"login": "reviewer"}}]}+ ],+ "deployment_branch_policy": None,+ }++ monkeypatch.setattr(wizard, "github_api", api)+ with pytest.raises(wizard.SetupError, match="requires approval"):+ wizard.ensure_environment("example-org/test", "main")+++def test_setup_status_detects_a_changed_scan_without_approving_it(repository, release_file, monkeypatch):+ import base64++ result = invoke(repository, release_file, "--no-input", "--mode", "save")+ assert result.exit_code == 0, result.output++ def api(method, endpoint, *args, **kwargs):+ if endpoint == "repos/example-org/consumer":+ return {"default_branch": "trunk"}+ if endpoint.endswith("/pages"):+ return {"html_url": "https://example-org.github.io/prototype-unit-only/", "build_type": "workflow"}+ for path in [wizard.SCAN, wizard.PUBLISH]:+ if f"/contents/{path}" in endpoint:+ content = (repository / path).read_bytes()+ if path == wizard.SCAN:+ content += b"# A later edit, not approved by the publisher\n"+ return {"encoding": "base64", "content": base64.b64encode(content).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 "Needs refresh" in result.output+++def test_pages_is_enabled_before_history_push_can_auto_enable_legacy_pages(monkeypatch, tmp_path):+ state = {"actions": {"enabled": True}, "pages": None, "history_exists": False}+ provider = {"build_type": None, "history_initialized": False}++ def api(method, endpoint, payload=None, **kwargs):+ if method == "POST" and endpoint.endswith("/pages"):+ provider["build_type"] = payload["build_type"]+ return {"build_type": provider["build_type"]}+ if method == "GET" and endpoint.endswith("/pages"):+ return {+ "build_type": provider["build_type"],+ "html_url": "https://example-org.github.io/test/",+ "cname": None,+ }+ raise AssertionError((method, endpoint))++ def history(repo, name):+ assert provider["build_type"] == "workflow", "Creating gh-pages first can auto-enable legacy Pages"+ provider["history_initialized"] = True++ monkeypatch.setattr(wizard, "github_api", api)+ monkeypatch.setattr(wizard, "initialize_history", history)+ monkeypatch.setattr(wizard, "ensure_environment", lambda *_args: None)+ wizard.enable_hosting(tmp_path, "example-org/test", "main", state, [])+ assert provider == {"build_type": "workflow", "history_initialized": True}+++def test_owned_legacy_pages_setup_can_resume_without_resetting_history(monkeypatch, tmp_path):+ provider = {"build_type": "legacy", "history": [{"run_id": "123"}]}+ state = {"actions": {"enabled": True}, "pages": {"build_type": "legacy", "cname": None}, "history_exists": True}++ def api(method, endpoint, payload=None, **kwargs):+ if method == "PUT" and endpoint.endswith("/pages"):+ provider["build_type"] = payload["build_type"]+ return {}+ if method == "GET" and endpoint.endswith("/pages"):+ return {+ "build_type": provider["build_type"],+ "html_url": "https://example-org.github.io/test/",+ "cname": None,+ }+ raise AssertionError((method, endpoint))++ def no_reset(*args):+ raise AssertionError("Existing history must not be recreated")++ monkeypatch.setattr(wizard, "github_api", api)+ monkeypatch.setattr(wizard, "initialize_history", no_reset)+ monkeypatch.setattr(wizard, "ensure_environment", lambda *_args: None)+ wizard.enable_hosting(tmp_path, "example-org/test", "main", state, [])+ assert provider == {"build_type": "workflow", "history": [{"run_id": "123"}]}+++def test_demo_requires_merged_setup_before_pushing(repository, monkeypatch):+ def api(method, endpoint, *args, **kwargs):+ if endpoint == "repos/example-org/consumer":+ return {"default_branch": "trunk", "permissions": {"admin": True}, "archived": False}+ if "/contents/" in endpoint:+ return None+ raise AssertionError("Demo must stop before any remote mutation")++ monkeypatch.setattr(wizard, "github_api", api)+ result = CliRunner().invoke(cli, ["ci", "demo", "--repo", str(repository), "--no-input"])+ assert result.exit_code != 0+ assert "Merge the setup PR" in result.output+ assert not (repository / ".github/workflows/skill-checks.yml").exists()+++def _remote_state(monkeypatch, info, *, actions=None, pages=None):+ calls = []+ git_calls = []++ def api(method, endpoint, payload=None, **kwargs):+ calls.append((method, endpoint, payload))+ assert method == "GET", "Preflight must not change remote settings"+ if endpoint.endswith("/actions/permissions"):+ return actions or {"enabled": True, "allowed_actions": "all"}+ if endpoint.endswith("/pages"):+ return pages+ return info++ def git(repo, *args, **kwargs):+ git_calls.append(args)+ if args[0] == "rev-parse":+ return "a" * 40+ return ""++ monkeypatch.setattr(wizard, "github_api", api)+ monkeypatch.setattr(wizard.git_helpers, "git", git)+ monkeypatch.setattr(wizard, "history_preflight", lambda _name: False)+ return calls, git_calls++[email protected]("owner", ["example-org", "another-user", "EnterpriseTeam"])+def test_automatic_setup_supports_any_github_owner(repository, monkeypatch, owner):+ info = {"default_branch": "trunk", "permissions": {"admin": True}, "private": False, "visibility": "public"}+ calls, _ = _remote_state(monkeypatch, info)+ state = wizard.remote_preflight(repository, f"{owner}/skills", "trunk", True)+ assert state["info"] == info+ assert calls[0][1] == f"repos/{owner}/skills"++[email protected]("visibility", ["private", "internal"])+def test_private_checks_only_does_not_access_pages(repository, monkeypatch, visibility):+ info = {"default_branch": "trunk", "permissions": {"admin": True}, "private": True, "visibility": visibility}+ calls, _ = _remote_state(monkeypatch, info)+ state = wizard.remote_preflight(repository, "example-org/private-skills", "trunk", False)+ assert state["pages"] is None+ assert all(not endpoint.endswith("/pages") for _, endpoint, _ in calls)+++ "private,visibility", [(True, "private"), (True, "internal"), (False, "internal"), (None, "public")]+)+def test_nonpublic_hosting_stops_before_fetch_or_settings(repository, monkeypatch, private, visibility):+ info = {"default_branch": "trunk", "permissions": {"admin": True}, "private": private, "visibility": visibility}+ calls, git_calls = _remote_state(monkeypatch, info)+ with pytest.raises(wizard.SetupError, match="--checks-only"):+ wizard.remote_preflight(repository, "example-org/private-skills", "trunk", True)+ assert len(calls) == 1+ assert all(args[0] == "status" for args in git_calls)++[email protected]("archived,permissions", [(True, {"admin": True}), (False, {"push": True}), (False, {})])+def test_remote_setup_requires_active_repo_and_admin(repository, monkeypatch, archived, permissions):+ info = {"default_branch": "trunk", "permissions": permissions, "private": False, "archived": archived}+ calls, git_calls = _remote_state(monkeypatch, info)+ with pytest.raises(wizard.SetupError, match="admin access"):+ wizard.remote_preflight(repository, "example-org/skills", "trunk", False)+ assert len(calls) == 1+ assert all(args[0] == "status" for args in git_calls)+++def test_restricted_actions_are_preserved_and_point_to_manual_setup(repository, monkeypatch):+ info = {"default_branch": "trunk", "permissions": {"admin": True}, "private": False}+ calls, _ = _remote_state(monkeypatch, info, actions={"enabled": True, "allowed_actions": "selected"})+ with pytest.raises(wizard.SetupError, match="--mode save"):+ wizard.remote_preflight(repository, "example-org/skills", "trunk", True)+ assert all(method == "GET" for method, _, _ in calls)+++def test_existing_unowned_pages_site_is_not_replaced(repository, monkeypatch):+ info = {"default_branch": "trunk", "permissions": {"admin": True}, "private": False}+ calls, _ = _remote_state(monkeypatch, info, pages={"build_type": "workflow", "cname": None})+ with pytest.raises(wizard.SetupError, match="will not be replaced"):+ wizard.remote_preflight(repository, "example-org/skills", "trunk", True)+ assert all(method == "GET" for method, _, _ in calls)+++def test_default_selection_is_not_specific_to_a_demo_folder():+ roots = [{"root": "sandbox-skills", "count": 2, "default": True}, {"root": "skills", "count": 3, "default": True}]+ assert wizard.select_roots(roots, (), True) == ["sandbox-skills", "skills"]++[email protected]("content", [b"not a workflow", b"jobs: [", b"jobs: {}", b"jobs: {skills: {with: 3}}"])+def test_malformed_existing_workflow_has_actionable_error(content):+ import base64++ value = {"encoding": "base64", "content": base64.b64encode(content).decode()}+ with pytest.raises(wizard.SetupError, match="workflow"):+ wizard.workflow_inputs(value, "skills")+++def test_bundled_release_and_ci_namespace_are_available():+ from importlib.resources import files++ release = wizard.load_release(files("skillevaluator").joinpath("ci-release.json"))+ assert release["repository"] == "NVIDIA/SkillEvaluator"+ assert release["schema_version"] == 1+ assert "ci" in cli.commands+ for command in ["init", "status", "demo"]:+ result = CliRunner().invoke(cli, ["ci", command, "--help"])+ assert result.exit_code == 0, result.output+++def test_default_branch_mismatch_stops_before_fetch(repository, monkeypatch):+ info = {"default_branch": "main", "permissions": {"admin": True}, "private": False}+ calls, git_calls = _remote_state(monkeypatch, info)+ with pytest.raises(wizard.SetupError, match="--default-branch"):+ wizard.remote_preflight(repository, "example-org/skills", "trunk", True)+ assert len(calls) == 1+ assert all(args[0] == "status" for args in git_calls)++[email protected]("console_script", [True, False])+def test_windows_followup_quotes_powershell_paths(monkeypatch, tmp_path, console_script):+ install = tmp_path / "User's Python"+ install.mkdir()+ python = install / "python.exe"+ if console_script:+ (install / "skillevaluator.exe").touch()+ monkeypatch.setattr(wizard.sys, "platform", "win32")+ monkeypatch.setattr(wizard.sys, "executable", str(python))+ command = wizard.cli_command(tmp_path / "consumer", "ci", "demo")+ assert command.startswith("& '")+ assert "User''s Python" in command+ assert command.endswith("'ci' 'demo'")+ assert ("skillevaluator.exe" in command) == console_script+ assert ("'-m' 'skillevaluator.cli'" in command) != console_script++[email protected]("full", [True, False])+def test_missing_git_identity_stops_before_github_settings(repository, monkeypatch, full):+ def no_identity(_repo):+ raise wizard.SetupError("Set your Git commit identity")++ def unexpected_remote(*args, **kwargs):+ raise AssertionError("Missing identity must be checked before GitHub changes")++ monkeypatch.setattr(wizard.git_helpers, "require_identity", no_identity)+ monkeypatch.setattr(wizard, "remote_preflight", unexpected_remote)+ with pytest.raises(wizard.SetupError, match="Git commit identity"):+ wizard.create_setup(repository, "example-org/consumer", "trunk", {}, full, {})+++def test_pages_protected_branch_endpoint_escapes_special_characters(monkeypatch):+ calls = []++ def api(method, endpoint, *args, **kwargs):+ calls.append((method, endpoint))+ if endpoint.endswith("/environments/github-pages"):+ return {"deployment_branch_policy": {"protected_branches": True}, "protection_rules": []}+ return {"protected": True}++ monkeypatch.setattr(wizard, "github_api", api)+ wizard.ensure_environment("example-org/consumer", "release/2026#11&stable")+ assert calls[-1] == ("GET", "repos/example-org/consumer/branches/release%2F2026%2311%26stable")+ assert all(method == "GET" for method, _ in calls)diff --git a/tests/test_ci_onboarding_git.py b/tests/test_ci_onboarding_git.pynew file mode 100644index 00000000..3d5e4cbc--- /dev/null+++ b/tests/test_ci_onboarding_git.py@@ -0,0 +1,122 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++"""Real repository discovery and path-boundary checks."""++import subprocess++import pytest++from skillevaluator import _ci_onboarding_git as git_helpers+from test_ci_onboarding import repository as repository # noqa: PLC0414 -- export shared pytest fixture+++def raw_git(repo, *args):+ return subprocess.check_output(+ ["git", "-c", "core.hooksPath=/dev/null", "-c", "commit.gpgsign=false", "-C", str(repo), *args], text=True+ )+++ "value",+ [+ "https://other.example/example-org/demo.git",+ "https://[email protected]/example-org/demo.git",+ "https://github.com:443/example-org/demo.git",+ "https://github.com/example-org/demo?token=secret",+ "[email protected]:../demo.git",+ "file:///tmp/repository",+ ],+)+def test_remote_rejects_non_github_or_credential_bearing_inputs(value):+ with pytest.raises(git_helpers.SetupError):+ git_helpers.parse_remote(value)++[email protected]("value", ["../skills", "/tmp/skills", "skills/../x", "skills\\x", "a\nb", "a//b", ""])+def test_paths_reject_unsafe_inputs(value):+ with pytest.raises(git_helpers.SetupError):+ git_helpers.safe_relative(value)+++def test_both_supported_remote_forms():+ assert git_helpers.parse_remote("[email protected]:example-org/demo.git") == "example-org/demo"+ assert git_helpers.parse_remote("https://github.com/example-org/demo") == "example-org/demo"+++def test_discovery_groups_hidden_roots_excludes_fixtures_and_untracked(repository):+ new = repository / "untracked/new/SKILL.md"+ new.parent.mkdir(parents=True)+ new.write_text("not committed")+ assert git_helpers.discover(repository) == [+ {"root": ".agents/skills", "count": 1, "default": True},+ {"root": "skills", "count": 2, "default": True},+ {"root": "tests/fixtures", "count": 1, "default": False},+ ]+++def test_tracked_symlink_manifest_is_rejected(repository, tmp_path):+ outside = tmp_path / "outside.md"+ outside.write_text("source outside repository")+ link = repository / "skills/a/SKILL.md"+ link.unlink()+ link.symlink_to(outside)+ with pytest.raises(git_helpers.SetupError, match="Symlink"):+ git_helpers.discover(repository)++[email protected]("operation", ["fetch", "push", "ls-remote"])+def test_network_git_uses_existing_gh_login_without_global_config(monkeypatch, tmp_path, operation):+ captured = {}+ monkeypatch.setenv("GH_HOST", "github.example.internal")+ monkeypatch.setenv("GH_REPO", "unrelated/repository")++ def run(args, **kwargs):+ captured["args"] = args+ captured["env"] = kwargs["env"]+ return subprocess.CompletedProcess(args, 0, stdout="ok\n", stderr="")++ monkeypatch.setattr(git_helpers.subprocess, "run", run)+ name = git_helpers.parse_remote("[email protected]:example-org/skills.git")+ assert git_helpers.git(tmp_path, operation, f"https://github.com/{name}.git", network=True) == "ok\n"+ args = captured["args"]+ assert "credential.helper=" in args+ assert "credential.https://github.com.helper=!gh auth git-credential" in args+ assert "--global" not in args+ assert captured["env"]["GH_HOST"] == "github.com"+ assert "GH_REPO" not in captured["env"]+++def test_local_git_operations_do_not_enable_network_or_credentials(monkeypatch, tmp_path):+ captured = []++ def run(args, **kwargs):+ captured.extend(args)+ return ""++ monkeypatch.setattr(git_helpers, "run", run)+ git_helpers.git(tmp_path, "status", "--porcelain=v1")+ assert "protocol.allow=never" in captured+ assert not any("credential" in value for value in captured)++[email protected]("missing_key", ["user.name", "user.email"])+def test_identity_preflight_has_local_configuration_guidance(monkeypatch, tmp_path, missing_key):+ def git(_repo, *args):+ if args == ("config", "--get", missing_key):+ raise git_helpers.SetupError("missing")+ return "set"++ monkeypatch.setattr(git_helpers, "git", git)+ with pytest.raises(git_helpers.SetupError, match=r"git config user\.name"):+ git_helpers.require_identity(tmp_path)+++def test_push_error_suggests_workflow_permission_without_exposing_stderr(monkeypatch, tmp_path):+ def run(*args, **kwargs):+ return subprocess.CompletedProcess(args, 1, stdout="", stderr="secret-credential")++ monkeypatch.setattr(git_helpers.subprocess, "run", run)+ with pytest.raises(git_helpers.SetupError, match="gh auth refresh") as error:+ git_helpers.git(tmp_path, "push", "https://github.com/example-org/consumer.git", network=True)+ assert "secret-credential" not in str(error.value)diff --git a/tests/test_cli.py b/tests/test_cli.pyindex 167d586a..bfcac5e2 100644--- a/tests/test_cli.py+++ b/tests/test_cli.py@@ -83,6 +83,7 @@ def test_top_level_help_groups_commands_by_workflow() -> None:headings = ("Tier workflows:","Core workflows:",+ "Repository CI:","Tier 1 · Static and security:","Tier 2 · Deduplication:","Tier 3 · Live evaluation:",@@ -90,8 +91,10 @@ def test_top_level_help_groups_commands_by_workflow() -> None:positions = [result.output.index(heading) for heading in headings]assert positions == sorted(positions)- core = result.output.split("Core workflows:", 1)[1].split("Tier 1 · Static and security:", 1)[0]+ core = result.output.split("Core workflows:", 1)[1].split("Repository CI:", 1)[0]assert all(command in core for command in ("validate", "health-check", "doctor", "models", "dashboard"))+ repository_ci = result.output.split("Repository CI:", 1)[1].split("Tier 1 · Static and security:", 1)[0]+ assert any(line.split() and line.split()[0] == "ci" for line in repository_ci.splitlines())tier3 = result.output.split("Tier 3 · Live evaluation:", 1)[1]assert all(command in tier3 for command in ("create-eval-dataset", "compare", "view", "harbor-view"))assert "Other commands:" not in result.outputdiff --git a/tests/tier3/test_local_runtime_install.py b/tests/tier3/test_local_runtime_install.pyindex cbe20662..2270605a 100644--- a/tests/tier3/test_local_runtime_install.py+++ b/tests/tier3/test_local_runtime_install.py@@ -26,6 +26,8 @@ def test_install_without_npm(monkeypatch, tmp_path):def _fake_npm(monkeypatch, returncode, create_bin):calls = []+ # A simulated install must not discover the developer's real agent on PATH.+ monkeypatch.setenv("PATH", "")def run(argv, **_kwargs):calls.append(argv)diff --git a/uv.lock b/uv.lockindex 52367f08..39ed4d76 100644--- a/uv.lock+++ b/uv.lock@@ -2556,7 +2556,7 @@ wheels = [[[package]]name = "skillevaluator"-version = "0.7.0"+version = "0.7.1"source = { editable = "." }dependencies = [{ name = "click" },