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
ci: cover every workflow with the hardening guards, and fix the gaps they surface (#126)
berzan93-progaaeb3d481239
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex ce8abbc1..1038f702 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -80,27 +80,22 @@ jobs:--cov-report=term-missing--cov-report=xml:coverage.xml- name: Set up Node.js for docs- if: ${{ needs.classify-changes.outputs.docs_only == 'true' }}uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0with:node-version: "22"- name: Validate Fern documentation- if: ${{ needs.classify-changes.outputs.docs_only == 'true' }}shell: bashrun: |set -euo pipefail- FERN_VERSION="$(node -p "require('./fern/fern.config.json').version")"- if [[ ! "$FERN_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then- echo "::error file=fern/fern.config.json::Invalid Fern CLI version: $FERN_VERSION"- exit 1- fi- npm install --global "fern-api@$FERN_VERSION"- fern check+ # npm ci reproduces fern/package-lock.json exactly. tests/test_ci_workflows.py+ # asserts fern/package.json and fern/fern.config.json name the same version.+ npm ci --prefix fern --ignore-scripts --omit=optional+ FERN_VERSION="$(node -p "require('./fern/package.json').dependencies['fern-api']")"+ ./fern/node_modules/.bin/fern check{- echo "### Documentation-only CI"+ echo "### Fern documentation validation"echoecho "Validated docs and Fern configuration with Fern CLI $FERN_VERSION."- echo "The platform test matrix was skipped because only docs/** and fern/** changed."} >> "$GITHUB_STEP_SUMMARY"test-python-313:diff --git a/.github/workflows/publish-docs.yml b/.github/workflows/publish-docs.ymlindex a1ead4c1..43a1d7c0 100644--- a/.github/workflows/publish-docs.yml+++ b/.github/workflows/publish-docs.yml@@ -18,18 +18,18 @@ jobs:with:persist-credentials: false- - name: Install Fern- shell: bash- run: |- set -euo pipefail- FERN_VERSION="$(node -p "require('./fern/fern.config.json').version")"- if [[ ! "$FERN_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then- echo "::error file=fern/fern.config.json::Invalid Fern CLI version: $FERN_VERSION"- exit 1- fi- npm install --global "fern-api@$FERN_VERSION"+ - name: Set up Node.js+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0+ with:+ node-version: "22"++ # npm ci reproduces fern/package-lock.json exactly -- every version and+ # integrity hash -- so nothing resolved at run time reaches the step below,+ # which holds FERN_TOKEN.+ - name: Install the pinned Fern CLI+ run: npm ci --prefix fern --ignore-scripts --omit=optional- name: Publish Docsenv:FERN_TOKEN: ${{ secrets.FERN_TOKEN }}- run: fern generate --docs+ run: ./fern/node_modules/.bin/fern generate --docsdiff --git a/.gitignore b/.gitignoreindex a8d5f768..f1a4c74d 100644--- a/.gitignore+++ b/.gitignore@@ -60,3 +60,6 @@ src/skillevaluator/tier3/reference_skills/*/evals/results/skillevaluator-output*skillevaluator-quality*skillevaluator-rubric-eval*++# Node modules for the pinned Fern documentation CLI (see fern/package.json)+node_modules/diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 559a9a9f..3b357dbc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -734,6 +734,49 @@ All notable changes to SkillEvaluator are documented in this file.observations explicit, and reports unsupported or malformed JavaScript asuntrusted instead of a clean security result.+### Security++- The docs-publishing workflow, the only one that passes a secret to a step,+ now pins `actions/checkout` to a commit SHA, declares+ `permissions: contents: read`, and sets `persist-credentials: false`.+ `dco.yml` no longer persists checkout credentials either.+- Docs are now published with the same Fern CLI version they are validated+ with. Both workflows install the CLI from `fern/package.json` and its+ committed lockfile; a test checks that the pin matches `fern/fern.config.json`.+- Workflow hardening guards now glob `.github/workflows/` instead of a+ hardcoded two-file list, so every workflow — including any added later — must+ pin each action to a commit, avoid persisting checkout credentials, and+ declare a `permissions:` block. The guards also cover job-level+ `permissions:` overrides and job-level reusable-workflow `uses:` references,+ neither of which the step-level checks reached.+- The Fern CLI is now installed from a committed lockfile, `fern/package-lock.json`,+ with `npm ci --prefix fern --ignore-scripts --omit=optional`, and both workflows+ invoke `./fern/node_modules/.bin/fern` rather than a binary on `PATH`. Previously+ `publish-docs.yml` ran `npm install`, which re-resolves every transitive+ dependency from semver ranges on each run: pinning `fern-api`'s own version+ pinned nothing beneath it. `@scarf/scarf` — reached through `fern-api`'s+ optional dependency on `@boundaryml/baml` — declares a `postinstall` script.+ The install step did not receive `FERN_TOKEN`, but its resulting CLI was later+ run in the token-bearing publish step. The lockfile pins every package to an+ exact version and integrity hash, `--ignore-scripts` stops lifecycle code+ running, and `--omit=optional` (which npm honours for this local install, but+ silently ignores for a `--global` one) leaves `fern-api` alone in the tree.+ Guards now permit only the reviewed lockfile install command in workflows,+ check the Fern manifest and lockfile dependency inputs, and require+ `fern/package.json`, `fern/package-lock.json`, and `fern/fern.config.json` to+ name the same CLI version. Fern dependency and config changes run the full+ CI lane, including dependency review, while `fern check` runs in both lanes.+ The developer-facing install instructions+ (`docs/README.md`, `docs/AGENTS.md`, `docs/developer-guide.mdx`) use the same+ lockfile install, so a contributor or agent following them gets the tree CI runs.+- The action-pinning guard now accepts a same-repo composite action or+ reusable workflow (`uses: ./...`) without requiring a commit SHA, since+ GitHub always resolves a local reference from the caller's own commit and+ nothing about it can float. A local reference that escapes the repository+ (e.g. `./../outside`) or carries an `@ref` (a syntax local references don't+ have) is still rejected, and a `docker://` reference is unaffected by the+ exemption.+## 0.2.1 - 2026-08-24### Addeddiff --git a/docs/AGENTS.md b/docs/AGENTS.mdindex a771c731..e79d3630 100644--- a/docs/AGENTS.md+++ b/docs/AGENTS.md@@ -75,11 +75,12 @@ Navigation order, page titles, and slugs are defined in## Verify before committing-Requires **Node.js 22+** and the Fern CLI (`npm install -g fern-api`).+Requires **Node.js 22+**. Install the pinned CLI from the committed lockfile with+`npm ci --prefix fern --ignore-scripts --omit=optional`.```bash-fern check # validate docs.yml config and all links — must pass-fern docs dev # optional live preview at http://localhost:3000+./fern/node_modules/.bin/fern check # validate docs.yml config and all links — must pass+./fern/node_modules/.bin/fern docs dev # optional live preview at http://localhost:3000````fern check` must pass; it is the same gate the site build relies on. Publishingdiff --git a/docs/README.md b/docs/README.mdindex 3482c500..34690a8a 100644--- a/docs/README.md+++ b/docs/README.md@@ -38,14 +38,14 @@ published automatically from `main` via the Fern GitHub integration.Prerequisites: Node.js 22+ and npm 10+ (the versions the Fern CLI requires).```bash-# Install the Fern CLI-npm install -g fern-api+# Install the pinned Fern CLI from the committed lockfile+npm ci --prefix fern --ignore-scripts --omit=optional# From the repo root, preview the site with live reload-fern docs dev+./fern/node_modules/.bin/fern docs dev# Validate the docs configuration and links-fern check+./fern/node_modules/.bin/fern check````fern docs dev` serves the site at <http://localhost:3000> and reloads on changesdiff --git a/docs/developer-guide.mdx b/docs/developer-guide.mdxindex f496a3f2..b276d05a 100644--- a/docs/developer-guide.mdx+++ b/docs/developer-guide.mdx@@ -83,16 +83,18 @@ The documentation site is built with [Fern](https://buildwithfern.com/) from the<Steps>### Install the Fern CLI- Requires Node.js 22+ and npm 10+.+ Requires Node.js 22+ and npm 10+. `fern/package-lock.json` pins the CLI and every package+ below it; `npm ci` reproduces that tree exactly, and the flags keep npm from running any+ install-time scripts. This is the same install CI performs.- ```bash title="Install fern-api"- npm install -g fern-api+ ```bash title="Install the pinned fern-api"+ npm ci --prefix fern --ignore-scripts --omit=optional```### Preview with live reload```bash title="Local docs preview"- fern docs dev+ ./fern/node_modules/.bin/fern docs dev```The site serves at `http://localhost:3000` and reloads on changes to `.mdx` files or `fern/docs.yml`.@@ -100,7 +102,7 @@ The documentation site is built with [Fern](https://buildwithfern.com/) from the### Validate before pushing```bash title="Check config and links"- fern check+ ./fern/node_modules/.bin/fern check````fern check` must pass — it is the same gate the site build relies on.diff --git a/fern/fern.config.json b/fern/fern.config.jsonindex 459af742..a9125ad4 100644--- a/fern/fern.config.json+++ b/fern/fern.config.json@@ -1,4 +1,4 @@{"organization": "nvidia",- "version": "5.66.1"+ "version": "5.121.0"}diff --git a/fern/package-lock.json b/fern/package-lock.jsonnew file mode 100644index 00000000..db58aa76--- /dev/null+++ b/fern/package-lock.json@@ -0,0 +1,190 @@+{+ "name": "skillevaluator-docs",+ "version": "0.0.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "skillevaluator-docs",+ "version": "0.0.0",+ "license": "Apache-2.0",+ "dependencies": {+ "fern-api": "5.121.0"+ }+ },+ "node_modules/@boundaryml/baml": {+ "version": "0.219.0",+ "resolved": "https://registry.npmjs.org/@boundaryml/baml/-/baml-0.219.0.tgz",+ "integrity": "sha512-hE6t6G/1Td9yYN/T6E13igF06ZHD0J9dr5FH3tjCCZQplqTLBiVn4wyVoboK7ypjdHdGkg6O0vAcXrcbdwM6pA==",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@scarf/scarf": "^1.3.0"+ },+ "bin": {+ "baml": "cli.js",+ "baml-cli": "cli.js"+ },+ "engines": {+ "node": ">= 10"+ },+ "optionalDependencies": {+ "@boundaryml/baml-darwin-arm64": "0.219.0",+ "@boundaryml/baml-darwin-x64": "0.219.0",+ "@boundaryml/baml-linux-arm64-gnu": "0.219.0",+ "@boundaryml/baml-linux-arm64-musl": "0.219.0",+ "@boundaryml/baml-linux-x64-gnu": "0.219.0",+ "@boundaryml/baml-linux-x64-musl": "0.219.0",+ "@boundaryml/baml-win32-arm64-msvc": "0.219.0",+ "@boundaryml/baml-win32-x64-msvc": "0.219.0"+ }+ },+ "node_modules/@boundaryml/baml-darwin-arm64": {+ "version": "0.219.0",+ "resolved": "https://registry.npmjs.org/@boundaryml/baml-darwin-arm64/-/baml-darwin-arm64-0.219.0.tgz",+ "integrity": "sha512-jhPN83UM+9Y99aCbzIS/3OpC7N8dOukPZO2piueIbzsmpaJrzTW+srKxYtVDE26Q9riFypOmizSs5SBFst04Fw==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@boundaryml/baml-darwin-x64": {+ "version": "0.219.0",+ "resolved": "https://registry.npmjs.org/@boundaryml/baml-darwin-x64/-/baml-darwin-x64-0.219.0.tgz",+ "integrity": "sha512-t7pnbVT3KEE3+stOrW7nATdipCWK8OK1gTV8qiD4pN8lZwGMtJpzrVvgWeycroWCaeJ8tNsQA/V2FyFU9pqjkg==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@boundaryml/baml-linux-arm64-gnu": {+ "version": "0.219.0",+ "resolved": "https://registry.npmjs.org/@boundaryml/baml-linux-arm64-gnu/-/baml-linux-arm64-gnu-0.219.0.tgz",+ "integrity": "sha512-a3ikRhlOdX+Lb08TaZU4k1Qb55mAHMuwArxpM1No/ltc0ylvo9EbJ4Nv0ZKemEHdngM6udagwdDxohpNzR1QTg==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@boundaryml/baml-linux-arm64-musl": {+ "version": "0.219.0",+ "resolved": "https://registry.npmjs.org/@boundaryml/baml-linux-arm64-musl/-/baml-linux-arm64-musl-0.219.0.tgz",+ "integrity": "sha512-KjwJL5aXf4XvwpX3RwMau19XcHDcffhbiTX+tk41kGC4LZl7UXB4FgnOBtSOMvWtHj2f4cIN81+yCZBRsMxdNg==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@boundaryml/baml-linux-x64-gnu": {+ "version": "0.219.0",+ "resolved": "https://registry.npmjs.org/@boundaryml/baml-linux-x64-gnu/-/baml-linux-x64-gnu-0.219.0.tgz",+ "integrity": "sha512-JWMhzx1LDfCPwDbOUQbFaPgNb7TUvLCb4+1TjRAJR+Z2Nl08RqNWUUfFctMEzsN6HrcHVOZ0xSl/hJRxN8OcTA==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@boundaryml/baml-linux-x64-musl": {+ "version": "0.219.0",+ "resolved": "https://registry.npmjs.org/@boundaryml/baml-linux-x64-musl/-/baml-linux-x64-musl-0.219.0.tgz",+ "integrity": "sha512-lPosn6eJqI+8EjMI71AUEb3B9uk4dUfQgerbDyu6FvNMWx+HZDPB4UWl66+OlEeMA2Gb6DUp3LLE/Jl9/KDKSg==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@boundaryml/baml-win32-arm64-msvc": {+ "version": "0.219.0",+ "resolved": "https://registry.npmjs.org/@boundaryml/baml-win32-arm64-msvc/-/baml-win32-arm64-msvc-0.219.0.tgz",+ "integrity": "sha512-djy9pn8s1Ogr3ovTDxDcOiM1YOhkBwNsBnlZDQzrIdR/LgSh/GGmrwW5Ks3gfa2NvvNOIFPccdUp0nDZZNsjfQ==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@boundaryml/baml-win32-x64-msvc": {+ "version": "0.219.0",+ "resolved": "https://registry.npmjs.org/@boundaryml/baml-win32-x64-msvc/-/baml-win32-x64-msvc-0.219.0.tgz",+ "integrity": "sha512-BJkgq/qyn3BcBZt3iyfYWirZyZrKiqa1J0OTWd45P8OQ8dJhRnU6JGcpXPTXNmkryXQFY+O4HA+lQBKA5SZ7kg==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@scarf/scarf": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/@scarf/scarf/-/scarf-1.4.0.tgz",+ "integrity": "sha512-xxeapPiUXdZAE3che6f3xogoJPeZgig6omHEy1rIY5WVsB3H2BHNnZH+gHG6x91SCWyQCzWGsuL2Hh3ClO5/qQ==",+ "hasInstallScript": true,+ "license": "Apache-2.0",+ "optional": true+ },+ "node_modules/fern-api": {+ "version": "5.121.0",+ "resolved": "https://registry.npmjs.org/fern-api/-/fern-api-5.121.0.tgz",+ "integrity": "sha512-fFI3qWmH9jvEx0bXwJGaIsB+gSnl/OUVnlOIUEGf8r+3CF+WSjPVtZR/DgJ7WIfSBU7KeNyitScWTCyf/xbrBA==",+ "bin": {+ "fern": "cli.cjs"+ },+ "optionalDependencies": {+ "@boundaryml/baml": "^0.219.0"+ }+ }+ }+}diff --git a/fern/package.json b/fern/package.jsonnew file mode 100644index 00000000..f7f183c1--- /dev/null+++ b/fern/package.json@@ -0,0 +1,10 @@+{+ "name": "skillevaluator-docs",+ "version": "0.0.0",+ "private": true,+ "description": "Pins the Fern CLI that validates and publishes the documentation site. Keep the fern-api version in step with fern.config.json; tests/test_ci_workflows.py asserts they agree.",+ "license": "Apache-2.0",+ "dependencies": {+ "fern-api": "5.121.0"+ }+}diff --git a/scripts/classify_ci_changes.py b/scripts/classify_ci_changes.pyindex aadb1f4b..0897af59 100644--- a/scripts/classify_ci_changes.py+++ b/scripts/classify_ci_changes.py@@ -14,13 +14,14 @@ import sysfrom collections.abc import Sequencefrom pathlib import Path-DOC_PREFIXES = (b"docs/", b"fern/")+DOC_PREFIXES = (b"docs/",)+DOC_FILES = frozenset({b"fern/docs.yml"})KNOWN_STATUSES = frozenset(b"ACDMRTUXB")def is_docs_only(paths: Sequence[bytes]) -> bool:"""Return whether every changed path belongs to published documentation."""- return bool(paths) and all(path.startswith(DOC_PREFIXES) for path in paths)+ return bool(paths) and all(path.startswith(DOC_PREFIXES) or path in DOC_FILES for path in paths)def parse_name_status_z(payload: bytes) -> list[bytes]:diff --git a/tests/test_ci_change_classifier.py b/tests/test_ci_change_classifier.pyindex fa2ee383..0c085f14 100644--- a/tests/test_ci_change_classifier.py+++ b/tests/test_ci_change_classifier.py@@ -42,7 +42,11 @@ def git_repo(tmp_path: Path) -> tuple[Path, str]:("paths", "expected"),[([b"docs/index.mdx"], True),- ([b"fern/fern.config.json"], True),+ ([b"fern/fern.config.json"], False),+ ([b"fern/package.json"], False),+ ([b"fern/package-lock.json"], False),+ ([b"fern/new-config.yml"], False),+ ([b"docs/index.mdx", b"fern/package-lock.json"], False),([b"fern/docs.yml", b"docs/assets/logo.svg"], True),([b"docs"], False),([b"fern"], False),diff --git a/tests/test_ci_workflows.py b/tests/test_ci_workflows.pyindex 84673c07..5b610a97 100644--- a/tests/test_ci_workflows.py+++ b/tests/test_ci_workflows.py@@ -3,16 +3,22 @@from __future__ import annotations+import jsonimport re+import shlex+import sysimport tomllib+from collections.abc import Sequencefrom pathlib import Pathfrom typing import Any+import pytestimport yamlROOT = Path(__file__).resolve().parents[1]WORKFLOWS = ROOT / ".github" / "workflows"GITLEAKS_CONFIG = ROOT / ".gitleaks.toml"+REVIEWED_NPM_COMMAND = ["npm", "ci", "--prefix", "fern", "--ignore-scripts", "--omit=optional"]REQUIRED_CI_JOBS = {"test-python-312": "Tests (Python 3.12)",@@ -27,7 +33,6 @@ REQUIRED_CI_JOBS = {HEAVY_CI_JOBS = set(REQUIRED_CI_JOBS) - {"test-python-312"}RUN_UNLESS_CANCELLED_IF = "${{ !cancelled() }}"FULL_LANE_IF = "${{ !cancelled() && needs.classify-changes.outputs.docs_only != 'true' }}"-DOCS_ONLY_IF = "${{ needs.classify-changes.outputs.docs_only == 'true' }}"NOT_DOCS_ONLY_IF = "${{ needs.classify-changes.outputs.docs_only != 'true' }}"PR_CONCURRENCY = {"group": "${{ github.workflow }}-${{ github.event.pull_request.number || github.run_id }}",@@ -39,6 +44,13 @@ def _load(name: str) -> dict[str, Any]:return yaml.load((WORKFLOWS / name).read_text(encoding="utf-8"), Loader=yaml.BaseLoader)+def _workflow_names() -> list[str]:+ """Every workflow on disk, so a new one is covered the day it lands."""+ names = sorted(path.name for pattern in ("*.yml", "*.yaml") for path in WORKFLOWS.glob(pattern))+ assert names, "no workflows found"+ return names++def _assert_no_path_filter(workflow: dict[str, Any], event: str = "pull_request") -> None:trigger = workflow["on"][event]if isinstance(trigger, dict):@@ -51,15 +63,35 @@ def _runs(job: dict[str, Any]) -> str:def _all_uses(workflow: dict[str, Any]) -> list[str]:- return [step["uses"] for job in workflow["jobs"].values() for step in job.get("steps", []) if "uses" in step]+ """Every action reference: step-level actions and job-level reusable workflows."""+ step_uses = [step["uses"] for job in workflow["jobs"].values() for step in job.get("steps", []) if "uses" in step]+ job_uses = [job["uses"] for job in workflow["jobs"].values() if "uses" in job]+ return step_uses + job_usesdef _all_steps(workflow: dict[str, Any]) -> list[dict[str, Any]]:return [step for job in workflow["jobs"].values() for step in job.get("steps", [])]-def _workflow_names() -> list[str]:- return sorted(path.name for path in WORKFLOWS.glob("*.y*ml"))+def _action_repository(uses: str) -> str:+ """The ``owner/repo`` half of a ``uses:`` value, folded for comparison.++ GitHub resolves repository names case-insensitively, so ``Actions/Checkout``+ runs exactly the action ``actions/checkout`` names. A guard that filters on+ one literal spelling therefore skips a step that really does run -- which is+ a silent hole, not a cosmetic one.+ """+ return uses.split("@", 1)[0].casefold()+++def _is_checkout_step(step: dict[str, Any]) -> bool:+ """Whether ``step`` runs ``actions/checkout``, however GitHub spells it.++ An unpinned ``uses: actions/checkout`` counts too: the pin guard is what+ rejects that, and until it does the step still checks out a credentialed+ workspace.+ """+ return _action_repository(step.get("uses", "")) == "actions/checkout"def test_ci_preserves_required_contexts_as_explicit_jobs() -> None:@@ -92,7 +124,7 @@ def test_ci_classifier_is_pull_request_only_and_exports_docs_only() -> None:}-def test_ci_docs_lane_uses_the_required_python_312_context() -> None:+def test_ci_validates_fern_on_the_required_python_312_context() -> None:job = _load("ci.yml")["jobs"]["test-python-312"]assert job["needs"] == "classify-changes"@@ -114,13 +146,13 @@ def test_ci_docs_lane_uses_the_required_python_312_context() -> None:node_step = next(step for step in job["steps"] if step.get("name") == "Set up Node.js for docs")docs_step = next(step for step in job["steps"] if step.get("name") == "Validate Fern documentation")- assert node_step["if"] == DOCS_ONLY_IF+ assert "if" not in node_step, "Fern validation must run for mixed and Fern dependency PRs"assert len(node_step["uses"].split("@", 1)[1]) == 40- assert docs_step["if"] == DOCS_ONLY_IF- assert "fern/fern.config.json" in docs_step["run"]- assert 'npm install --global "fern-api@$FERN_VERSION"' in docs_step["run"]- assert "fern check" in docs_step["run"]+ assert "if" not in docs_step, "Fern validation must run for mixed and Fern dependency PRs"+ assert "npm ci --prefix fern --ignore-scripts --omit=optional" in docs_step["run"]+ assert "./fern/node_modules/.bin/fern check" in docs_step["run"]assert "GITHUB_STEP_SUMMARY" in docs_step["run"]+ assert "platform test matrix was skipped" not in docs_step["run"]def test_ci_skips_every_other_required_job_only_after_classification() -> None:@@ -216,9 +248,7 @@ def test_gitleaks_single_value_allowlists_are_exactly_scoped() -> None:def test_gitleaks_uses_event_specific_full_history_scopes() -> None:job = _load("security.yml")["jobs"]["gitleaks"]- checkout = next(- step for step in job["steps"] if step.get("uses", "").startswith("actions/checkout@")- )+ checkout = next(step for step in job["steps"] if _is_checkout_step(step))verify = next(step for step in job["steps"] if step.get("name") == "Verify full Git checkout")scan = next(step for step in job["steps"] if step.get("name") == "Scan Git history")@@ -264,25 +294,372 @@ def test_non_pr_workflow_triggers_are_preserved() -> None:assert "workflow_dispatch" in security["on"]-def test_all_workflows_pin_every_action_to_a_commit() -> None:+def _is_local_reference(uses: str) -> bool:+ """A same-repo composite action or reusable workflow, e.g. ``./.github/actions/x``.++ GitHub always resolves these from the caller's own commit, so nothing about+ them can float and there is no ``@ref`` syntax for one. A reference that is+ both ``./``-prefixed and carries an ``@`` is therefore not this syntax --+ treat it as a normal reference so it still has to satisfy the SHA-pin check.+ """+ return uses.startswith("./") and "@" not in uses+++def _local_reference_escapes_repo(uses: str) -> bool:+ return ".." in Path(uses).parts+++def test_every_workflow_pins_every_action_to_a_commit() -> None:for workflow_name in _workflow_names():for uses in _all_uses(_load(workflow_name)):- assert re.fullmatch(r"[^@]+@[0-9a-f]{40}", uses), uses+ if _is_local_reference(uses):+ assert not _local_reference_escapes_repo(uses), f"{workflow_name}: {uses}"+ continue+ assert re.fullmatch(r"[^@]+@[0-9a-f]{40}", uses), f"{workflow_name}: {uses}"+++def test_every_workflow_does_not_persist_checkout_credentials() -> None:+ checkout_steps = [+ (workflow_name, step)+ for workflow_name in _workflow_names()+ for step in _all_steps(_load(workflow_name))+ if _is_checkout_step(step)+ ]+ assert checkout_steps+ for workflow_name, step in checkout_steps:+ assert step.get("with", {}).get("persist-credentials") == "false", workflow_name+++def test_publish_docs_installs_the_fern_cli_from_the_committed_lockfile() -> None:+ """The secret-bearing job runs a CLI whose whole tree was reviewed, not resolved.++ ``npm ci`` reproduces ``fern/package-lock.json`` exactly -- every version and+ integrity hash -- so nothing between the commit and the run can change what+ executes next to ``FERN_TOKEN``.+ """+ job = _load("publish-docs.yml")["jobs"]["run"]+ install_commands = [argv for step in job["steps"] for argv in _npm_commands(step.get("run", ""))]+ assert install_commands == [REVIEWED_NPM_COMMAND], (+ "publish-docs.yml must install the pinned Fern CLI with the reviewed command"+ )+ publish_step = next(step for step in job["steps"] if "fern generate" in step.get("run", ""))+ assert "fern/node_modules/.bin/fern" in publish_step["run"], "run the installed CLI, not one from PATH"-def test_all_workflows_do_not_persist_checkout_credentials() -> None:- for workflow_name in _workflow_names():- checkout_steps = [- step for step in _all_steps(_load(workflow_name)) if step.get("uses", "").startswith("actions/checkout@")- ]- assert checkout_steps- assert all(step.get("with", {}).get("persist-credentials") == "false" for step in checkout_steps)+def test_every_workflow_declares_explicit_permissions() -> None:+ """A job-level permissions: block overrides the workflow-level one, so check both.-def test_all_workflows_declare_restricted_permissions() -> None:+ This rejects the write-all shorthand and the inherited-default token scope, not+ every broad grant -- a granular write like `contents: write` is a legitimate+ choice for a release workflow and is not this test's concern.+ """for workflow_name in _workflow_names():workflow = _load(workflow_name)- assert "permissions" in workflow- assert workflow["permissions"] != "write-all"- for job in workflow["jobs"].values():- assert job.get("permissions", {}) != "write-all"+ assert workflow.get("permissions") is not None, (+ f"{workflow_name} inherits the repository default token scope"+ )+ for scope, permissions in [("workflow", workflow["permissions"])] + [+ (f"job {job_id}", job["permissions"]) for job_id, job in workflow["jobs"].items() if "permissions" in job+ ]:+ assert permissions != "write-all", f"{workflow_name}: {scope}"+++# npm is not always the first word of a line: `cd fern && npm install`, `env npm+# install` and `npm --prefix fern install` are all real installs that a+# line-anchored pattern never sees. These guards therefore split each `run:`+# block into the commands a shell would run and inspect each one's argv -- and+# fail closed on any npm mention this parser cannot resolve to a plain+# invocation, because a guard that silently sees nothing is worse than one that+# is noisy.+#+# A mention is npm as a whole word, so `pnpm`, `npm-cache` and `--no-npm` stay+# quiet. Inside `${...}`, though, `-`, `=`, `+`, `?` and `/` are the parameter+# expansion operators that open a word the shell substitutes -- `${UNSET:-npm}+# install` runs npm -- so inside the braces they delimit npm too.+NPM_EXECUTABLE = re.compile(r"^(?:.*[/\\])?npm(?:\.cmd|\.exe|\.ps1)?$", re.IGNORECASE)+NPM_MENTION = re.compile(+ r"""(?:^|[\s'"`(;&|=]|\$\{[^}]*?[-=+?/])(?:[\w./\\-]*[/\\])?npm(?:\.cmd|\.exe|\.ps1)?(?=$|[\s'"`);&|}])""",+ re.IGNORECASE,+)+SHELL_ASSIGNMENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=")+SHELL_OPERATOR = re.compile(r"&&|\|\||[;&|()]")+SHELL_WRAPPERS = frozenset({"command", "env", "exec", "ionice", "nice", "setsid", "stdbuf", "sudo", "time"})+SHELL_KEYWORDS = frozenset({"!", "do", "elif", "else", "if", "then", "until", "while", "{"})+++def _logical_lines(run: str) -> list[str]:+ """``run`` split into lines, with backslash continuations joined back up."""+ return re.sub(r"\\\n", " ", run).splitlines()+++def _shell_segments(line: str) -> list[str]:+ """``line`` cut into command texts at every *unquoted* shell operator.++ Quoting is tracked by hand rather than left to ``shlex``'s lexer, because+ the lexer answers two questions wrongly for this job. It ends a word at any+ ``#``, so the URL in ``curl https://host/doc#install && npm install`` would+ swallow the install; and once a token is quoted it no longer says whether+ that token was an operator, so an argument like ``";"`` would cut the+ command in half. Both mistakes end with an npm command going unguarded,+ which is the failure this parser exists to prevent.+ """+ segments: list[str] = []+ current: list[str] = []+ quote = ""+ index = 0+ while index < len(line):+ char = line[index]+ if quote:+ current.append(char)+ quote = "" if char == quote else quote+ index += 1+ continue+ if char in "'\"":+ quote = char+ current.append(char)+ index += 1+ continue+ if char == "\\" and index + 1 < len(line):+ current.extend(line[index : index + 2])+ index += 2+ continue+ if char == "#" and (not current or current[-1].isspace() or current[-1] in "(;&|"):+ break # A word-initial # opens a comment: the rest of the line is not a command.+ operator = SHELL_OPERATOR.match(line, index)+ if operator:+ segments.append("".join(current))+ current = []+ index = operator.end()+ continue+ current.append(char)+ index += 1+ if quote:+ raise ValueError(f"unbalanced {quote} quote")+ segments.append("".join(current))+ return [segment for segment in segments if segment.strip()]+++def _shell_commands(line: str) -> list[list[str]]:+ """``line`` split into the separate commands a shell would run.++ Raises ``ValueError`` on a line no shell could read either, e.g. one+ holding an unbalanced quote; the callers decide what that means.+ """+ return [shlex.split(segment, comments=False) for segment in _shell_segments(line)]+++def _invoked_command(command: Sequence[str]) -> list[str]:+ """``command`` with what stands between the shell and the program removed.++ Environment assignments, wrappers such as ``env``, and the keywords that+ open a compound statement all sit in front of a command that really does+ run, so a guard that reads only the first word misses it.+ """+ argv = list(command)+ while argv and (+ SHELL_ASSIGNMENT.match(argv[0])+ or argv[0] in SHELL_WRAPPERS+ or argv[0] in SHELL_KEYWORDS+ or argv[0].startswith("-")+ ):+ argv = argv[1:]+ return argv+++def _npm_commands(run: str) -> list[list[str]]:+ """Every npm invocation in a ``run:`` block, as its argv tokens.++ Anything holding the word ``npm`` that does not come out of this as a plain+ npm invocation -- a line the lexer cannot read, an install hidden inside+ ``bash -c "..."``, a wrapper this parser does not model -- raises instead of+ being skipped. Guards that quietly match nothing are the bug this replaces.+ """+ invocations: list[list[str]] = []+ for line in _logical_lines(run):+ try:+ commands = _shell_commands(line)+ except ValueError as error:+ assert not NPM_MENTION.search(line), f"unreadable npm command line ({error}): {line.strip()}"+ continue+ for command in commands:+ argv = _invoked_command(command)+ if argv and NPM_EXECUTABLE.match(argv[0]):+ invocations.append(argv)+ continue+ assert not any(NPM_MENTION.search(token) for token in command), (+ f"npm invocation these guards cannot classify: {line.strip()}"+ )+ return invocations+++def test_npm_commands_sees_invocations_that_do_not_open_the_line() -> None:+ """The forms a line-anchored pattern silently missed."""+ assert _npm_commands("cd fern && npm install --ignore-scripts") == [["npm", "install", "--ignore-scripts"]]+ assert _npm_commands("env npm install") == [["npm", "install"]]+ assert _npm_commands("npm --prefix fern install") == [["npm", "--prefix", "fern", "install"]]+ assert _npm_commands("CI=true npm ci") == [["npm", "ci"]]+ assert _npm_commands("./node_modules/.bin/../../bin/npm ci") == [["./node_modules/.bin/../../bin/npm", "ci"]]+ assert _npm_commands("npm ci --ignore-scripts; npm run build") == [+ ["npm", "ci", "--ignore-scripts"],+ ["npm", "run", "build"],+ ]+++def test_npm_commands_recognizes_windows_case_insensitive_executable_names() -> None:+ assert _npm_commands("NPM install --ignore-scripts") == [["NPM", "install", "--ignore-scripts"]]+ assert _npm_commands("NpM.CmD ci --ignore-scripts") == [["NpM.CmD", "ci", "--ignore-scripts"]]+ assert _npm_commands("npm.ps1 ci --ignore-scripts") == [["npm.ps1", "ci", "--ignore-scripts"]]+++def test_npm_commands_reads_quoting_and_comments_the_way_a_shell_does() -> None:+ """Where the line ends and where an argument ends are both easy to get wrong.++ A ``#`` inside a URL does not open a comment, a quoted ``;`` is an argument+ rather than a command break, and a command inside ``if``/``then`` still runs.+ Each mistake hides a real npm invocation from the guards below.+ """+ assert _npm_commands("curl https://host/doc#install && npm install") == [["npm", "install"]]+ assert _npm_commands("npm ci --ignore-scripts # installs the pinned CLI") == [["npm", "ci", "--ignore-scripts"]]+ assert _npm_commands("if [ -d fern ]; then npm ci --ignore-scripts; fi") == [["npm", "ci", "--ignore-scripts"]]++ quoted = _npm_commands("npm ci --ignore-scripts ';' --no-ignore-scripts")+ assert quoted == [["npm", "ci", "--ignore-scripts", ";", "--no-ignore-scripts"]]+++def test_npm_commands_ignores_npm_outside_a_command() -> None:+ assert _npm_commands("# npm install is what this step replaces") == []+ assert _npm_commands("uv run pytest") == []+ assert _npm_commands("echo 'no npm-cache here' > /dev/null") == []+ assert _npm_commands('echo "${NPM_TOKEN}" "${NPM_CONFIG_CACHE:-$HOME/.npm}" ${PM:-pnpm}') == []+++def test_npm_commands_fails_closed_on_forms_it_cannot_classify() -> None:+ """An npm this parser cannot resolve must be loud, never skipped."""+ for run in (+ 'bash -c "npm install"',+ "sudo -u builder npm ci --ignore-scripts",+ "xargs npm install --ignore-scripts",+ 'NPM_BIN=npm && "$NPM_BIN" ci --ignore-scripts',+ "$(which npm) ci --ignore-scripts",+ "npm ci --ignore-scripts 'unbalanced",+ ):+ with pytest.raises(AssertionError):+ _npm_commands(run)+++ "run",+ [+ 'NPM_BIN=${UNSET:-npm}; "$NPM_BIN" install',+ "${UNSET:-npm} install",+ '"${UNSET:-npm}" install',+ "${UNSET-npm} install",+ "${UNSET:=npm} install",+ "${UNSET=npm} install",+ "${SET:+npm} install",+ "${UNSET:-/usr/bin/npm} install",+ "${PM/p/npm} install",+ ],+)+def test_npm_commands_fails_closed_on_npm_chosen_by_parameter_expansion(run: str) -> None:+ """With ``UNSET`` unset, Bash runs ``${UNSET:-npm} install`` as ``npm install``.++ Which word the expansion yields depends on the runner's environment, so+ the guard cannot classify it -- and must say so rather than see nothing.+ """+ with pytest.raises(AssertionError, match="cannot classify"):+ _npm_commands(run)+++ "run",+ [+ "npm install --package-lock-only --ignore-scripts",+ "npm ci --ignore-scripts --omit=optional",+ "npm ci --prefix fern --ignore-scripts --omit=optional --no-omit",+ "npm exec --yes --ignore-scripts --package-lock-only install",+ "npm ci -- --ignore-scripts",+ "npm ci --prefix fern --ignore-scripts --no-ignore-s --omit=optional",+ "npm cit --prefix fern --ignore-scripts --omit=optional",+ 'NPM_BIN=${UNSET:-npm}; "$NPM_BIN" install',+ ],+)+def test_unreviewed_npm_commands_fail_the_workflow_guard(+ run: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ (tmp_path / "probe.yml").write_text(+ yaml.safe_dump({"jobs": {"probe": {"steps": [{"run": run}]}}}), encoding="utf-8"+ )+ monkeypatch.setattr(sys.modules[__name__], "WORKFLOWS", tmp_path)++ with pytest.raises(AssertionError):+ test_every_workflow_uses_only_the_reviewed_npm_command()+++def test_every_workflow_uses_only_the_reviewed_npm_command() -> None:+ """The reviewed lockfile install is the only npm command in workflows.++ npm accepts option abbreviations, aliases, and a changing command grammar.+ An exact argv comparison keeps those forms from silently broadening what+ runs in a workflow. Any new npm use needs explicit review here.+ """+ for workflow_name in _workflow_names():+ for step in _all_steps(_load(workflow_name)):+ for argv in _npm_commands(step.get("run", "")):+ assert argv == REVIEWED_NPM_COMMAND, f"{workflow_name}: unreviewed npm command: {' '.join(argv)}"+++def test_the_pinned_fern_cli_version_matches_the_fern_config() -> None:+ """The Fern config, manifest, and lockfile describe one reviewed CLI tree.++ If they drift, docs may be validated or published with a different CLI or+ additional packages that were not reviewed for the token-bearing job.+ """+ manifest = json.loads((ROOT / "fern" / "package.json").read_text(encoding="utf-8"))+ fern_config = json.loads((ROOT / "fern" / "fern.config.json").read_text(encoding="utf-8"))+ lockfile = json.loads((ROOT / "fern" / "package-lock.json").read_text(encoding="utf-8"))++ declared = manifest["dependencies"]["fern-api"]+ assert declared == fern_config["version"], "fern/package.json and fern/fern.config.json disagree"+ assert re.fullmatch(r"\d+\.\d+\.\d+", declared), f"pin an exact version, not {declared!r}"+ assert manifest["dependencies"] == {"fern-api": declared}, "review new direct Fern dependencies"+ root_package = lockfile["packages"][""]+ assert root_package["dependencies"] == manifest["dependencies"], "lockfile root is stale"+ for dependency_group in ("devDependencies", "optionalDependencies", "peerDependencies"):+ assert not manifest.get(dependency_group), f"review new {dependency_group} in the Fern manifest"+ assert not root_package.get(dependency_group), f"review new {dependency_group} in the Fern lockfile"+ assert lockfile["packages"]["node_modules/fern-api"]["version"] == declared, "lockfile is stale"+ for path, package in lockfile["packages"].items():+ if not path:+ continue+ assert package.get("resolved", "").startswith("https://registry.npmjs.org/"), path+ assert package.get("integrity", "").startswith("sha512-"), path++[email protected]("mutation", ["extra_dependency", "root_drift", "missing_integrity"])+def test_fern_pin_guard_rejects_unreviewed_dependency_changes(+ mutation: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ source_fern = ROOT / "fern"+ isolated_fern = tmp_path / "fern"+ isolated_fern.mkdir()+ for name in ("package.json", "package-lock.json", "fern.config.json"):+ (isolated_fern / name).write_bytes((source_fern / name).read_bytes())++ manifest_path = isolated_fern / "package.json"+ lockfile_path = isolated_fern / "package-lock.json"+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))+ lockfile = json.loads(lockfile_path.read_text(encoding="utf-8"))+ if mutation == "extra_dependency":+ manifest["dependencies"]["extra-package"] = "1.0.0"+ elif mutation == "root_drift":+ lockfile["packages"][""]["dependencies"]["fern-api"] = "0.0.0"+ else:+ del lockfile["packages"]["node_modules/fern-api"]["integrity"]+ manifest_path.write_text(json.dumps(manifest), encoding="utf-8")+ lockfile_path.write_text(json.dumps(lockfile), encoding="utf-8")+ monkeypatch.setattr(sys.modules[__name__], "ROOT", tmp_path)++ with pytest.raises(AssertionError):+ test_the_pinned_fern_cli_version_matches_the_fern_config()