From e16c4bba5a44ab18150a5fe5c0eb0b7c5dc29881 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Wed, 2 Dec 2026 22:07:57 -0800 Subject: [PATCH 1/7] Consume the Built NuGet Package per Target Framework Before It Publishes (#4612) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Part of #4609 ## What - New composite action `.github/actions/package-consume-nuget/` (`action.yml` and `package_consume_nuget.py`), run by `build-nuget` after the hub default leaf in smoke and publish runs alike. It uploads nothing. - `plan` phase reads the declared target frameworks and outputs the runtime lines for the `dotnet-sdk` action, the `global.json` line first. `check` phase asserts the package shape (lib folders, nuspec version, dependency group per framework, symbol package) and then restores, builds, and runs a throwaway consumer per framework against the exact `.nupkg`, with its own `nuget.config` source mapping and package cache. It asserts the resolved `lib//` folder and the loaded assembly's `TargetFrameworkAttribute`. - Optional caller hook `.github/actions/package-consume/action.yml`, called once with the JSON `frameworks`, `package-id`, `version`, and `feed-dir`. A caller's own `build-nuget` hook is outside the check. - Hub self-test `scripts/package_consume_nuget_selftest.py` and a `NuGet package consume self-test job` in `test-pull-request.yml`, added to the aggregator's `needs:`. Unit tests in `tests/test_package_consume_nuget.py`. - `WORKFLOW.md` D1.7, S15, a 5A sentence, and the section 6 `nuget` row. `docs/reusable-workflows.md` hook contract and table. Skill mirrors regenerated with `build_dist.py`. ## Local evidence (SDKs 10.0 and 11.0) Good package, trimmed verdict lines: ```text PASS [package] lib folders equal declared frameworks: lib has ['net10.0', 'net11.0'], declared ['net10.0', 'net11.0'] PASS [net10.0] TargetFrameworkAttribute matches the folder: folder lib/net10.0 expects .NETCoreApp,Version=v10.0, assembly reports ['.NETCoreApp,Version=v10.0'] PASS [net11.0] TargetFrameworkAttribute matches the folder: folder lib/net11.0 expects .NETCoreApp,Version=v11.0, assembly reports ['.NETCoreApp,Version=v11.0'] ``` The net11.0 assembly under `lib/net10.0` (the #4534 shape), and the reverse: ```text FAIL [net10.0] TargetFrameworkAttribute matches the folder: folder lib/net10.0 expects .NETCoreApp,Version=v10.0, assembly reports ["FileNotFoundException: Could not load file or assembly 'System.Runtime, Version=11.0.0.0 ... FAIL [net11.0] TargetFrameworkAttribute matches the folder: folder lib/net11.0 expects .NETCoreApp,Version=v11.0, assembly reports ['.NETCoreApp,Version=v10.0'] SELF-TEST OK ``` ## Verification run locally ruff check and format, mypy, `python3 -m unittest discover -s tests` (the only failures are host-environment ones in `test_cli_usage` for host-setup scripts, plus two this change caused and fixed), `spec/validate.py`, `scripts/repo_gate.py`, actionlint in Docker, `prose_lint.py --diff origin/develop`, `build_dist.py`. The prose gate needs the `comments` label for the added comment lines. ## Local review Three recorded-pass rounds. Fixed: UTF-8 spawns, the deadline helper, package selection by ID, Release/Debug property read, skipped status, per-framework failure isolation, unknown-mode refusal, sibling package mapping, own-assembly attribute scoping, symbol package scoping, wording. Declined: netstandard resolving the nearest folder (the decided design), duplicated `escape_command` and `global.json` reading (actions ship self-contained), echo-line escaping, aggregator `needs` interpolation (matches the adjacent lines), packages without `lib/` assemblies (D1.7 scopes to library packages). Eight recorded passes ran. Every finding any of them raised is fixed or declined above, and the CodeRabbit threads are answered (frameworks wording 6ac0565b, C# 9 consumer 1a4c9cfb, signal path and sibling wording cbee2f3c). Declined with evidence: a single-PID SIGTERM sent to the self-test mid-run kills the check script through `run_with_deadline` before its own handler runs, which can leave a dotnet child. The self-test is a developer and CI harness whose process group the runner or terminal ends as a whole, and a group SIGINT was probed by hand (dies by SIGINT, no temporary directory left). `GOVERNANCE.md` "Trust Boundaries and Hardening Effort" rules out hardening for that input. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Sonnet 5.5 --- .../references/d-guarantees.md | 1 + .../references/test-methodology.md | 5 +- .../.source-digests/workflow-ci-contract | 2 +- .../references/d-guarantees.md | 1 + .../references/test-methodology.md | 5 +- .../actions/package-consume-nuget/action.yml | 78 +++ .../package_consume_nuget.py | 655 ++++++++++++++++++ .../references/d-guarantees.md | 1 + .../references/test-methodology.md | 5 +- .github/workflows/build-release-task.yml | 41 ++ .github/workflows/test-pull-request.yml | 33 +- WORKFLOW.md | 10 +- docs/reusable-workflows.md | 4 +- pyproject.toml | 2 +- scripts/package_consume_nuget_selftest.py | 198 ++++++ tests/test_cli_usage.py | 2 + tests/test_package_consume_nuget.py | 330 +++++++++ 17 files changed, 1362 insertions(+), 11 deletions(-) create mode 100644 .github/actions/package-consume-nuget/action.yml create mode 100755 .github/actions/package-consume-nuget/package_consume_nuget.py create mode 100755 scripts/package_consume_nuget_selftest.py create mode 100755 tests/test_package_consume_nuget.py diff --git a/.agents/skills/workflow-ci-contract/references/d-guarantees.md b/.agents/skills/workflow-ci-contract/references/d-guarantees.md index 10600e0ab..bdfdf1d53 100644 --- a/.agents/skills/workflow-ci-contract/references/d-guarantees.md +++ b/.agents/skills/workflow-ci-contract/references/d-guarantees.md @@ -16,6 +16,7 @@ The required behaviors, organized by domain. Each is a **MUST**, and its `Output - **D1.4 Workflow-file changes are not smoke-built.** Input: a PR changing only `.github/workflows/**`. Output: the paths-filter marks no target, so smoke-build skips. An inclusion list satisfying D1.1 reaches this by leaving workflow paths out of every target's entry. *Implication: a workflow-only change is not smoke-built, but actionlint still validates it in CI.* - **D1.5 One required aggregator gates merge.** Input: any PR. Output: a single aggregator job must **succeed**. It must run under `if: always()`, so a failed or skipped dependency cannot skip the gate itself. It must also `needs:` the validation job, and the `changes` and `smoke-build` jobs too wherever the repo has a smoke build. It must treat a **skipped** smoke build as pass, and **block** on `failure`/`cancelled`. Its name is ruleset-bound: the job `name:` and the ruleset `context:` are the same string and MUST be renamed together, never independently. The workflow holding it MUST trigger on `pull_request`. A gate without a `pull_request` trigger never runs the validator's pull-request-only steps, the prose gate among them. A workflow any other event also triggers yields that name only when `github.event_name == 'pull_request'`, through an expression `name:`. Otherwise a dispatch or push run on a PR's head posts the required context without the PR run's gates. *Prevents: a paths-filter error letting a target-changing PR merge unbuilt.* - **D1.6 Coverage is reported to Codecov (C# and Python).** Input: a C# or Python repo that has tests for that type. Output: the validation job runs those tests under coverage collection, and a `codecov/codecov-action` step uploads the report. The collection is `dotnet test --coverage --coverage-output-format cobertura --results-directory ./coverage`, leaving `--coverage-output` unset so each test project writes its own report rather than overwriting a shared one. A bare call resolves one workspace from the working directory, so it fails at a root holding none or more than one. Unless the repository root holds exactly one solution or project, the hub's validator therefore runs the collection once per tracked `*Tests*.csproj` with `--project`. It names no solution in that case, since a solution holding no test project fails the run. Or it is `pytest --cov-report=xml` in a Python directory with its own `uv.lock` or `requirements*.txt`, whose own `pyproject.toml` selects what to measure. Or it is `coverage run -m unittest discover -s tests` then `coverage xml` in a `lint-only` one. The upload is **best-effort** (`continue-on-error` and/or `fail_ci_if_error: false`), so a Codecov outage or an absent token never reds the gate. Each leg **fails its test step when the run wrote no report**. The reason is that the best-effort upload reads a missing report exactly as it reads a healthy run. A second reason is that, on the Python leg, `--cov-report=xml` alone selects nothing to measure. The C# leg renames each report to `coverage-.cobertura.xml` before the upload step reads the directory, since `codecov-cli`'s own finder does not match the default name. A repo owning its validator rather than calling the hub's owes that rename itself. `CODECOV_TOKEN` lives in the repo's **actions** and **dependabot** secret stores. The token is in the second because a run triggered by a Dependabot pull request reads the Dependabot store. Without the token there, the upload would otherwise skip silently on every bot pull request. A caller reaching the reusable validator across repositories names the secret it passes (`secrets:` with `CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}`). It does so on its pull request path and its publisher path alike. That is because `secrets: inherit` is documented for a caller in the same organization or enterprise, which a personal account is not. A call by local path stays inside one repository, where the caller's own store is the one the callee reads. So `secrets: inherit` is available there instead of naming each secret. The repo ships a **`.codecov.yml`** at the repository root. It sets the project and patch statuses to **`informational: true`**, so a coverage delta never gates a pull request. A repo whose quality bar requires a threshold may turn that off. The same file excludes intentionally-untested, non-shipped code (an example or benchmark project) from the denominator via `ignore`. Codecov reads its configuration under several names, but `.codecov.yml` is the only one the fleet accepts. So a copy under any other name is drift to rename. Coverage output is a build artifact, so `.gitignore` excludes it. The C# invocation runs under **Microsoft.Testing.Platform**, and the runner declaration, package references, and version floor an MTP-based test project needs are `CODESTYLE.md`'s .NET side. The Python invocation needs **`pytest-cov`** and a coverage selector, which are `CODESTYLE.md`'s Python side. A Python directory declared in the validator's `python-directories` input owes a `tests/` suite whatever its profile, so the validator fails one that has none. N/A for a repo carrying no tests for that type. *Prevents: coverage silently going unreported, and a coverage regression blocking an unrelated pull request.* +- **D1.7 A built NuGet package is consumed before it publishes.** Input: a repo whose `build-nuget` job runs the hub's default leaf, in a smoke run or a publish run alike. Output: after the leaf packs, the job restores, builds, and runs a throwaway console project against that exact `.nupkg`. It does so once per target framework the project declares. Each consumer lives outside the checkout, so the caller's `global.json` and `Directory.Build.props` do not apply. Its `nuget.config` resolves the package ID, and the ID of each sibling package in the folder holding the build output, only from that folder. Every other ID resolves from nuget.org. Its package cache is its own, so neither a cached nor a published copy can stand in for the artifact under test. The consumer loads the package assembly and calls `GetExportedTypes()`. The check asserts from `obj/project.assets.json` that the package resolved from the `lib//` folder of the consumer's own framework. It also asserts that the loaded assembly's `TargetFrameworkAttribute` matches that folder. A `netstandard` framework is consumed under the SDK line `global.json` selects, or the newest declared line where there is none. It is asserted against the folder it resolved. A framework the check does not consume is reported skipped. Examples are .NET Framework, `netcoreapp3.1`, and a platform-specific `netX.Y-windows`. The attribute row of a `netstandard` consumer resolving such a folder is skipped too. Four static assertions join them. The package's `lib//` folders equal the declared frameworks. The nuspec `` equals the build version. The nuspec holds a dependency group per framework. A symbol package exists where the project enables symbols. Every declared `netX.Y` and `netstandard` framework is consumed and reported with one summary row per assertion. A failed step ends that framework's rows rather than the run. The job fails at the end if any failed. The check covers a library package, whose assemblies sit under `lib//`. The check uploads nothing, so it honors D1.3. It runs inside the build job, so a failure blocks the publish job that `needs:` that build. A caller's own `build-nuget` hook replaces the whole leaf and is outside the check. A caller's own `.github/actions/package-consume/action.yml` runs once after the default check. It receives the declared frameworks as JSON beside the package ID, version, and package folder. *Prevents: a defect that exists only in the packed form shipping. One example is one target framework's assembly packed under every `lib//` folder while the tests, which reach the library through a project reference, stay green.* ### D2 - Input/State Validation at Entry diff --git a/.agents/skills/workflow-ci-contract/references/test-methodology.md b/.agents/skills/workflow-ci-contract/references/test-methodology.md index d5140ce9f..d5030643e 100644 --- a/.agents/skills/workflow-ci-contract/references/test-methodology.md +++ b/.agents/skills/workflow-ci-contract/references/test-methodology.md @@ -14,11 +14,13 @@ Assert the structural fact each *applicable* D-guarantee implies, and record **p Most of the evidence is in the workflow files and the composite actions they reach. Where a guarantee's evidence lies outside them, in practice it lies in one of these places. They are the repo's branch ruleset, its Actions and Dependabot secret names, a workflow the repo only calls, or a project or dependency file. They also include a committed file such as `version.json`, `.github/dependabot.yml`, `global.json`, `.codecov.yml`, `.gitignore`, or `.editorconfig`. +D1.7 is read in the build job. A step after the default leaf plans the declared frameworks, then the `dotnet-sdk` action installs those runtime lines, then the consume check runs. None of them uploads. + Cite what each verdict rests on. That is `file:line` for a file in the audited repo. It is the evidence's own name where a setting, a ruleset, or a secret name rather than a file is the evidence. Where the guarantee binds a workflow or composite action the audited repo only reaches, it is `/@` plus the `file:line` in that repo. The callee is read at the SHA the caller pins. An **N/A** verdict names the absent construct instead, there being no line to cite. ### 5B. End-to-End Trace Scenarios (No Execution, Deterministic from the YAML) -For each *applicable* scenario, evaluate every job's `if:`/`needs:` against the inputs. Emit the predicted **run/skip + version + release + artifact-end-state** table, then compare to the expected. A scenario governing a construct the repo does not contain is N/A, per `WORKFLOW.md` section 1, and an absent trigger is such a construct. Each scenario's trigger belongs to one workflow, so read that workflow's own `on:` block rather than the repo's type. For S1 to S4 the block is the pull request workflow's, and for S5 to S10 and S14 the publisher's. For S11 the block is the upstream tracker's, and for S12 and S13 the deploy workflow's. A publisher carrying only `workflow_dispatch` therefore records S5, S6 and S9 N/A, their push and schedule paths never firing there. A repo with no publisher lacks a construct every repo owes. So S7, S8, S10 and S14 fail there, and none is excluded from the verdict. S5, S6 and S9 turn on the `on:` block that publisher has yet to state, so each is judged once it lands. A publisher whose schedule never publishes, per D4.1, records the schedule paths of S7 and S9 N/A as well. Where a scenario's path runs through a workflow or composite action the repo only **calls**, trace that callee as the repo reaches it. Read it at the SHA the caller pins rather than at the callee's current default branch, which is the same evidence rule 5A states. Predicting from the callee's `main` predicts a table for YAML the audited repo never runs. A self-repository (`$/`) call or a job-level local (`./`) reusable-workflow call carries no pin of its own. It resolves at the calling workflow file's commit, so it is traced at that file's own commit. That commit is the SHA fixed by the pin that reached that file. Where that file is one of the audited repository's own workflows, it is the audited commit instead. A local (`./`) action reference carries no pin either, but it resolves against whatever the job checked out. So it is traced at that checkout's commit. That is the caller's commit where a reusable workflow called from another repository checks out its caller. Minimum set: +For each *applicable* scenario, evaluate every job's `if:`/`needs:` against the inputs. Emit the predicted **run/skip + version + release + artifact-end-state** table, then compare to the expected. A scenario governing a construct the repo does not contain is N/A, per `WORKFLOW.md` section 1, and an absent trigger is such a construct. Each scenario's trigger belongs to one workflow, so read that workflow's own `on:` block rather than the repo's type. For S1 to S4 the block is the pull request workflow's. For S5 to S10 and S14 it is the publisher's. For S15 it is whichever workflow reaches the `build-nuget` job. For S11 the block is the upstream tracker's, and for S12 and S13 the deploy workflow's. A publisher carrying only `workflow_dispatch` therefore records S5, S6 and S9 N/A, their push and schedule paths never firing there. A repo with no publisher lacks a construct every repo owes. So S7, S8, S10 and S14 fail there, and none is excluded from the verdict. S5, S6 and S9 turn on the `on:` block that publisher has yet to state, so each is judged once it lands. A publisher whose schedule never publishes, per D4.1, records the schedule paths of S7 and S9 N/A as well. Where a scenario's path runs through a workflow or composite action the repo only **calls**, trace that callee as the repo reaches it. Read it at the SHA the caller pins rather than at the callee's current default branch, which is the same evidence rule 5A states. Predicting from the callee's `main` predicts a table for YAML the audited repo never runs. A self-repository (`$/`) call or a job-level local (`./`) reusable-workflow call carries no pin of its own. It resolves at the calling workflow file's commit, so it is traced at that file's own commit. That commit is the SHA fixed by the pin that reached that file. Where that file is one of the audited repository's own workflows, it is the audited commit instead. A local (`./`) action reference carries no pin either, but it resolves against whatever the job checked out. So it is traced at that checkout's commit. That is the caller's commit where a reusable workflow called from another repository checks out its caller. Minimum set: | # | Input | Expected output | Exercises | | --- | --- | --- | --- | @@ -36,6 +38,7 @@ For each *applicable* scenario, evaluate every job's `if:`/`needs:` against the | S12 | deploy dispatch naming an environment | the ref gate runs **first**, allowing production from the default branch only and any ref to a non-production environment. Validation runs, and the callee re-asserts the environment name. A release installs under its own id, and the pointer flips as a separate step. Retention is bounded by whichever of the D5.6 shapes the repo uses. So a deploy whose credential can observe the destination asserts the count converged, and one confined write-only leaves it to the host. The live check asserts the environment and the release id, waiting out the reload, then the URL contract. **No tag and no release are created** | D2.1, D4.6, D5.6 | | S13 | deploy dispatch of a production environment from a non-default ref | **fails fast**, before anything is installed or written | D2.1 | | S14 | publish whose branch head gained different `.github/workflows` content after the build began | every update since a release bot's push or merge: release-create **skipped** and the publisher dispatched on the branch. In that case this run ends **cancelled** with its package publish jobs skipped (a Docker image already pushed). The dispatched run releases the head, queueing behind this run only where the head's publisher evaluates this run's group for a dispatch. A push landing after the branch is confirmed unmoved and before the dispatch is released as if it were such an update. That is an accepted, bounded limit per D4.7. Any other update: the step **fails**, nothing is released or dispatched | D4.1, D4.2, D4.5, D4.7 | +| S15 | a smoke or publish run whose `build-nuget` job runs the hub default leaf, for a project declaring `net10.0;net11.0`. The package holds one framework's assembly under both `lib/` folders | the job plans both runtime lines, installs them, and consumes the package once per framework. It **fails** on the `TargetFrameworkAttribute` of the `lib/` folder holding the other framework's assembly, after reporting every other row. A correct package **passes**. The check uploads nothing in either run. A publish run's leaf has uploaded its artifacts already, and a failure leaves them to their retention and the dependent publish job **skipped** | D1.3, D1.7 | ### 5C. Live Probe (Where Warranted) diff --git a/.claude-plugin/fleet-skills/.source-digests/workflow-ci-contract b/.claude-plugin/fleet-skills/.source-digests/workflow-ci-contract index 5e7c4c577..34815610b 100644 --- a/.claude-plugin/fleet-skills/.source-digests/workflow-ci-contract +++ b/.claude-plugin/fleet-skills/.source-digests/workflow-ci-contract @@ -1 +1 @@ -1017f507478d9c3d +1f8840231e1f50fb diff --git a/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/d-guarantees.md b/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/d-guarantees.md index 10600e0ab..bdfdf1d53 100644 --- a/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/d-guarantees.md +++ b/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/d-guarantees.md @@ -16,6 +16,7 @@ The required behaviors, organized by domain. Each is a **MUST**, and its `Output - **D1.4 Workflow-file changes are not smoke-built.** Input: a PR changing only `.github/workflows/**`. Output: the paths-filter marks no target, so smoke-build skips. An inclusion list satisfying D1.1 reaches this by leaving workflow paths out of every target's entry. *Implication: a workflow-only change is not smoke-built, but actionlint still validates it in CI.* - **D1.5 One required aggregator gates merge.** Input: any PR. Output: a single aggregator job must **succeed**. It must run under `if: always()`, so a failed or skipped dependency cannot skip the gate itself. It must also `needs:` the validation job, and the `changes` and `smoke-build` jobs too wherever the repo has a smoke build. It must treat a **skipped** smoke build as pass, and **block** on `failure`/`cancelled`. Its name is ruleset-bound: the job `name:` and the ruleset `context:` are the same string and MUST be renamed together, never independently. The workflow holding it MUST trigger on `pull_request`. A gate without a `pull_request` trigger never runs the validator's pull-request-only steps, the prose gate among them. A workflow any other event also triggers yields that name only when `github.event_name == 'pull_request'`, through an expression `name:`. Otherwise a dispatch or push run on a PR's head posts the required context without the PR run's gates. *Prevents: a paths-filter error letting a target-changing PR merge unbuilt.* - **D1.6 Coverage is reported to Codecov (C# and Python).** Input: a C# or Python repo that has tests for that type. Output: the validation job runs those tests under coverage collection, and a `codecov/codecov-action` step uploads the report. The collection is `dotnet test --coverage --coverage-output-format cobertura --results-directory ./coverage`, leaving `--coverage-output` unset so each test project writes its own report rather than overwriting a shared one. A bare call resolves one workspace from the working directory, so it fails at a root holding none or more than one. Unless the repository root holds exactly one solution or project, the hub's validator therefore runs the collection once per tracked `*Tests*.csproj` with `--project`. It names no solution in that case, since a solution holding no test project fails the run. Or it is `pytest --cov-report=xml` in a Python directory with its own `uv.lock` or `requirements*.txt`, whose own `pyproject.toml` selects what to measure. Or it is `coverage run -m unittest discover -s tests` then `coverage xml` in a `lint-only` one. The upload is **best-effort** (`continue-on-error` and/or `fail_ci_if_error: false`), so a Codecov outage or an absent token never reds the gate. Each leg **fails its test step when the run wrote no report**. The reason is that the best-effort upload reads a missing report exactly as it reads a healthy run. A second reason is that, on the Python leg, `--cov-report=xml` alone selects nothing to measure. The C# leg renames each report to `coverage-.cobertura.xml` before the upload step reads the directory, since `codecov-cli`'s own finder does not match the default name. A repo owning its validator rather than calling the hub's owes that rename itself. `CODECOV_TOKEN` lives in the repo's **actions** and **dependabot** secret stores. The token is in the second because a run triggered by a Dependabot pull request reads the Dependabot store. Without the token there, the upload would otherwise skip silently on every bot pull request. A caller reaching the reusable validator across repositories names the secret it passes (`secrets:` with `CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}`). It does so on its pull request path and its publisher path alike. That is because `secrets: inherit` is documented for a caller in the same organization or enterprise, which a personal account is not. A call by local path stays inside one repository, where the caller's own store is the one the callee reads. So `secrets: inherit` is available there instead of naming each secret. The repo ships a **`.codecov.yml`** at the repository root. It sets the project and patch statuses to **`informational: true`**, so a coverage delta never gates a pull request. A repo whose quality bar requires a threshold may turn that off. The same file excludes intentionally-untested, non-shipped code (an example or benchmark project) from the denominator via `ignore`. Codecov reads its configuration under several names, but `.codecov.yml` is the only one the fleet accepts. So a copy under any other name is drift to rename. Coverage output is a build artifact, so `.gitignore` excludes it. The C# invocation runs under **Microsoft.Testing.Platform**, and the runner declaration, package references, and version floor an MTP-based test project needs are `CODESTYLE.md`'s .NET side. The Python invocation needs **`pytest-cov`** and a coverage selector, which are `CODESTYLE.md`'s Python side. A Python directory declared in the validator's `python-directories` input owes a `tests/` suite whatever its profile, so the validator fails one that has none. N/A for a repo carrying no tests for that type. *Prevents: coverage silently going unreported, and a coverage regression blocking an unrelated pull request.* +- **D1.7 A built NuGet package is consumed before it publishes.** Input: a repo whose `build-nuget` job runs the hub's default leaf, in a smoke run or a publish run alike. Output: after the leaf packs, the job restores, builds, and runs a throwaway console project against that exact `.nupkg`. It does so once per target framework the project declares. Each consumer lives outside the checkout, so the caller's `global.json` and `Directory.Build.props` do not apply. Its `nuget.config` resolves the package ID, and the ID of each sibling package in the folder holding the build output, only from that folder. Every other ID resolves from nuget.org. Its package cache is its own, so neither a cached nor a published copy can stand in for the artifact under test. The consumer loads the package assembly and calls `GetExportedTypes()`. The check asserts from `obj/project.assets.json` that the package resolved from the `lib//` folder of the consumer's own framework. It also asserts that the loaded assembly's `TargetFrameworkAttribute` matches that folder. A `netstandard` framework is consumed under the SDK line `global.json` selects, or the newest declared line where there is none. It is asserted against the folder it resolved. A framework the check does not consume is reported skipped. Examples are .NET Framework, `netcoreapp3.1`, and a platform-specific `netX.Y-windows`. The attribute row of a `netstandard` consumer resolving such a folder is skipped too. Four static assertions join them. The package's `lib//` folders equal the declared frameworks. The nuspec `` equals the build version. The nuspec holds a dependency group per framework. A symbol package exists where the project enables symbols. Every declared `netX.Y` and `netstandard` framework is consumed and reported with one summary row per assertion. A failed step ends that framework's rows rather than the run. The job fails at the end if any failed. The check covers a library package, whose assemblies sit under `lib//`. The check uploads nothing, so it honors D1.3. It runs inside the build job, so a failure blocks the publish job that `needs:` that build. A caller's own `build-nuget` hook replaces the whole leaf and is outside the check. A caller's own `.github/actions/package-consume/action.yml` runs once after the default check. It receives the declared frameworks as JSON beside the package ID, version, and package folder. *Prevents: a defect that exists only in the packed form shipping. One example is one target framework's assembly packed under every `lib//` folder while the tests, which reach the library through a project reference, stay green.* ### D2 - Input/State Validation at Entry diff --git a/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/test-methodology.md b/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/test-methodology.md index d5140ce9f..d5030643e 100644 --- a/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/test-methodology.md +++ b/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/test-methodology.md @@ -14,11 +14,13 @@ Assert the structural fact each *applicable* D-guarantee implies, and record **p Most of the evidence is in the workflow files and the composite actions they reach. Where a guarantee's evidence lies outside them, in practice it lies in one of these places. They are the repo's branch ruleset, its Actions and Dependabot secret names, a workflow the repo only calls, or a project or dependency file. They also include a committed file such as `version.json`, `.github/dependabot.yml`, `global.json`, `.codecov.yml`, `.gitignore`, or `.editorconfig`. +D1.7 is read in the build job. A step after the default leaf plans the declared frameworks, then the `dotnet-sdk` action installs those runtime lines, then the consume check runs. None of them uploads. + Cite what each verdict rests on. That is `file:line` for a file in the audited repo. It is the evidence's own name where a setting, a ruleset, or a secret name rather than a file is the evidence. Where the guarantee binds a workflow or composite action the audited repo only reaches, it is `/@` plus the `file:line` in that repo. The callee is read at the SHA the caller pins. An **N/A** verdict names the absent construct instead, there being no line to cite. ### 5B. End-to-End Trace Scenarios (No Execution, Deterministic from the YAML) -For each *applicable* scenario, evaluate every job's `if:`/`needs:` against the inputs. Emit the predicted **run/skip + version + release + artifact-end-state** table, then compare to the expected. A scenario governing a construct the repo does not contain is N/A, per `WORKFLOW.md` section 1, and an absent trigger is such a construct. Each scenario's trigger belongs to one workflow, so read that workflow's own `on:` block rather than the repo's type. For S1 to S4 the block is the pull request workflow's, and for S5 to S10 and S14 the publisher's. For S11 the block is the upstream tracker's, and for S12 and S13 the deploy workflow's. A publisher carrying only `workflow_dispatch` therefore records S5, S6 and S9 N/A, their push and schedule paths never firing there. A repo with no publisher lacks a construct every repo owes. So S7, S8, S10 and S14 fail there, and none is excluded from the verdict. S5, S6 and S9 turn on the `on:` block that publisher has yet to state, so each is judged once it lands. A publisher whose schedule never publishes, per D4.1, records the schedule paths of S7 and S9 N/A as well. Where a scenario's path runs through a workflow or composite action the repo only **calls**, trace that callee as the repo reaches it. Read it at the SHA the caller pins rather than at the callee's current default branch, which is the same evidence rule 5A states. Predicting from the callee's `main` predicts a table for YAML the audited repo never runs. A self-repository (`$/`) call or a job-level local (`./`) reusable-workflow call carries no pin of its own. It resolves at the calling workflow file's commit, so it is traced at that file's own commit. That commit is the SHA fixed by the pin that reached that file. Where that file is one of the audited repository's own workflows, it is the audited commit instead. A local (`./`) action reference carries no pin either, but it resolves against whatever the job checked out. So it is traced at that checkout's commit. That is the caller's commit where a reusable workflow called from another repository checks out its caller. Minimum set: +For each *applicable* scenario, evaluate every job's `if:`/`needs:` against the inputs. Emit the predicted **run/skip + version + release + artifact-end-state** table, then compare to the expected. A scenario governing a construct the repo does not contain is N/A, per `WORKFLOW.md` section 1, and an absent trigger is such a construct. Each scenario's trigger belongs to one workflow, so read that workflow's own `on:` block rather than the repo's type. For S1 to S4 the block is the pull request workflow's. For S5 to S10 and S14 it is the publisher's. For S15 it is whichever workflow reaches the `build-nuget` job. For S11 the block is the upstream tracker's, and for S12 and S13 the deploy workflow's. A publisher carrying only `workflow_dispatch` therefore records S5, S6 and S9 N/A, their push and schedule paths never firing there. A repo with no publisher lacks a construct every repo owes. So S7, S8, S10 and S14 fail there, and none is excluded from the verdict. S5, S6 and S9 turn on the `on:` block that publisher has yet to state, so each is judged once it lands. A publisher whose schedule never publishes, per D4.1, records the schedule paths of S7 and S9 N/A as well. Where a scenario's path runs through a workflow or composite action the repo only **calls**, trace that callee as the repo reaches it. Read it at the SHA the caller pins rather than at the callee's current default branch, which is the same evidence rule 5A states. Predicting from the callee's `main` predicts a table for YAML the audited repo never runs. A self-repository (`$/`) call or a job-level local (`./`) reusable-workflow call carries no pin of its own. It resolves at the calling workflow file's commit, so it is traced at that file's own commit. That commit is the SHA fixed by the pin that reached that file. Where that file is one of the audited repository's own workflows, it is the audited commit instead. A local (`./`) action reference carries no pin either, but it resolves against whatever the job checked out. So it is traced at that checkout's commit. That is the caller's commit where a reusable workflow called from another repository checks out its caller. Minimum set: | # | Input | Expected output | Exercises | | --- | --- | --- | --- | @@ -36,6 +38,7 @@ For each *applicable* scenario, evaluate every job's `if:`/`needs:` against the | S12 | deploy dispatch naming an environment | the ref gate runs **first**, allowing production from the default branch only and any ref to a non-production environment. Validation runs, and the callee re-asserts the environment name. A release installs under its own id, and the pointer flips as a separate step. Retention is bounded by whichever of the D5.6 shapes the repo uses. So a deploy whose credential can observe the destination asserts the count converged, and one confined write-only leaves it to the host. The live check asserts the environment and the release id, waiting out the reload, then the URL contract. **No tag and no release are created** | D2.1, D4.6, D5.6 | | S13 | deploy dispatch of a production environment from a non-default ref | **fails fast**, before anything is installed or written | D2.1 | | S14 | publish whose branch head gained different `.github/workflows` content after the build began | every update since a release bot's push or merge: release-create **skipped** and the publisher dispatched on the branch. In that case this run ends **cancelled** with its package publish jobs skipped (a Docker image already pushed). The dispatched run releases the head, queueing behind this run only where the head's publisher evaluates this run's group for a dispatch. A push landing after the branch is confirmed unmoved and before the dispatch is released as if it were such an update. That is an accepted, bounded limit per D4.7. Any other update: the step **fails**, nothing is released or dispatched | D4.1, D4.2, D4.5, D4.7 | +| S15 | a smoke or publish run whose `build-nuget` job runs the hub default leaf, for a project declaring `net10.0;net11.0`. The package holds one framework's assembly under both `lib/` folders | the job plans both runtime lines, installs them, and consumes the package once per framework. It **fails** on the `TargetFrameworkAttribute` of the `lib/` folder holding the other framework's assembly, after reporting every other row. A correct package **passes**. The check uploads nothing in either run. A publish run's leaf has uploaded its artifacts already, and a failure leaves them to their retention and the dependent publish job **skipped** | D1.3, D1.7 | ### 5C. Live Probe (Where Warranted) diff --git a/.github/actions/package-consume-nuget/action.yml b/.github/actions/package-consume-nuget/action.yml new file mode 100644 index 000000000..33a1ccb35 --- /dev/null +++ b/.github/actions/package-consume-nuget/action.yml @@ -0,0 +1,78 @@ +name: Package consume NuGet +description: >- + Check the NuGet package a build produced by consuming it, once per target framework the project declares, before anything publishes. + The phase `plan` reads the declared frameworks and outputs the .NET lines to install, so the caller installs them with the dotnet-sdk action between the two phases. + The phase `check` asserts the package's shape (lib folders, nuspec version, dependency groups, symbol package) and then restores, builds, and runs a throwaway consumer per framework against the exact package. + A caller's own `.github/actions/package-consume/action.yml` is outside this action. + The hub's build task runs that hook once, after the default check, with the JSON `frameworks` array, the `package-id`, the `version`, and the `feed-dir` holding the packages, so the hook loops over the frameworks itself. + A caller's own build-nuget hook replaces the whole default build and is outside the check. + Nothing is uploaded, so a smoke run runs it unchanged. + +inputs: + mode: + description: "plan reads the declared frameworks and outputs. check runs the shape assertions and the consumers." + required: true + branch: + description: Logical branch the package was built for. main reads the project's properties as Release, anything else as Debug, as the build leaf packs. + required: true + project-file: + description: Path to the .NET project file the package was built from. + required: true + semver2: + description: The package version the build was given, which the nuspec must carry. + required: true + package-dir: + description: Folder holding the built .nupkg and .snupkg, which also serves as the consumer's only local package source. + required: true + +outputs: + sdk-versions: + description: JSON array of the X.Y lines to install, the one global.json selects first. Empty where nothing needs a specific line. + value: ${{ steps.plan.outputs.sdk-versions }} + frameworks: + description: JSON array of the declared target frameworks in the short folder-style spelling, a platform version dropped, so `net10.0-windows10.0.19041.0` reads `net10.0-windows`. + value: ${{ steps.plan.outputs.frameworks }} + package-id: + description: The package ID read from the built nuspec. + value: ${{ steps.plan.outputs.package-id }} + +runs: + using: composite + steps: + + - name: Require a known mode step + if: ${{ inputs.mode != 'plan' && inputs.mode != 'check' }} + shell: bash + run: | + set -Eeuo pipefail + echo "::error::package-consume-nuget takes a mode of plan or check." + exit 1 + + - name: Plan the package consume step + id: plan + if: ${{ inputs.mode == 'plan' }} + shell: bash + env: + PACKAGE_CONSUME_MODE: plan + BRANCH: ${{ inputs.branch }} + PROJECT_FILE: ${{ inputs.project-file }} + PACKAGE_DIR: ${{ inputs.package-dir }} + run: | + set -Eeuo pipefail + python3 "$GITHUB_ACTION_PATH/package_consume_nuget.py" + + - name: Consume the package step + if: ${{ inputs.mode == 'check' }} + shell: bash + env: + PACKAGE_CONSUME_MODE: check + BRANCH: ${{ inputs.branch }} + PROJECT_FILE: ${{ inputs.project-file }} + SEMVER2: ${{ inputs.semver2 }} + PACKAGE_DIR: ${{ inputs.package-dir }} + run: | + set -Eeuo pipefail + # The consumers live in the runner's temp folder, outside the checkout, so the caller's global.json and Directory.*.props do not apply. + WORK_DIR="$(mktemp -d "$RUNNER_TEMP/package-consume.XXXXXX")" + export WORK_DIR + python3 "$GITHUB_ACTION_PATH/package_consume_nuget.py" diff --git a/.github/actions/package-consume-nuget/package_consume_nuget.py b/.github/actions/package-consume-nuget/package_consume_nuget.py new file mode 100755 index 000000000..ed4b22938 --- /dev/null +++ b/.github/actions/package-consume-nuget/package_consume_nuget.py @@ -0,0 +1,655 @@ +#!/usr/bin/env python3 +"""Consume the built NuGet package once per declared target framework, before anything publishes. + +The unit tests reach the library through a project reference and never through the package. +So a defect that exists only in the packed form passes every other gate. +One package once carried a single target framework's assembly under every `lib//` folder, and CI stayed green. + +`PACKAGE_CONSUME_MODE` selects the phase, since a composite action cannot install the SDK lines between two of its own steps. + +- `plan` reads the project's declared target frameworks. + It writes the .NET lines to install, the package ID, and the declared frameworks to GITHUB_OUTPUT. +- `check` runs the static shape checks on the .nupkg. + It then restores, builds, and runs a throwaway console project per declared framework against exactly that package. + +The consumer lives outside the repository. +So the caller's global.json, Directory.Build.props, and Directory.Packages.props do not apply. +Its nuget.config resolves the package ID, and each sibling package in the local folder, only from that folder. +Every other ID resolves from nuget.org. +Its package cache is its own, so neither a cached copy nor the published one can stand in for the build under test. + +Every check runs and reports, then the exit status says whether any failed. +Nothing is uploaded. +""" + +from __future__ import annotations + +import argparse +import contextlib +import json +import os +import re +import signal +import subprocess +import sys +import zipfile +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, field +from pathlib import Path +from types import FrameType +from xml.etree import ElementTree +from xml.sax.saxutils import quoteattr + +COMMAND_TIMEOUT_SECONDS = 900 +FALLBACK_LINE = "10.0" +PROPERTIES = ( + "TargetFrameworks", + "TargetFramework", + "IncludeSymbols", + "SymbolPackageFormat", + "PackageId", + "AssemblyName", +) +NET_MODERN = re.compile(r"^net(\d+)\.(\d+)$") +NET_STANDARD = re.compile(r"^netstandard\d+\.\d+$") + +PROGRAM = """using System; +using System.Reflection; +using System.Runtime.Versioning; + +// The attribute is read before the types, so a package whose assembly cannot load still reports why. +var failed = false; +foreach (var name in args) +{ + try + { + var assembly = Assembly.Load(new AssemblyName(name)); + var attribute = assembly.GetCustomAttribute(); + Console.WriteLine($"FRAMEWORK\\t{name}\\t{attribute?.FrameworkName}"); + Console.WriteLine($"EXPORTED\\t{name}\\t{assembly.GetExportedTypes().Length}"); + } + catch (Exception exception) + { + failed = true; + Console.WriteLine($"LOADFAIL\\t{name}\\t{exception.GetType().Name}: {exception.Message.Split('\\n')[0]}"); + } +} +return failed ? 1 : 0; +""" + + +def escape_command(value: str) -> str: + """Encode a value for a workflow command, percent first so the later escapes are not re-encoded.""" + return value.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A") + + +def normalize_tfm(value: str) -> str: + """The short folder-style name of a target framework, however a project or nuspec spells it.""" + text = value.strip().lower() + match = re.fullmatch(r"\.netcoreapp,version=v(\d+)\.(\d+)", text) + if match: + major, minor = int(match.group(1)), match.group(2) + return f"net{major}.{minor}" if major >= 5 else f"netcoreapp{major}.{minor}" + match = re.fullmatch(r"\.netcoreapp(\d+\.\d+)", text) + if match: + return f"netcoreapp{match.group(1)}" + match = re.fullmatch(r"\.netstandard,?(?:version=v)?(\d+\.\d+)", text) + if match: + return f"netstandard{match.group(1)}" + match = re.fullmatch(r"\.netframework,?(?:version=v)?(\d+)\.(\d+)(?:\.(\d+))?", text) + if match: + return "net" + "".join(part for part in match.groups() if part) + # A platform-specific folder carries a platform version that the project's own spelling omits. + match = re.fullmatch(r"(net\d+\.\d+)-([a-z]+)[\d.]*", text) + if match: + return f"{match.group(1)}-{match.group(2)}" + return text + + +def declared_frameworks(properties: Mapping[str, str]) -> list[str]: + """The declared frameworks in order, normalized and without duplicates.""" + raw = properties.get("TargetFrameworks", "").strip() or properties.get("TargetFramework", "") + seen: list[str] = [] + for part in raw.split(";"): + name = normalize_tfm(part) + if name and name not in seen: + seen.append(name) + return seen + + +def modern_line(framework: str) -> str | None: + """The X.Y runtime line of a plain netX.Y framework with X at least 5, else None.""" + match = NET_MODERN.fullmatch(framework) + if match and int(match.group(1)) >= 5: + return f"{match.group(1)}.{match.group(2)}" + return None + + +def expected_attribute(folder: str) -> str | None: + """The TargetFrameworkAttribute value an assembly built for a lib folder carries.""" + line = modern_line(folder) + if line: + return f".NETCoreApp,Version=v{line}" + if NET_STANDARD.fullmatch(folder): + return f".NETStandard,Version=v{folder.removeprefix('netstandard')}" + return None + + +def plan_versions(frameworks: Sequence[str], global_line: str | None) -> list[str]: + """The lines to install, the one the root global.json selects first, as the dotnet-sdk action requires.""" + lines = sorted( + {line for name in frameworks if (line := modern_line(name))}, + key=lambda line: tuple(int(part) for part in line.split(".")), + reverse=True, + ) + first = global_line or (lines[0] if lines else None) + if first is None: + return [] + return [first, *[line for line in lines if line != first]] + + +def global_json_line(path: Path) -> str | None: + """The X.Y line global.json's sdk.version selects, or None where there is none to read.""" + if not path.is_file(): + return None + text = path.read_text(encoding="utf-8-sig", errors="replace") + comments = re.compile(r'("(?:\\.|[^"\\])*")|//[^\n]*|/\*.*?\*/', re.DOTALL) + text = comments.sub(lambda m: m.group(1) or re.sub(r"[^\n]", " ", m.group(0)), text) + try: + sdk = json.loads(text).get("sdk") + except (ValueError, AttributeError): + return None + if not isinstance(sdk, dict) or not isinstance(sdk.get("version"), str): + return None + match = re.match(r"(\d+\.\d+)", sdk["version"]) + return match.group(1) if match else None + + +def project_properties(project: str) -> dict[str, str]: + # The leaf packs Release on main and Debug elsewhere, and a property can be conditioned on it. + configuration = "Release" if os.environ.get("BRANCH") == "main" else "Debug" + result = subprocess.run( + [ + "dotnet", + "msbuild", + project, + "-nologo", + f"-property:Configuration={configuration}", + "-getProperty:" + ",".join(PROPERTIES), + ], + capture_output=True, + text=True, + encoding="utf-8", + check=False, + timeout=COMMAND_TIMEOUT_SECONDS, + ) + if result.returncode != 0: + raise SystemExit(f"Reading {project}'s properties failed:\n{result.stdout}{result.stderr}") + return {k: str(v) for k, v in json.loads(result.stdout)["Properties"].items()} + + +def find_package(package_dir: Path, package_id: str = "") -> Path: + """The one package built for the project, chosen by its ID where a referenced project packed one too.""" + found = sorted( + path for path in package_dir.glob("*.nupkg") if not path.name.endswith(".symbols.nupkg") + ) + if package_id: + found = [ + p for p in found if nuspec_text(read_nuspec(p), "id").lower() == package_id.lower() + ] + if len(found) != 1: + raise SystemExit(f"Expected exactly one .nupkg in {package_dir}, found {len(found)}.") + return found[0] + + +def read_nuspec(package: Path) -> ElementTree.Element: + with zipfile.ZipFile(package) as archive: + names = [n for n in archive.namelist() if n.endswith(".nuspec") and "/" not in n] + if len(names) != 1: + raise SystemExit(f"{package.name} holds {len(names)} root .nuspec files, expected one.") + return ElementTree.fromstring(archive.read(names[0])) + + +def nuspec_text(root: ElementTree.Element, tag: str) -> str: + for element in root.iter(): + if element.tag.rpartition("}")[2] == tag and element.text: + return element.text.strip() + return "" + + +@dataclass +class Result: + target: str + check: str + ok: bool + detail: str + skipped: bool = False + + +@dataclass +class Report: + results: list[Result] = field(default_factory=list) + + def add(self, target: str, check: str, ok: bool, detail: str, skipped: bool = False) -> bool: + self.results.append(Result(target, check, ok, detail, skipped)) + # A detail can carry command output, so a line break must not start a line of its own and forge a command. + print( + f"{'SKIP' if skipped else 'PASS' if ok else 'FAIL'} [{target}] {check}: {escape_command(detail)}" + ) + if not ok: + print(f"::error::{escape_command(f'package-consume [{target}] {check}: {detail}')}") + return ok + + def table(self) -> str: + def cell(value: str) -> str: + return value.replace("|", "\\|").replace("\r", " ").replace("\n", " ") + + rows = ["| Target | Check | Result | Detail |", "| --- | --- | --- | --- |"] + rows += [ + f"| {cell(r.target)} | {cell(r.check)} | {'skip' if r.skipped else 'pass' if r.ok else 'fail'} | {cell(r.detail)} |" + for r in self.results + ] + return "\n".join(rows) + "\n" + + @property + def failed(self) -> bool: + return any(not r.ok for r in self.results) + + +def without_metadata(version: str) -> str: + """A version as NuGet stores it, without build metadata and case-folded.""" + return version.split("+")[0].lower() + + +def static_shape( + package: Path, + frameworks: Sequence[str], + version: str, + symbols_expected: bool, + symbol_format: str, + report: Report, +) -> None: + """Assert the package's folder layout, metadata, and symbol package against the project's declaration.""" + print("::group::Static package shape") + try: + with zipfile.ZipFile(package) as archive: + names = archive.namelist() + folders = { + n.split("/")[1].lower() for n in names if n.startswith("lib/") and n.count("/") >= 2 + } + declared = set(frameworks) + normalized = {normalize_tfm(f) for f in folders} + report.add( + "package", + "lib folders equal declared frameworks", + normalized == declared, + f"lib has {sorted(normalized)}, declared {sorted(declared)}", + ) + root = read_nuspec(package) + nuspec_version = nuspec_text(root, "version") + report.add( + "package", + "nuspec version equals the build version", + without_metadata(nuspec_version) == without_metadata(version), + f"nuspec {nuspec_version!r}, built {version!r}", + ) + groups = { + normalize_tfm(element.attrib["targetFramework"]) + for element in root.iter() + if element.tag.rpartition("}")[2] == "group" and element.attrib.get("targetFramework") + } + missing = sorted(declared - groups) + report.add( + "package", + "dependency group per framework", + not missing, + f"missing groups {missing}" if missing else f"groups {sorted(groups)}", + ) + if symbols_expected: + suffix = ".snupkg" if symbol_format.lower() == "snupkg" else ".symbols.nupkg" + wanted = package.with_suffix("").name + suffix + found = [wanted] if (package.parent / wanted).is_file() else [] + report.add( + "package", + "symbol package exists", + bool(found), + f"found {found}" if found else f"no {wanted} beside {package.name}", + ) + finally: + print("::endgroup::") + + +def resolved_folder(assets: Mapping[str, object], package_id: str) -> tuple[str, list[str]]: + """The `lib/` a restore resolved the package from, and the assembly names it supplies.""" + targets = assets.get("targets") + if not isinstance(targets, dict) or len(targets) != 1: + raise ValueError("project.assets.json does not hold exactly one target") + (entries,) = targets.values() + wanted = package_id.lower() + "/" + entry = next((v for k, v in entries.items() if k.lower().startswith(wanted)), None) + if entry is None: + raise ValueError(f"{package_id} is not in the resolved target") + keys = [*entry.get("compile", {}), *entry.get("runtime", {})] + paths = [k for k in keys if k.lower().endswith(".dll")] + folders = {p.split("/")[1] for p in paths if p.startswith("lib/")} + if len(folders) != 1: + raise ValueError(f"expected one lib folder, resolved {sorted(folders)}") + names = sorted({Path(p).stem for p in entry.get("runtime", {}) if p.lower().endswith(".dll")}) + if not names: + raise ValueError("the package supplies no runtime assembly") + return folders.pop(), names + + +def run( + command: Sequence[str], cwd: Path, env: Mapping[str, str] +) -> subprocess.CompletedProcess[str]: + print("$ " + " ".join(command)) + result = subprocess.run( + list(command), + cwd=cwd, + env=dict(env), + capture_output=True, + text=True, + encoding="utf-8", + check=False, + timeout=COMMAND_TIMEOUT_SECONDS, + ) + print(result.stdout + result.stderr, end="") + return result + + +def write_consumer( + directory: Path, + package_id: str, + version: str, + consumer_tfm: str, + feed: Path, + local_ids: Sequence[str], +) -> None: + directory.mkdir(parents=True, exist_ok=True) + # A global.json of its own stops the lookup short of the caller's, and rolls forward so any installed SDK serves. + (directory.parent / "global.json").write_text( + '{"sdk": {"rollForward": "latestMajor", "allowPrerelease": true}}\n', encoding="utf-8" + ) + (directory / "Consumer.csproj").write_text( + '\n \n' + " Exe\n" + f" {consumer_tfm}\n" + " false\n" + " false\n" + " \n \n" + f" \n" + " \n\n", + encoding="utf-8", + ) + (directory / "Program.cs").write_text(PROGRAM, encoding="utf-8") + (directory / "nuget.config").write_text( + '\n\n \n \n' + f' \n' + ' \n' + " \n \n" + ' \n' + + "".join(f" \n" for i in local_ids) + + " \n" + ' \n' + " \n\n", + encoding="utf-8", + ) + + +def consume( + package_id: str, + version: str, + framework: str, + declared: Sequence[str], + consumer_line: str, + feed: Path, + work: Path, + report: Report, + primary: Sequence[str] = (), +) -> None: + """Restore, build, and run a consumer of the exact package, then assert what it resolved and loaded.""" + label = f"consume {framework}" + print(f"::group::{escape_command(label)}") + try: + line = modern_line(framework) + consumer_tfm = f"net{line or consumer_line}" + directory = work / framework / "app" + # A sibling package a referenced project packed beside this one exists only in the folder, so it maps there too. + local_ids = sorted( + {package_id} + | { + nuspec_text(read_nuspec(p), "id") + for p in feed.glob("*.nupkg") + if not p.name.endswith(".symbols.nupkg") + } + ) + write_consumer(directory, package_id, version, consumer_tfm, feed, local_ids) + env = { + **os.environ, + "NUGET_PACKAGES": str(work / framework / "packages"), + "DOTNET_CLI_TELEMETRY_OPTOUT": "1", + "DOTNET_NOLOGO": "1", + # No build server or node outlives the step, which would otherwise hold the runner's temp folder. + "MSBUILDDISABLENODEREUSE": "1", + "DOTNET_CLI_HOME": str(work / framework / "home"), + } + restore = run( + ["dotnet", "restore", "--configfile", "nuget.config", "-nologo"], directory, env + ) + if not report.add(framework, "restore", restore.returncode == 0, f"as {consumer_tfm}"): + return + try: + assets = json.loads((directory / "obj" / "project.assets.json").read_text("utf-8")) + folder, assemblies = resolved_folder(assets, package_id) + except (OSError, ValueError) as error: + report.add(framework, "resolved lib folder", False, str(error)) + return + # A netstandard library is consumed under the SDK line, so it resolves to the best folder the package holds for it. + wanted = framework if line else None + ok = folder == wanted if wanted else normalize_tfm(folder) in declared + report.add( + framework, + "resolved lib folder", + ok, + f"resolved lib/{folder}, expected {'lib/' + wanted if wanted else 'a declared folder'}", + ) + out = directory / "out" + build = run( + ["dotnet", "build", "--no-restore", "-c", "Release", "-nologo", "-o", str(out)], + directory, + env, + ) + if not report.add(framework, "build", build.returncode == 0, f"as {consumer_tfm}"): + return + loaded = run(["dotnet", str(out / "Consumer.dll"), *assemblies], directory, env) + rows = [ln.split("\t") for ln in loaded.stdout.splitlines()] + exported = [r[1] for r in rows if r[0] == "EXPORTED"] + # The framework assertion runs even where the load failed, since a mispacked assembly often cannot load. + expected = expected_attribute(folder) + # A bundled helper assembly can legitimately carry another framework's attribute, so only the package's own assembly is held to the folder. + names = {n.lower() for n in primary if n} + own = [r for r in rows if r[0] == "FRAMEWORK" and r[1].lower() in names] + got = {r[2] for r in (own or [r for r in rows if r[0] == "FRAMEWORK"])} + failures = [r[2] for r in rows if r[0] == "LOADFAIL"] + if expected is None: + # A netstandard consumer can resolve a folder the check does not assert, such as netcoreapp3.1. + report.add( + framework, + "TargetFrameworkAttribute matches the folder", + True, + f"lib/{folder} is not a framework the check asserts", + skipped=True, + ) + else: + report.add( + framework, + "TargetFrameworkAttribute matches the folder", + got == {expected}, + f"folder lib/{folder} expects {expected}, assembly reports {sorted(got) or failures}", + ) + report.add( + framework, + "load and GetExportedTypes", + loaded.returncode == 0 and sorted(exported) == sorted(assemblies), + f"loaded {exported}" + (f", failed {failures}" if failures else ""), + ) + finally: + print("::endgroup::") + + +def write_outputs(values: Mapping[str, str]) -> None: + target = os.environ.get("GITHUB_OUTPUT") + if not target: + return + with open(target, "a", encoding="utf-8") as output: + for key, value in values.items(): + if "\n" in value or "\r" in value: + raise SystemExit(f"Output {key} holds a line break.") + output.write(f"{key}={value}\n") + + +def project_package_id(properties: Mapping[str, str]) -> str: + return properties.get("PackageId") or properties.get("AssemblyName", "") + + +def plan(project: str, package_dir: Path) -> int: + properties = project_properties(project) + frameworks = declared_frameworks(properties) + if not frameworks: + print(f"::error::{escape_command(f'{project} declares no target framework.')}") + return 1 + versions = plan_versions(frameworks, global_json_line(Path("global.json"))) + package = find_package(package_dir, project_package_id(properties)) + package_id = nuspec_text(read_nuspec(package), "id") + write_outputs( + { + "sdk-versions": json.dumps(versions) if versions else "", + "frameworks": json.dumps(frameworks), + "package-id": package_id, + } + ) + print(f"frameworks {frameworks}, install {versions}, package {package_id}") + return 0 + + +def check(project: str, version: str, package_dir: Path, work: Path) -> int: + properties = project_properties(project) + frameworks = declared_frameworks(properties) + package = find_package(package_dir, project_package_id(properties)) + package_id = nuspec_text(read_nuspec(package), "id") + versions = plan_versions(frameworks, global_json_line(Path("global.json"))) + consumer_line = versions[0] if versions else FALLBACK_LINE + report = Report() + symbols = properties.get("IncludeSymbols", "").lower() == "true" + static_shape( + package, frameworks, version, symbols, properties.get("SymbolPackageFormat", ""), report + ) + for framework in frameworks: + if modern_line(framework) is None and not NET_STANDARD.fullmatch(framework): + report.add( + framework, + "consume", + True, + "the check consumes plain net5.0 and later and netstandard frameworks only", + skipped=True, + ) + continue + try: + consume( + package_id, + version, + framework, + frameworks, + consumer_line, + package_dir, + work, + report, + [package_id, properties.get("AssemblyName", "")], + ) + except (OSError, ValueError, KeyError, AttributeError, subprocess.SubprocessError) as error: + # One framework's unexpected failure must not hide the rows of the others. + report.add(framework, "consume", False, f"{type(error).__name__}: {error}") + summary = os.environ.get("GITHUB_STEP_SUMMARY") + if summary: + with open(summary, "a", encoding="utf-8") as handle: + handle.write( + f"### Package consume check for {package_id} {version}\n\n{report.table()}\n" + ) + return 1 if report.failed else 0 + + +def main(argv: Sequence[str] = ()) -> int: + argparse.ArgumentParser( + description=(__doc__ or "").splitlines()[0], + epilog="Reads PACKAGE_CONSUME_MODE (plan or check), BRANCH, PROJECT_FILE, SEMVER2, PACKAGE_DIR, and WORK_DIR from the environment.", + ).parse_args(list(argv)) + os.environ.setdefault("MSBUILDDISABLENODEREUSE", "1") + mode = os.environ.get("PACKAGE_CONSUME_MODE", "") + project = os.environ.get("PROJECT_FILE", "") + package_dir = Path(os.environ.get("PACKAGE_DIR", "")).resolve() + if mode not in {"plan", "check"} or not project or not package_dir.is_dir(): + print( + "::error::package-consume needs a mode of plan or check, a project file, and the package directory." + ) + return 1 + if mode == "plan": + return plan(project, package_dir) + version = os.environ.get("SEMVER2", "") + work = Path(os.environ.get("WORK_DIR", "")) if os.environ.get("WORK_DIR") else None + if not version or work is None: + print("::error::package-consume's check phase needs SEMVER2 and WORK_DIR.") + return 1 + return check(project, version, package_dir, work) + + +received: list[int] = [] + + +def on_signal(signum: int, frame: FrameType | None) -> None: + """Record the signal and raise KeyboardInterrupt, so every signal unwinds one path. + + A later signal is passed over, since it would cut the unwinding short. + A later signal can start inside this handler, so a call from this frame returns too. + """ + if received or (frame is not None and frame.f_code is on_signal.__code__): + return + received.append(signum) + raise KeyboardInterrupt + + +def interrupted() -> int: + """Name the recorded signal, and return it as the status the caller re-raises.""" + signum = signal.Signals(received[0] if received else signal.SIGINT) + print(f"{Path(__file__).name}: interrupted by {signum.name}.", file=sys.stderr) + return signum + + +def reraise(signum: signal.Signals) -> None: + """End this process by `signum`, so a caller sees the signal rather than an exit status.""" + with contextlib.suppress(OSError): + sys.stdout.flush() + sys.stderr.flush() + if sys.platform == "win32": + sys.exit(130) + signal.signal(signum, signal.SIG_DFL) + os.kill(os.getpid(), signum) + sys.exit(128 + signum) + + +def entry(argv: Sequence[str]) -> int: + """Run main with one handler for both signals, returning the signal's number where one arrived.""" + signal.signal(signal.SIGTERM, on_signal) + if signal.getsignal(signal.SIGINT) is signal.default_int_handler: + signal.signal(signal.SIGINT, on_signal) + try: + return main(argv) + except KeyboardInterrupt: + return interrupted() + + +if __name__ == "__main__": + status = entry(sys.argv[1:]) + if received: + reraise(signal.Signals(received[0])) + sys.exit(status) diff --git a/.github/skills/workflow-ci-contract/references/d-guarantees.md b/.github/skills/workflow-ci-contract/references/d-guarantees.md index 10600e0ab..bdfdf1d53 100644 --- a/.github/skills/workflow-ci-contract/references/d-guarantees.md +++ b/.github/skills/workflow-ci-contract/references/d-guarantees.md @@ -16,6 +16,7 @@ The required behaviors, organized by domain. Each is a **MUST**, and its `Output - **D1.4 Workflow-file changes are not smoke-built.** Input: a PR changing only `.github/workflows/**`. Output: the paths-filter marks no target, so smoke-build skips. An inclusion list satisfying D1.1 reaches this by leaving workflow paths out of every target's entry. *Implication: a workflow-only change is not smoke-built, but actionlint still validates it in CI.* - **D1.5 One required aggregator gates merge.** Input: any PR. Output: a single aggregator job must **succeed**. It must run under `if: always()`, so a failed or skipped dependency cannot skip the gate itself. It must also `needs:` the validation job, and the `changes` and `smoke-build` jobs too wherever the repo has a smoke build. It must treat a **skipped** smoke build as pass, and **block** on `failure`/`cancelled`. Its name is ruleset-bound: the job `name:` and the ruleset `context:` are the same string and MUST be renamed together, never independently. The workflow holding it MUST trigger on `pull_request`. A gate without a `pull_request` trigger never runs the validator's pull-request-only steps, the prose gate among them. A workflow any other event also triggers yields that name only when `github.event_name == 'pull_request'`, through an expression `name:`. Otherwise a dispatch or push run on a PR's head posts the required context without the PR run's gates. *Prevents: a paths-filter error letting a target-changing PR merge unbuilt.* - **D1.6 Coverage is reported to Codecov (C# and Python).** Input: a C# or Python repo that has tests for that type. Output: the validation job runs those tests under coverage collection, and a `codecov/codecov-action` step uploads the report. The collection is `dotnet test --coverage --coverage-output-format cobertura --results-directory ./coverage`, leaving `--coverage-output` unset so each test project writes its own report rather than overwriting a shared one. A bare call resolves one workspace from the working directory, so it fails at a root holding none or more than one. Unless the repository root holds exactly one solution or project, the hub's validator therefore runs the collection once per tracked `*Tests*.csproj` with `--project`. It names no solution in that case, since a solution holding no test project fails the run. Or it is `pytest --cov-report=xml` in a Python directory with its own `uv.lock` or `requirements*.txt`, whose own `pyproject.toml` selects what to measure. Or it is `coverage run -m unittest discover -s tests` then `coverage xml` in a `lint-only` one. The upload is **best-effort** (`continue-on-error` and/or `fail_ci_if_error: false`), so a Codecov outage or an absent token never reds the gate. Each leg **fails its test step when the run wrote no report**. The reason is that the best-effort upload reads a missing report exactly as it reads a healthy run. A second reason is that, on the Python leg, `--cov-report=xml` alone selects nothing to measure. The C# leg renames each report to `coverage-.cobertura.xml` before the upload step reads the directory, since `codecov-cli`'s own finder does not match the default name. A repo owning its validator rather than calling the hub's owes that rename itself. `CODECOV_TOKEN` lives in the repo's **actions** and **dependabot** secret stores. The token is in the second because a run triggered by a Dependabot pull request reads the Dependabot store. Without the token there, the upload would otherwise skip silently on every bot pull request. A caller reaching the reusable validator across repositories names the secret it passes (`secrets:` with `CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}`). It does so on its pull request path and its publisher path alike. That is because `secrets: inherit` is documented for a caller in the same organization or enterprise, which a personal account is not. A call by local path stays inside one repository, where the caller's own store is the one the callee reads. So `secrets: inherit` is available there instead of naming each secret. The repo ships a **`.codecov.yml`** at the repository root. It sets the project and patch statuses to **`informational: true`**, so a coverage delta never gates a pull request. A repo whose quality bar requires a threshold may turn that off. The same file excludes intentionally-untested, non-shipped code (an example or benchmark project) from the denominator via `ignore`. Codecov reads its configuration under several names, but `.codecov.yml` is the only one the fleet accepts. So a copy under any other name is drift to rename. Coverage output is a build artifact, so `.gitignore` excludes it. The C# invocation runs under **Microsoft.Testing.Platform**, and the runner declaration, package references, and version floor an MTP-based test project needs are `CODESTYLE.md`'s .NET side. The Python invocation needs **`pytest-cov`** and a coverage selector, which are `CODESTYLE.md`'s Python side. A Python directory declared in the validator's `python-directories` input owes a `tests/` suite whatever its profile, so the validator fails one that has none. N/A for a repo carrying no tests for that type. *Prevents: coverage silently going unreported, and a coverage regression blocking an unrelated pull request.* +- **D1.7 A built NuGet package is consumed before it publishes.** Input: a repo whose `build-nuget` job runs the hub's default leaf, in a smoke run or a publish run alike. Output: after the leaf packs, the job restores, builds, and runs a throwaway console project against that exact `.nupkg`. It does so once per target framework the project declares. Each consumer lives outside the checkout, so the caller's `global.json` and `Directory.Build.props` do not apply. Its `nuget.config` resolves the package ID, and the ID of each sibling package in the folder holding the build output, only from that folder. Every other ID resolves from nuget.org. Its package cache is its own, so neither a cached nor a published copy can stand in for the artifact under test. The consumer loads the package assembly and calls `GetExportedTypes()`. The check asserts from `obj/project.assets.json` that the package resolved from the `lib//` folder of the consumer's own framework. It also asserts that the loaded assembly's `TargetFrameworkAttribute` matches that folder. A `netstandard` framework is consumed under the SDK line `global.json` selects, or the newest declared line where there is none. It is asserted against the folder it resolved. A framework the check does not consume is reported skipped. Examples are .NET Framework, `netcoreapp3.1`, and a platform-specific `netX.Y-windows`. The attribute row of a `netstandard` consumer resolving such a folder is skipped too. Four static assertions join them. The package's `lib//` folders equal the declared frameworks. The nuspec `` equals the build version. The nuspec holds a dependency group per framework. A symbol package exists where the project enables symbols. Every declared `netX.Y` and `netstandard` framework is consumed and reported with one summary row per assertion. A failed step ends that framework's rows rather than the run. The job fails at the end if any failed. The check covers a library package, whose assemblies sit under `lib//`. The check uploads nothing, so it honors D1.3. It runs inside the build job, so a failure blocks the publish job that `needs:` that build. A caller's own `build-nuget` hook replaces the whole leaf and is outside the check. A caller's own `.github/actions/package-consume/action.yml` runs once after the default check. It receives the declared frameworks as JSON beside the package ID, version, and package folder. *Prevents: a defect that exists only in the packed form shipping. One example is one target framework's assembly packed under every `lib//` folder while the tests, which reach the library through a project reference, stay green.* ### D2 - Input/State Validation at Entry diff --git a/.github/skills/workflow-ci-contract/references/test-methodology.md b/.github/skills/workflow-ci-contract/references/test-methodology.md index d5140ce9f..d5030643e 100644 --- a/.github/skills/workflow-ci-contract/references/test-methodology.md +++ b/.github/skills/workflow-ci-contract/references/test-methodology.md @@ -14,11 +14,13 @@ Assert the structural fact each *applicable* D-guarantee implies, and record **p Most of the evidence is in the workflow files and the composite actions they reach. Where a guarantee's evidence lies outside them, in practice it lies in one of these places. They are the repo's branch ruleset, its Actions and Dependabot secret names, a workflow the repo only calls, or a project or dependency file. They also include a committed file such as `version.json`, `.github/dependabot.yml`, `global.json`, `.codecov.yml`, `.gitignore`, or `.editorconfig`. +D1.7 is read in the build job. A step after the default leaf plans the declared frameworks, then the `dotnet-sdk` action installs those runtime lines, then the consume check runs. None of them uploads. + Cite what each verdict rests on. That is `file:line` for a file in the audited repo. It is the evidence's own name where a setting, a ruleset, or a secret name rather than a file is the evidence. Where the guarantee binds a workflow or composite action the audited repo only reaches, it is `/@` plus the `file:line` in that repo. The callee is read at the SHA the caller pins. An **N/A** verdict names the absent construct instead, there being no line to cite. ### 5B. End-to-End Trace Scenarios (No Execution, Deterministic from the YAML) -For each *applicable* scenario, evaluate every job's `if:`/`needs:` against the inputs. Emit the predicted **run/skip + version + release + artifact-end-state** table, then compare to the expected. A scenario governing a construct the repo does not contain is N/A, per `WORKFLOW.md` section 1, and an absent trigger is such a construct. Each scenario's trigger belongs to one workflow, so read that workflow's own `on:` block rather than the repo's type. For S1 to S4 the block is the pull request workflow's, and for S5 to S10 and S14 the publisher's. For S11 the block is the upstream tracker's, and for S12 and S13 the deploy workflow's. A publisher carrying only `workflow_dispatch` therefore records S5, S6 and S9 N/A, their push and schedule paths never firing there. A repo with no publisher lacks a construct every repo owes. So S7, S8, S10 and S14 fail there, and none is excluded from the verdict. S5, S6 and S9 turn on the `on:` block that publisher has yet to state, so each is judged once it lands. A publisher whose schedule never publishes, per D4.1, records the schedule paths of S7 and S9 N/A as well. Where a scenario's path runs through a workflow or composite action the repo only **calls**, trace that callee as the repo reaches it. Read it at the SHA the caller pins rather than at the callee's current default branch, which is the same evidence rule 5A states. Predicting from the callee's `main` predicts a table for YAML the audited repo never runs. A self-repository (`$/`) call or a job-level local (`./`) reusable-workflow call carries no pin of its own. It resolves at the calling workflow file's commit, so it is traced at that file's own commit. That commit is the SHA fixed by the pin that reached that file. Where that file is one of the audited repository's own workflows, it is the audited commit instead. A local (`./`) action reference carries no pin either, but it resolves against whatever the job checked out. So it is traced at that checkout's commit. That is the caller's commit where a reusable workflow called from another repository checks out its caller. Minimum set: +For each *applicable* scenario, evaluate every job's `if:`/`needs:` against the inputs. Emit the predicted **run/skip + version + release + artifact-end-state** table, then compare to the expected. A scenario governing a construct the repo does not contain is N/A, per `WORKFLOW.md` section 1, and an absent trigger is such a construct. Each scenario's trigger belongs to one workflow, so read that workflow's own `on:` block rather than the repo's type. For S1 to S4 the block is the pull request workflow's. For S5 to S10 and S14 it is the publisher's. For S15 it is whichever workflow reaches the `build-nuget` job. For S11 the block is the upstream tracker's, and for S12 and S13 the deploy workflow's. A publisher carrying only `workflow_dispatch` therefore records S5, S6 and S9 N/A, their push and schedule paths never firing there. A repo with no publisher lacks a construct every repo owes. So S7, S8, S10 and S14 fail there, and none is excluded from the verdict. S5, S6 and S9 turn on the `on:` block that publisher has yet to state, so each is judged once it lands. A publisher whose schedule never publishes, per D4.1, records the schedule paths of S7 and S9 N/A as well. Where a scenario's path runs through a workflow or composite action the repo only **calls**, trace that callee as the repo reaches it. Read it at the SHA the caller pins rather than at the callee's current default branch, which is the same evidence rule 5A states. Predicting from the callee's `main` predicts a table for YAML the audited repo never runs. A self-repository (`$/`) call or a job-level local (`./`) reusable-workflow call carries no pin of its own. It resolves at the calling workflow file's commit, so it is traced at that file's own commit. That commit is the SHA fixed by the pin that reached that file. Where that file is one of the audited repository's own workflows, it is the audited commit instead. A local (`./`) action reference carries no pin either, but it resolves against whatever the job checked out. So it is traced at that checkout's commit. That is the caller's commit where a reusable workflow called from another repository checks out its caller. Minimum set: | # | Input | Expected output | Exercises | | --- | --- | --- | --- | @@ -36,6 +38,7 @@ For each *applicable* scenario, evaluate every job's `if:`/`needs:` against the | S12 | deploy dispatch naming an environment | the ref gate runs **first**, allowing production from the default branch only and any ref to a non-production environment. Validation runs, and the callee re-asserts the environment name. A release installs under its own id, and the pointer flips as a separate step. Retention is bounded by whichever of the D5.6 shapes the repo uses. So a deploy whose credential can observe the destination asserts the count converged, and one confined write-only leaves it to the host. The live check asserts the environment and the release id, waiting out the reload, then the URL contract. **No tag and no release are created** | D2.1, D4.6, D5.6 | | S13 | deploy dispatch of a production environment from a non-default ref | **fails fast**, before anything is installed or written | D2.1 | | S14 | publish whose branch head gained different `.github/workflows` content after the build began | every update since a release bot's push or merge: release-create **skipped** and the publisher dispatched on the branch. In that case this run ends **cancelled** with its package publish jobs skipped (a Docker image already pushed). The dispatched run releases the head, queueing behind this run only where the head's publisher evaluates this run's group for a dispatch. A push landing after the branch is confirmed unmoved and before the dispatch is released as if it were such an update. That is an accepted, bounded limit per D4.7. Any other update: the step **fails**, nothing is released or dispatched | D4.1, D4.2, D4.5, D4.7 | +| S15 | a smoke or publish run whose `build-nuget` job runs the hub default leaf, for a project declaring `net10.0;net11.0`. The package holds one framework's assembly under both `lib/` folders | the job plans both runtime lines, installs them, and consumes the package once per framework. It **fails** on the `TargetFrameworkAttribute` of the `lib/` folder holding the other framework's assembly, after reporting every other row. A correct package **passes**. The check uploads nothing in either run. A publish run's leaf has uploaded its artifacts already, and a failure leaves them to their retention and the dependent publish job **skipped** | D1.3, D1.7 | ### 5C. Live Probe (Where Warranted) diff --git a/.github/workflows/build-release-task.yml b/.github/workflows/build-release-task.yml index 3cd6bf795..ecfa994a5 100644 --- a/.github/workflows/build-release-task.yml +++ b/.github/workflows/build-release-task.yml @@ -252,6 +252,47 @@ jobs: assembly-informational-version: ${{ needs.get-version.outputs.AssemblyInformationalVersion }} project-file: ${{ inputs.nuget_project }} + # The package is consumed once per declared target framework before anything publishes, in smoke and publish runs alike. + # It uploads nothing, so D1.3 holds. + # A caller's own build-nuget hook is outside the check, since the hub cannot know where that hook wrote its package. + - name: Plan package consume step + id: package-consume-plan + if: ${{ hashFiles('.github/actions/build-nuget/action.yml') == '' }} + uses: $/.github/actions/package-consume-nuget + with: + mode: plan + branch: ${{ inputs.branch }} + project-file: ${{ inputs.nuget_project }} + semver2: ${{ needs.get-version.outputs.SemVer2 }} + package-dir: ${{ runner.temp }}/publish + + # The first entry is the line global.json selects, which the plan puts first, so the action's own check accepts it. + - name: Setup consumer .NET runtimes step + if: ${{ hashFiles('.github/actions/build-nuget/action.yml') == '' }} + uses: $/.github/actions/dotnet-sdk + with: + versions: ${{ steps.package-consume-plan.outputs.sdk-versions }} + + - name: Run package consume check step + if: ${{ hashFiles('.github/actions/build-nuget/action.yml') == '' }} + uses: $/.github/actions/package-consume-nuget + with: + mode: check + branch: ${{ inputs.branch }} + project-file: ${{ inputs.nuget_project }} + semver2: ${{ needs.get-version.outputs.SemVer2 }} + package-dir: ${{ runner.temp }}/publish + + # The caller's own consumer, run once with every declared framework so it loops over them itself. + - name: Run caller package-consume hook step + if: ${{ hashFiles('.github/actions/build-nuget/action.yml') == '' && hashFiles('.github/actions/package-consume/action.yml') != '' }} + uses: ./.github/actions/package-consume + with: + frameworks: ${{ steps.package-consume-plan.outputs.frameworks }} + package-id: ${{ steps.package-consume-plan.outputs.package-id }} + version: ${{ needs.get-version.outputs.SemVer2 }} + feed-dir: ${{ runner.temp }}/publish + # PyPI publishing happens in the caller stub's own publish-pypi job, since id-token: write is granted only at that one entry point. # This job just builds and uploads the artifact for that job to download. build-pypi: diff --git a/.github/workflows/test-pull-request.yml b/.github/workflows/test-pull-request.yml index 688b4f194..bb7a61344 100644 --- a/.github/workflows/test-pull-request.yml +++ b/.github/workflows/test-pull-request.yml @@ -57,6 +57,33 @@ jobs: python -m pip install --requirement tests/requirements.txt python -m unittest discover -s tests + # The hub holds no .NET project, so this builds a constructed multi-targeted library, packs it, and runs the package consume check against it. + # A correct package must pass, and one with the net11.0 assembly under lib/net10.0 must fail. + # That proves the check can still see the defect it exists for. + nuget-consume-test: + name: NuGet package consume self-test job + runs-on: ubuntu-latest + timeout-minutes: 30 + permissions: + contents: read + steps: + + - name: Checkout code step + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + # The hub has no global.json, so both lines install and neither is the one a root file selects. + - name: Setup .NET SDK step + uses: ./.github/actions/dotnet-sdk + with: + versions: '["11.0", "10.0"]' + + - name: Run package consume self-test step + run: | + set -Eeuo pipefail + python3 scripts/package_consume_nuget_selftest.py + # GitHub Actions does not support required status checks on conditional jobs, so a single always-run aggregator gates the merge. # Its name is the ruleset-bound required status-check context, so rename it and the ruleset context together. # Only a pull_request run takes that name. @@ -64,7 +91,7 @@ jobs: check-workflow-status: name: ${{ github.event_name == 'pull_request' && 'Check pull request workflow status job' || 'Check workflow status job' }} runs-on: ubuntu-latest - needs: [ validate, windows-test ] + needs: [ validate, windows-test, nuget-consume-test ] if: always() steps: - name: Check workflow results step @@ -78,3 +105,7 @@ jobs: echo "Job 'windows-test' did not succeed (${{ needs.windows-test.result }}); refusing to pass." exit 1 fi + if [[ "${{ needs.nuget-consume-test.result }}" != "success" ]]; then + echo "Job 'nuget-consume-test' did not succeed (${{ needs.nuget-consume-test.result }}); refusing to pass." + exit 1 + fi diff --git a/WORKFLOW.md b/WORKFLOW.md index e6a42ae38..da050bcef 100644 --- a/WORKFLOW.md +++ b/WORKFLOW.md @@ -144,6 +144,7 @@ The required behaviors, organized by domain. Each is a **MUST**, and its `Output - **D1.4 Workflow-file changes are not smoke-built.** Input: a PR changing only `.github/workflows/**`. Output: the paths-filter marks no target, so smoke-build skips. An inclusion list satisfying D1.1 reaches this by leaving workflow paths out of every target's entry. *Implication: a workflow-only change is not smoke-built, but actionlint still validates it in CI.* - **D1.5 One required aggregator gates merge.** Input: any PR. Output: a single aggregator job must **succeed**. It must run under `if: always()`, so a failed or skipped dependency cannot skip the gate itself. It must also `needs:` the validation job, and the `changes` and `smoke-build` jobs too wherever the repo has a smoke build. It must treat a **skipped** smoke build as pass, and **block** on `failure`/`cancelled`. Its name is ruleset-bound: the job `name:` and the ruleset `context:` are the same string and MUST be renamed together, never independently. The workflow holding it MUST trigger on `pull_request`. A gate without a `pull_request` trigger never runs the validator's pull-request-only steps, the prose gate among them. A workflow any other event also triggers yields that name only when `github.event_name == 'pull_request'`, through an expression `name:`. Otherwise a dispatch or push run on a PR's head posts the required context without the PR run's gates. *Prevents: a paths-filter error letting a target-changing PR merge unbuilt.* - **D1.6 Coverage is reported to Codecov (C# and Python).** Input: a C# or Python repo that has tests for that type. Output: the validation job runs those tests under coverage collection, and a `codecov/codecov-action` step uploads the report. The collection is `dotnet test --coverage --coverage-output-format cobertura --results-directory ./coverage`, leaving `--coverage-output` unset so each test project writes its own report rather than overwriting a shared one. A bare call resolves one workspace from the working directory, so it fails at a root holding none or more than one. Unless the repository root holds exactly one solution or project, the hub's validator therefore runs the collection once per tracked `*Tests*.csproj` with `--project`. It names no solution in that case, since a solution holding no test project fails the run. Or it is `pytest --cov-report=xml` in a Python directory with its own `uv.lock` or `requirements*.txt`, whose own `pyproject.toml` selects what to measure. Or it is `coverage run -m unittest discover -s tests` then `coverage xml` in a `lint-only` one. The upload is **best-effort** (`continue-on-error` and/or `fail_ci_if_error: false`), so a Codecov outage or an absent token never reds the gate. Each leg **fails its test step when the run wrote no report**. The reason is that the best-effort upload reads a missing report exactly as it reads a healthy run. A second reason is that, on the Python leg, `--cov-report=xml` alone selects nothing to measure. The C# leg renames each report to `coverage-.cobertura.xml` before the upload step reads the directory, since `codecov-cli`'s own finder does not match the default name. A repo owning its validator rather than calling the hub's owes that rename itself. `CODECOV_TOKEN` lives in the repo's **actions** and **dependabot** secret stores. The token is in the second because a run triggered by a Dependabot pull request reads the Dependabot store. Without the token there, the upload would otherwise skip silently on every bot pull request. A caller reaching the reusable validator across repositories names the secret it passes (`secrets:` with `CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}`). It does so on its pull request path and its publisher path alike. That is because `secrets: inherit` is documented for a caller in the same organization or enterprise, which a personal account is not. A call by local path stays inside one repository, where the caller's own store is the one the callee reads. So `secrets: inherit` is available there instead of naming each secret. The repo ships a **`.codecov.yml`** at the repository root. It sets the project and patch statuses to **`informational: true`**, so a coverage delta never gates a pull request. A repo whose quality bar requires a threshold may turn that off. The same file excludes intentionally-untested, non-shipped code (an example or benchmark project) from the denominator via `ignore`. Codecov reads its configuration under several names, but `.codecov.yml` is the only one the fleet accepts. So a copy under any other name is drift to rename. Coverage output is a build artifact, so `.gitignore` excludes it. The C# invocation runs under **Microsoft.Testing.Platform**, and the runner declaration, package references, and version floor an MTP-based test project needs are `CODESTYLE.md`'s .NET side. The Python invocation needs **`pytest-cov`** and a coverage selector, which are `CODESTYLE.md`'s Python side. A Python directory declared in the validator's `python-directories` input owes a `tests/` suite whatever its profile, so the validator fails one that has none. N/A for a repo carrying no tests for that type. *Prevents: coverage silently going unreported, and a coverage regression blocking an unrelated pull request.* +- **D1.7 A built NuGet package is consumed before it publishes.** Input: a repo whose `build-nuget` job runs the hub's default leaf, in a smoke run or a publish run alike. Output: after the leaf packs, the job restores, builds, and runs a throwaway console project against that exact `.nupkg`. It does so once per target framework the project declares. Each consumer lives outside the checkout, so the caller's `global.json` and `Directory.Build.props` do not apply. Its `nuget.config` resolves the package ID, and the ID of each sibling package in the folder holding the build output, only from that folder. Every other ID resolves from nuget.org. Its package cache is its own, so neither a cached nor a published copy can stand in for the artifact under test. The consumer loads the package assembly and calls `GetExportedTypes()`. The check asserts from `obj/project.assets.json` that the package resolved from the `lib//` folder of the consumer's own framework. It also asserts that the loaded assembly's `TargetFrameworkAttribute` matches that folder. A `netstandard` framework is consumed under the SDK line `global.json` selects, or the newest declared line where there is none. It is asserted against the folder it resolved. A framework the check does not consume is reported skipped. Examples are .NET Framework, `netcoreapp3.1`, and a platform-specific `netX.Y-windows`. The attribute row of a `netstandard` consumer resolving such a folder is skipped too. Four static assertions join them. The package's `lib//` folders equal the declared frameworks. The nuspec `` equals the build version. The nuspec holds a dependency group per framework. A symbol package exists where the project enables symbols. Every declared `netX.Y` and `netstandard` framework is consumed and reported with one summary row per assertion. A failed step ends that framework's rows rather than the run. The job fails at the end if any failed. The check covers a library package, whose assemblies sit under `lib//`. The check uploads nothing, so it honors D1.3. It runs inside the build job, so a failure blocks the publish job that `needs:` that build. A caller's own `build-nuget` hook replaces the whole leaf and is outside the check. A caller's own `.github/actions/package-consume/action.yml` runs once after the default check. It receives the declared frameworks as JSON beside the package ID, version, and package folder. *Prevents: a defect that exists only in the packed form shipping. One example is one target framework's assembly packed under every `lib//` folder while the tests, which reach the library through a project reference, stay green.* ### D2 - Input/State Validation at Entry @@ -223,11 +224,13 @@ Assert the structural fact each *applicable* D-guarantee implies, and record **p Most of the evidence is in the workflow files and the composite actions they reach. Where a guarantee's evidence lies outside them, in practice it lies in one of these places. They are the repo's branch ruleset, its Actions and Dependabot secret names, a workflow the repo only calls, or a project or dependency file. They also include a committed file such as `version.json`, `.github/dependabot.yml`, `global.json`, `.codecov.yml`, `.gitignore`, or `.editorconfig`. +D1.7 is read in the build job. A step after the default leaf plans the declared frameworks, then the `dotnet-sdk` action installs those runtime lines, then the consume check runs. None of them uploads. + Cite what each verdict rests on. That is `file:line` for a file in the audited repo. It is the evidence's own name where a setting, a ruleset, or a secret name rather than a file is the evidence. Where the guarantee binds a workflow or composite action the audited repo only reaches, it is `/@` plus the `file:line` in that repo. The callee is read at the SHA the caller pins. An **N/A** verdict names the absent construct instead, there being no line to cite. ### 5B. End-to-End Trace Scenarios (No Execution, Deterministic from the YAML) -For each *applicable* scenario, evaluate every job's `if:`/`needs:` against the inputs. Emit the predicted **run/skip + version + release + artifact-end-state** table, then compare to the expected. A scenario governing a construct the repo does not contain is N/A, per `WORKFLOW.md` section 1, and an absent trigger is such a construct. Each scenario's trigger belongs to one workflow, so read that workflow's own `on:` block rather than the repo's type. For S1 to S4 the block is the pull request workflow's, and for S5 to S10 and S14 the publisher's. For S11 the block is the upstream tracker's, and for S12 and S13 the deploy workflow's. A publisher carrying only `workflow_dispatch` therefore records S5, S6 and S9 N/A, their push and schedule paths never firing there. A repo with no publisher lacks a construct every repo owes. So S7, S8, S10 and S14 fail there, and none is excluded from the verdict. S5, S6 and S9 turn on the `on:` block that publisher has yet to state, so each is judged once it lands. A publisher whose schedule never publishes, per D4.1, records the schedule paths of S7 and S9 N/A as well. Where a scenario's path runs through a workflow or composite action the repo only **calls**, trace that callee as the repo reaches it. Read it at the SHA the caller pins rather than at the callee's current default branch, which is the same evidence rule 5A states. Predicting from the callee's `main` predicts a table for YAML the audited repo never runs. A self-repository (`$/`) call or a job-level local (`./`) reusable-workflow call carries no pin of its own. It resolves at the calling workflow file's commit, so it is traced at that file's own commit. That commit is the SHA fixed by the pin that reached that file. Where that file is one of the audited repository's own workflows, it is the audited commit instead. A local (`./`) action reference carries no pin either, but it resolves against whatever the job checked out. So it is traced at that checkout's commit. That is the caller's commit where a reusable workflow called from another repository checks out its caller. Minimum set: +For each *applicable* scenario, evaluate every job's `if:`/`needs:` against the inputs. Emit the predicted **run/skip + version + release + artifact-end-state** table, then compare to the expected. A scenario governing a construct the repo does not contain is N/A, per `WORKFLOW.md` section 1, and an absent trigger is such a construct. Each scenario's trigger belongs to one workflow, so read that workflow's own `on:` block rather than the repo's type. For S1 to S4 the block is the pull request workflow's. For S5 to S10 and S14 it is the publisher's. For S15 it is whichever workflow reaches the `build-nuget` job. For S11 the block is the upstream tracker's, and for S12 and S13 the deploy workflow's. A publisher carrying only `workflow_dispatch` therefore records S5, S6 and S9 N/A, their push and schedule paths never firing there. A repo with no publisher lacks a construct every repo owes. So S7, S8, S10 and S14 fail there, and none is excluded from the verdict. S5, S6 and S9 turn on the `on:` block that publisher has yet to state, so each is judged once it lands. A publisher whose schedule never publishes, per D4.1, records the schedule paths of S7 and S9 N/A as well. Where a scenario's path runs through a workflow or composite action the repo only **calls**, trace that callee as the repo reaches it. Read it at the SHA the caller pins rather than at the callee's current default branch, which is the same evidence rule 5A states. Predicting from the callee's `main` predicts a table for YAML the audited repo never runs. A self-repository (`$/`) call or a job-level local (`./`) reusable-workflow call carries no pin of its own. It resolves at the calling workflow file's commit, so it is traced at that file's own commit. That commit is the SHA fixed by the pin that reached that file. Where that file is one of the audited repository's own workflows, it is the audited commit instead. A local (`./`) action reference carries no pin either, but it resolves against whatever the job checked out. So it is traced at that checkout's commit. That is the caller's commit where a reusable workflow called from another repository checks out its caller. Minimum set: | # | Input | Expected output | Exercises | | --- | --- | --- | --- | @@ -245,6 +248,7 @@ For each *applicable* scenario, evaluate every job's `if:`/`needs:` against the | S12 | deploy dispatch naming an environment | the ref gate runs **first**, allowing production from the default branch only and any ref to a non-production environment. Validation runs, and the callee re-asserts the environment name. A release installs under its own id, and the pointer flips as a separate step. Retention is bounded by whichever of the D5.6 shapes the repo uses. So a deploy whose credential can observe the destination asserts the count converged, and one confined write-only leaves it to the host. The live check asserts the environment and the release id, waiting out the reload, then the URL contract. **No tag and no release are created** | D2.1, D4.6, D5.6 | | S13 | deploy dispatch of a production environment from a non-default ref | **fails fast**, before anything is installed or written | D2.1 | | S14 | publish whose branch head gained different `.github/workflows` content after the build began | every update since a release bot's push or merge: release-create **skipped** and the publisher dispatched on the branch. In that case this run ends **cancelled** with its package publish jobs skipped (a Docker image already pushed). The dispatched run releases the head, queueing behind this run only where the head's publisher evaluates this run's group for a dispatch. A push landing after the branch is confirmed unmoved and before the dispatch is released as if it were such an update. That is an accepted, bounded limit per D4.7. Any other update: the step **fails**, nothing is released or dispatched | D4.1, D4.2, D4.5, D4.7 | +| S15 | a smoke or publish run whose `build-nuget` job runs the hub default leaf, for a project declaring `net10.0;net11.0`. The package holds one framework's assembly under both `lib/` folders | the job plans both runtime lines, installs them, and consumes the package once per framework. It **fails** on the `TargetFrameworkAttribute` of the `lib/` folder holding the other framework's assembly, after reporting every other row. A correct package **passes**. The check uploads nothing in either run. A publish run's leaf has uploaded its artifacts already, and a failure leaves them to their retention and the dependent publish job **skipped** | D1.3, D1.7 | ### 5C. Live Probe (Where Warranted) @@ -281,7 +285,7 @@ The table files each scenario in section 5B's table under exactly one row, which | Construct the repo contains | Scenarios it reaches | | --- | --- | | A pull request workflow with a validation job and the required aggregator | S2, S3 | -| A build target: a `changes` filter entry, a smoke build, and a leaf that builds it | S1, S4 | +| A build target: a `changes` filter entry, a smoke build, and a leaf that builds it | S1, S4, and S15 for the hub default NuGet leaf | | A publisher, meaning a workflow that cuts the release | S7, S8, S10, S14, plus S5 and S6 wherever its own `on:` admits a push, and S9 wherever it admits a push or a schedule | | An upstream-version tracker and its merge-bot | S11 | | A deploy workflow targeting a filesystem on a host the project owns | S12, S13 | @@ -291,7 +295,7 @@ The rows below say which constructs a type brings with it. Read the repository f What each type adds beyond that, and how its leaf behaves, is below. - **`dotnet-publish`.** The target runs a sequential `dotnet publish` runtime loop inside one composite-action job. Configuration is Release on the default branch and Debug otherwise. A non-smoke run builds the full runtime set, archives the combined output as a `.7z`, and uploads it as `release-asset--dotnet-publish`. The archive is named from the project file stem unless `dotnet_publish_asset_name` overrides it. A smoke run builds a **strict, non-empty subset** of that runtime set and skips the archive and upload steps, so it uploads nothing. S1 smoke-builds that subset after a .NET project change. S7 attaches the 7z from a non-smoke run. The non-default leg sets `prerelease=true`, and the default leg sets `prerelease=false`. GitHub marks the stable default release "Latest" automatically. -- **`nuget`.** The leaf uploads both `release-asset--nuget` and `nuget-build-` on a non-smoke run and pushes nothing. A separate `publish-nuget` job in the repo's own publisher consumes the second and runs `dotnet nuget push *.nupkg --skip-duplicate`. It then deletes that artifact under the download step's own success (D5.2). Section 3's `Output Seam by Destination` says why the push sits there rather than in the leaf. Configuration is Release on the default branch, Debug otherwise. The release-asset `.7z` carries the packages alone, never the loose build output, since each package already holds every target framework's build under its own `lib//`. Where symbols are enabled (`snupkg`), the push auto-carries the paired `.snupkg` to NuGet.org's symbol server and the release-asset `.7z` also contains it, a triple surface. NuGet.org derives `isPrerelease` from the SemVer2 `-g` suffix (the workflow sets no such flag). Test: S7 non-default leg publishes a prerelease package + asset, default a stable. S9 re-run is a server-side `--skip-duplicate` no-op. 5C: query NuGet.org for both versions and the symbol package. +- **`nuget`.** The leaf uploads both `release-asset--nuget` and `nuget-build-` on a non-smoke run and pushes nothing. A separate `publish-nuget` job in the repo's own publisher consumes the second and runs `dotnet nuget push *.nupkg --skip-duplicate`. It then deletes that artifact under the download step's own success (D5.2). Section 3's `Output Seam by Destination` says why the push sits there rather than in the leaf. Configuration is Release on the default branch, Debug otherwise. The default leaf is followed by the D1.7 package consume check in smoke and publish runs alike. A caller's own `build-nuget` hook is outside it. The release-asset `.7z` carries the packages alone, never the loose build output, since each package already holds every target framework's build under its own `lib//`. Where symbols are enabled (`snupkg`), the push auto-carries the paired `.snupkg` to NuGet.org's symbol server and the release-asset `.7z` also contains it, a triple surface. NuGet.org derives `isPrerelease` from the SemVer2 `-g` suffix (the workflow sets no such flag). Test: S15 consumes the package per framework. S7 non-default leg publishes a prerelease package + asset, default a stable. S9 re-run is a server-side `--skip-duplicate` no-op. 5C: query NuGet.org for both versions and the symbol package. - **`pypi`.** The leaf builds and uploads `pypi-build-`. A **separate** `publish-pypi` job (with `environment: pypi`, `id-token: write`, `actions: write`) does the OIDC Trusted-Publishing upload with `skip-existing: true`. It then **consume-then-deletes** the build artifact under the download step's own success (D5.2). So on S9 the build artifact is deleted even though the `release-asset-*` delete is skipped. The version is the `X.Y.Z` core of `SemVer2` with `.dev0` appended on `develop` only, per D3.4. PyPI contributes no `release-asset-*`. A PyPI-only repo sets `expect_release_assets: false` at the caller. Test: S7 default leg publishes a release, non-default a `.dev0`. S9 is a `skip-existing` no-op. 5C inspects the `dist/*` filenames and the compute-version log. - **`docker`.** The leaf pushes the default branch multi-arch (amd64+arm64) and any other branch `amd64`-only, with a per-branch registry buildcache. A single-image repo caches to `:buildcache-`. A multi-image repo varies the cache **repository** rather than the tag, `:buildcache-` for each image, since the tag alone cannot distinguish two images. `cache-to` writes only the built branch and only on push, and `cache-from` reads both branches. It contributes no `release-asset-*`, so a Docker-only repo's caller passes `expect_release_assets: false`. The readme job (`peter-evans/dockerhub-description`, `DOCKER_HUB_ACCESS_TOKEN`) runs **only** when the default branch publishes, whether called directly or reached through the hub-hosted `publish-docker-readme-task.yml`. Where the Docker Hub overview differs from the project README, the repo publishes a `Docker/README.md` through that task, the Hub description being size-limited. The docker-readme task validates its two mutually-exclusive input sources, `repositories` against `manifest`+`manifest-jq`. It defaults to the calling repository where neither is supplied. A multi-image repo derives its publish matrix from the manifest. Docker **always re-pushes** the image, independently of a skipped release-create (S9). The tests that follow assume the default tag matrix, which a caller-supplied `matrix` or `docker-prepare` hook replaces. Test: S7 default leg pushes `latest` + the version tag and updates the readme. Non-default pushes `develop` + the version tag (amd64 only). S9 still re-pushes. 5C Docker probe needs `DOCKER_HUB_*` secrets and same-repo (not fork) runs. - **`library` (a worked example, not a fleet type).** No such leaf ships, so this row walks D6.4's add-a-target procedure rather than an existing shape. The target is a single new leaf that validates, zips, and uploads `release-asset--library` (`retention-days: 1` per D5.4, upload gated on smoke being false per D1.3). Adding it means a new `enable_library` input, and a `build-library` job and its `github-release` and `build-docker` `needs:` entries, in the release task. In the PR workflow it means a `library` paths-filter entry, `changes` output, and `smoke-build` enable-forward. Without that last one, D1.1 never smoke-builds the library. In the publisher, it means the `enable_library` value the publisher passes, and the library's paths in its `on.push.paths` where it carries a `push` trigger. **Only a repo that owns its release task can make the release-task half of that edit.** The hub-hosted release task declares a closed input set, and a call passing an input it does not declare fails. So a repo calling it sets `enable_release_asset` instead and carries the leaf as its `build-release-asset` hook. The hook writes the zip, and the task uploads it under `release-asset--build-release-asset`, skipping the upload on a smoke run. Keep `expect_release_assets: true` (it has a file target, unlike Docker). The caller's own validation job is replaced by a type-appropriate validator only where the reusable one cannot express this repo's validation. The aggregator is then re-pointed to the replacement (D1.2). `smoke-build` keeps `needs: [changes]`, as D1.2 has it. `version.json` and the NBGV `get-version` **job** are retained (they own the tag). Test: S1 smoke runs validate+zip and uploads nothing. S7 attaches the zip, prerelease on the non-default leg. S9 on a push re-run skips release-create and the asset-delete (the existing zip is untouched, no registry push). A `workflow_dispatch` re-run, by contrast, is D4.4's refresh case rather than S9's, re-uploading then re-deleting the asset. diff --git a/docs/reusable-workflows.md b/docs/reusable-workflows.md index 2eaa8234f..d3608932a 100644 --- a/docs/reusable-workflows.md +++ b/docs/reusable-workflows.md @@ -56,7 +56,7 @@ A workflow whose job graph is identical across repos of a type is reached, not c ### The Hook Contract -A hook receives the fixed inputs [WORKFLOW.md "Reusable-Task Parameter Contract"][workflow-reusable-task-parameter-contract] gives a leaf today. Those are `ref`, `branch`, `smoke` where relevant, and the NBGV version outputs where a build needs them. It reports back through step outputs and, for a release target, through the existing artifact seam, `release-asset--`, which the hub's `github-release` job collects by pattern. Each task finds a hook by its `action.yml` alone, so a hook named `action.yaml` is never run. The `install-test-deps` hook is an exception, taking `leg` and `directories` inputs and reporting nothing back. It may also run a check that needs that leg's environment. A failure there fails the leg's `unit-test` job before its Python tests run. The `pre-test` hook is another, taking no inputs and reporting nothing back. Each `unit-test` leg runs it before the .NET SDK setup, where a .NET test project exists and the caller carries the hook. So a system tool a .NET test shells out to is installed before those tests run. The `build-release-asset` hook is another, writing its files into the `output-directory` it receives, on a smoke run too, and leaving the upload to the task. The task accepts only regular files at that directory's top level and refuses a subdirectory, a symlink, or a dot-prefixed name. A package hook also uploads the artifact its publish job consumes: a NuGet hook uploads `nuget-build-` as well as its `release-asset-*`. A PyPI hook uploads `pypi-build-` and no release asset at all. A NuGet or PyPI hook has to carry that exact package-artifact name or its publish job finds nothing. The `validate` and `resolve-upstream` hooks can also take one string from their caller. `validate-task.yml` and `check-upstream-version-task.yml` each declare an optional `hook-input` input. Each passes a non-empty value on to its hook's own `hook-input` input. The task passes it from a step of its own, run only when the caller sets it. So a caller passing none runs a hook declaring no such input exactly as before. A caller that sets it needs a hook declaring `hook-input` as an optional input. The caller defines what the value means. It can name which of two callers runs the hook, or carry a change-gate result an expensive check skips on. The hub's no-op `validate-default` never receives it. A hook may use marketplace actions, which is the reason a hook is a composite action rather than a script. A toolchain setup, a Docker build, or a coverage upload is a `uses:` step, and a shell script cannot carry one. Action pins inside a hook follow the SHA-pinning rule like any other workflow content, and Dependabot bumps them in the repo that carries the hook. A hook runs with no persisted git credential, since every checkout ahead of a hook sets `persist-credentials: false`. A hook that runs git against the remote therefore passes its own credential to that call. +A hook receives the fixed inputs [WORKFLOW.md "Reusable-Task Parameter Contract"][workflow-reusable-task-parameter-contract] gives a leaf today. Those are `ref`, `branch`, `smoke` where relevant, and the NBGV version outputs where a build needs them. It reports back through step outputs and, for a release target, through the existing artifact seam, `release-asset--`, which the hub's `github-release` job collects by pattern. Each task finds a hook by its `action.yml` alone, so a hook named `action.yaml` is never run. The `install-test-deps` hook is an exception, taking `leg` and `directories` inputs and reporting nothing back. It may also run a check that needs that leg's environment. A failure there fails the leg's `unit-test` job before its Python tests run. The `pre-test` hook is another, taking no inputs and reporting nothing back. Each `unit-test` leg runs it before the .NET SDK setup, where a .NET test project exists and the caller carries the hook. So a system tool a .NET test shells out to is installed before those tests run. The `build-release-asset` hook is another, writing its files into the `output-directory` it receives, on a smoke run too, and leaving the upload to the task. The task accepts only regular files at that directory's top level and refuses a subdirectory, a symlink, or a dot-prefixed name. A package hook also uploads the artifact its publish job consumes: a NuGet hook uploads `nuget-build-` as well as its `release-asset-*`. A PyPI hook uploads `pypi-build-` and no release asset at all. A NuGet or PyPI hook has to carry that exact package-artifact name or its publish job finds nothing. The `package-consume` hook is another, optional and taking `frameworks`, `package-id`, `version`, and `feed-dir` inputs while reporting nothing back. `build-nuget` runs it once after the hub default's own package consume check, in smoke and publish runs alike. So the hook loops over the JSON `frameworks` array itself. A caller carrying its own `build-nuget` hook gets neither check, since that hook's output location is unknown to the hub. The `validate` and `resolve-upstream` hooks can also take one string from their caller. `validate-task.yml` and `check-upstream-version-task.yml` each declare an optional `hook-input` input. Each passes a non-empty value on to its hook's own `hook-input` input. The task passes it from a step of its own, run only when the caller sets it. So a caller passing none runs a hook declaring no such input exactly as before. A caller that sets it needs a hook declaring `hook-input` as an optional input. The caller defines what the value means. It can name which of two callers runs the hook, or carry a change-gate result an expensive check skips on. The hub's no-op `validate-default` never receives it. A hook may use marketplace actions, which is the reason a hook is a composite action rather than a script. A toolchain setup, a Docker build, or a coverage upload is a `uses:` step, and a shell script cannot carry one. Action pins inside a hook follow the SHA-pinning rule like any other workflow content, and Dependabot bumps them in the repo that carries the hook. A hook runs with no persisted git credential, since every checkout ahead of a hook sets `persist-credentials: false`. A hook that runs git against the remote therefore passes its own credential to that call. ### Pinning @@ -89,7 +89,7 @@ The target set. A row exists once its hub task ships, and until then the row is | `merge-bot-task.yml` | none, extra bot rules are a `with:` input | not applicable | | `validate-task.yml` | `validate` (a repo's own domain checks, beyond the fleet doc-lint block and the generic unit-test job), `install-test-deps` (a `test-matrix` leg's dependency install and per-leg checks). Also `pre-test`, for system tools the .NET tests need | no-op for `validate`, none for `install-test-deps`, which is required where `test-matrix` or `test-matrix-file` is set. None for `pre-test` | | `get-version-task.yml`, `publish-plan-task.yml` | none | not applicable | -| `build-release-task.yml` | `dotnet-publish`, `build-nuget`, `build-pypi`, `build-release-asset` | `dotnet-publish-default`, `nuget-build-default`, `pypi-build-default`, none for `build-release-asset`, which is required where `enable_release_asset` is set | +| `build-release-task.yml` | `dotnet-publish`, `build-nuget`, `build-pypi`, `build-release-asset` | `dotnet-publish-default`, `nuget-build-default` followed by `package-consume-nuget`, `pypi-build-default`, none for `build-release-asset`, which is required where `enable_release_asset` is set | | `build-docker-task.yml` | `docker-prepare` (extra tags, build-args, matrix), `docker-build-base` | vanilla single-target from `image`, base build required when `build-base` | | `publish-docker-readme-task.yml` | `docker-readme-transform` | publish `Docker/README.md` or `README.md` as-is | | `check-upstream-version-task.yml` | `resolve-upstream` | none, required | diff --git a/pyproject.toml b/pyproject.toml index da4fa33eb..32487808f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -15,7 +15,7 @@ python_version = "3.13" # That is because mypy's own flow analysis does not narrow it away. platform = "linux" files = ["spec", "host-setup", "scripts", "tests"] -mypy_path = [".github/actions/prose-gate", ".github/actions/python-directories", ".github/actions/repo-gate"] +mypy_path = [".github/actions/package-consume-nuget", ".github/actions/prose-gate", ".github/actions/python-directories", ".github/actions/repo-gate"] exclude = 'scripts/(prose_lint|repo_gate)\.py' # A script declaring a library inline runs through uv. diff --git a/scripts/package_consume_nuget_selftest.py b/scripts/package_consume_nuget_selftest.py new file mode 100755 index 000000000..993e904d7 --- /dev/null +++ b/scripts/package_consume_nuget_selftest.py @@ -0,0 +1,198 @@ +#!/usr/bin/env python3 +"""Prove the NuGet package consume check passes a good package and fails a mispacked one. + +The hub holds no .NET project, so this builds a constructed class library in a temporary directory. +The library multi-targets net10.0 and net11.0, and the script packs it and runs the action's script against the result. +The first run must pass. +The later runs rewrite the package so one framework's assembly sits under the other's `lib/` folder, and each must fail. +The net11.0 assembly under `lib/net10.0` is the shape that once shipped. + +Needs the .NET 10.0 and 11.0 SDKs and runtimes. +Exits 1 when any run does not behave as expected. +""" + +from __future__ import annotations + +import argparse +import contextlib +import os +import shutil +import signal +import subprocess +import sys +import tempfile +import zipfile +from collections.abc import Sequence +from pathlib import Path +from types import FrameType + +from run_deadline import run_with_deadline + +ACTION = Path(__file__).resolve().parents[1] / ".github/actions/package-consume-nuget" +PACKAGE_ID = "Contoso.Widget" +VERSION = "1.2.3" +FRAMEWORKS = ("net10.0", "net11.0") +CSPROJ = f""" + + {";".join(FRAMEWORKS)} + true + snupkg + {PACKAGE_ID} + false + + +""" +SOURCE = 'namespace Contoso.Widget;\n\npublic sealed class Widget\n{\n public string Name => "widget";\n}\n' + + +def run(command: Sequence[str], cwd: Path, env: dict[str, str] | None = None) -> tuple[int, str]: + result = run_with_deadline( + list(command), 900, cwd=cwd, env=env, text=True, encoding="utf-8", stderr=subprocess.STDOUT + ) + return result.returncode, result.stdout + + +def consume(project: Path, feed: Path, work: Path) -> tuple[int, str]: + env = { + **os.environ, + "PACKAGE_CONSUME_MODE": "check", + "BRANCH": "develop", + "PROJECT_FILE": str(project), + "SEMVER2": VERSION, + "PACKAGE_DIR": str(feed), + "WORK_DIR": str(work), + } + env.pop("GITHUB_STEP_SUMMARY", None) + work.mkdir(parents=True) + return run([sys.executable, str(ACTION / "package_consume_nuget.py")], work, env) + + +def mispack(feed: Path, target: Path, source: str, destination: str) -> None: + """Copy the feed with one framework's assembly written over another's lib folder, the bug the check exists for.""" + target.mkdir() + for path in feed.iterdir(): + if not path.name.endswith(".nupkg") or path.name.endswith(".symbols.nupkg"): + shutil.copy2(path, target / path.name) + continue + with zipfile.ZipFile(path) as archive, zipfile.ZipFile(target / path.name, "w") as out: + replacement = archive.read(f"lib/{source}/{PACKAGE_ID}.dll") + for item in archive.infolist(): + data = ( + replacement + if item.filename == f"lib/{destination}/{PACKAGE_ID}.dll" + else archive.read(item) + ) + out.writestr(item, data) + + +def verdicts(output: str) -> list[str]: + return [line for line in output.splitlines() if line.startswith(("PASS ", "FAIL "))] + + +def main(argv: Sequence[str] = ()) -> int: + argparse.ArgumentParser(description=(__doc__ or "").splitlines()[0]).parse_args(list(argv)) + with tempfile.TemporaryDirectory(prefix="package-consume-selftest.") as name: + root = Path(name) + library = root / "library" + library.mkdir() + project = library / f"{PACKAGE_ID}.csproj" + project.write_text(CSPROJ, encoding="utf-8") + (library / "Widget.cs").write_text(SOURCE, encoding="utf-8") + feed = root / "feed" + code, output = run( + [ + "dotnet", + "pack", + str(project), + "-c", + "Release", + "-o", + str(feed), + f"-p:Version={VERSION}", + "-nologo", + ], + library, + {**os.environ, "MSBUILDDISABLENODEREUSE": "1"}, + ) + if code != 0: + print(output) + print("Packing the constructed library failed.") + return 1 + failures = 0 + code, output = consume(project, feed, root / "work-good") + print("Good package:") + print("\n".join(verdicts(output))) + if code != 0 or any(line.startswith("FAIL ") for line in verdicts(output)): + print(output) + print("EXPECTED PASS and the check failed.") + failures += 1 + # The first shape is the one that shipped. + # The second loads cleanly, so only the attribute assertion sees it. + for source, destination in (("net11.0", "net10.0"), ("net10.0", "net11.0")): + bad_feed = root / f"feed-{source}-under-{destination}" + mispack(feed, bad_feed, source, destination) + code, output = consume(project, bad_feed, root / f"work-{source}-under-{destination}") + print(f"Mispacked package ({source} assembly under lib/{destination}):") + print("\n".join(verdicts(output))) + tfm_failed = any( + line.startswith(f"FAIL [{destination}] TargetFrameworkAttribute") + for line in verdicts(output) + ) + if code == 0 or not tfm_failed: + print(output) + print(f"EXPECTED FAIL on the {destination} framework assertion and it did not.") + failures += 1 + print("SELF-TEST " + ("FAILED" if failures else "OK")) + return 1 if failures else 0 + + +received: list[int] = [] + + +def on_signal(signum: int, frame: FrameType | None) -> None: + """Record the signal and raise KeyboardInterrupt, so every signal unwinds one path. + + A later signal is passed over, since it would cut the unwinding short. + A later signal can start inside this handler, so a call from this frame returns too. + """ + if received or (frame is not None and frame.f_code is on_signal.__code__): + return + received.append(signum) + raise KeyboardInterrupt + + +def interrupted() -> int: + """Name the recorded signal, and return it as the status the caller re-raises.""" + signum = signal.Signals(received[0] if received else signal.SIGINT) + print(f"{Path(__file__).name}: interrupted by {signum.name}.", file=sys.stderr) + return signum + + +def reraise(signum: signal.Signals) -> None: + """End this process by `signum`, so a caller sees the signal rather than an exit status.""" + with contextlib.suppress(OSError): + sys.stdout.flush() + sys.stderr.flush() + if sys.platform == "win32": + sys.exit(130) + signal.signal(signum, signal.SIG_DFL) + os.kill(os.getpid(), signum) + sys.exit(128 + signum) + + +def entry(argv: Sequence[str]) -> int: + """Run main with one handler for both signals, returning the signal's number where one arrived.""" + signal.signal(signal.SIGTERM, on_signal) + if signal.getsignal(signal.SIGINT) is signal.default_int_handler: + signal.signal(signal.SIGINT, on_signal) + try: + return main(argv) + except KeyboardInterrupt: + return interrupted() + + +if __name__ == "__main__": + status = entry(sys.argv[1:]) + if received: + reraise(signal.Signals(received[0])) + sys.exit(status) diff --git a/tests/test_cli_usage.py b/tests/test_cli_usage.py index 22fb44f57..6f74bdd47 100755 --- a/tests/test_cli_usage.py +++ b/tests/test_cli_usage.py @@ -106,6 +106,7 @@ NO_REQUIRED_ARGUMENT = frozenset( { + ".github/actions/package-consume-nuget/package_consume_nuget.py", ".github/actions/prose-gate/prose_lint.py", ".github/actions/python-directories/python_directories.py", ".github/actions/repo-gate/repo_gate.py", @@ -137,6 +138,7 @@ "scripts/docker_lint.py", "scripts/enable_hooks.py", "scripts/host_gate.py", + "scripts/package_consume_nuget_selftest.py", "scripts/pr_review_copilot.py", "scripts/prose_lint.py", "scripts/repo_gate.py", diff --git a/tests/test_package_consume_nuget.py b/tests/test_package_consume_nuget.py new file mode 100755 index 000000000..8a59909fe --- /dev/null +++ b/tests/test_package_consume_nuget.py @@ -0,0 +1,330 @@ +#!/usr/bin/env python3 +"""Drive the NuGet package consume check's pure logic against constructed packages. + +Nothing here runs dotnet. The packages are zips holding only the entries the static shape check +reads, and the end-to-end proof is the hub's own self-test job in test-pull-request.yml. + +Run as `python3 tests/test_package_consume_nuget.py`, or under `python3 -m unittest discover -s tests`. +""" + +from __future__ import annotations + +import contextlib +import io +import re +import sys +import tempfile +import unittest +import zipfile +from pathlib import Path +from unittest import mock + +import yaml + +sys.path.insert( + 0, str(Path(__file__).resolve().parents[1] / ".github/actions/package-consume-nuget") +) +import package_consume_nuget as pcn + +NUSPEC = """ + + + Contoso.Widget + {version} + {groups} + + +""" + + +def build_package( + directory: Path, + folders: tuple[str, ...] = ("net10.0", "net11.0"), + version: str = "1.2.3", + groups: tuple[str, ...] = ("net10.0", "net11.0"), + symbols: bool = True, +) -> Path: + package = directory / f"Contoso.Widget.{version}.nupkg" + group_xml = "".join(f'' for g in groups) + with zipfile.ZipFile(package, "w") as archive: + archive.writestr("Contoso.Widget.nuspec", NUSPEC.format(version=version, groups=group_xml)) + for folder in folders: + archive.writestr(f"lib/{folder}/Contoso.Widget.dll", b"dll") + if symbols: + (directory / f"Contoso.Widget.{version}.snupkg").write_bytes(b"symbols") + return package + + +def shape(directory: Path, package: Path, **overrides: object) -> dict[str, bool]: + report = pcn.Report() + arguments: dict[str, object] = { + "frameworks": ["net10.0", "net11.0"], + "version": "1.2.3", + "symbols_expected": True, + "symbol_format": "snupkg", + } + arguments.update(overrides) + with contextlib.redirect_stdout(io.StringIO()): + pcn.static_shape(package, report=report, **arguments) # type: ignore[arg-type] + return {r.check: r.ok for r in report.results} + + +class NormalizeTests(unittest.TestCase): + def test_spellings_meet_at_the_folder_name(self) -> None: + cases = { + "net10.0": "net10.0", + "NET10.0": "net10.0", + ".NETCoreApp,Version=v10.0": "net10.0", + ".NETCoreApp,Version=v3.1": "netcoreapp3.1", + ".NETStandard2.0": "netstandard2.0", + ".NETCoreApp3.1": "netcoreapp3.1", + ".NETStandard,Version=v2.1": "netstandard2.1", + ".NETFramework4.8": "net48", + "net10.0-windows7.0": "net10.0-windows", + "net10.0-windows": "net10.0-windows", + } + for raw, expected in cases.items(): + with self.subTest(raw=raw): + self.assertEqual(pcn.normalize_tfm(raw), expected) + + def test_declared_frameworks_prefers_the_plural_and_drops_duplicates(self) -> None: + self.assertEqual( + pcn.declared_frameworks( + {"TargetFrameworks": "net10.0;net11.0;net10.0", "TargetFramework": ""} + ), + ["net10.0", "net11.0"], + ) + self.assertEqual(pcn.declared_frameworks({"TargetFramework": "net10.0"}), ["net10.0"]) + self.assertEqual(pcn.declared_frameworks({}), []) + + def test_expected_attribute(self) -> None: + self.assertEqual(pcn.expected_attribute("net11.0"), ".NETCoreApp,Version=v11.0") + self.assertEqual(pcn.expected_attribute("netstandard2.0"), ".NETStandard,Version=v2.0") + self.assertIsNone(pcn.expected_attribute("net48")) + + +class PlanTests(unittest.TestCase): + def test_global_line_goes_first_and_the_rest_follow_newest_first(self) -> None: + self.assertEqual(pcn.plan_versions(["net10.0", "net11.0"], "11.0"), ["11.0", "10.0"]) + self.assertEqual(pcn.plan_versions(["net10.0", "net11.0"], "10.0"), ["10.0", "11.0"]) + + def test_a_global_line_the_project_does_not_declare_is_still_installed(self) -> None: + self.assertEqual(pcn.plan_versions(["net10.0"], "11.0"), ["11.0", "10.0"]) + + def test_without_a_global_json_the_newest_declared_line_leads(self) -> None: + self.assertEqual(pcn.plan_versions(["net10.0", "net11.0"], None), ["11.0", "10.0"]) + + def test_nothing_declared_and_no_global_json_leaves_the_fallback_to_the_action(self) -> None: + self.assertEqual(pcn.plan_versions(["netstandard2.0", "net48"], None), []) + + def test_global_json_line_reads_comments_and_missing_versions(self) -> None: + with tempfile.TemporaryDirectory() as name: + path = Path(name) / "global.json" + self.assertIsNone(pcn.global_json_line(path)) + path.write_text( + '// pinned\n{"sdk": {"version": "10.0.404", "rollForward": "latestFeature"}}' + ) + self.assertEqual(pcn.global_json_line(path), "10.0") + path.write_text('{"sdk": {"rollForward": "latestMajor"}}') + self.assertIsNone(pcn.global_json_line(path)) + path.write_text("{ not json") + self.assertIsNone(pcn.global_json_line(path)) + + +class StaticShapeTests(unittest.TestCase): + def test_a_correct_package_passes_every_check(self) -> None: + with tempfile.TemporaryDirectory() as name: + directory = Path(name) + result = shape(directory, build_package(directory)) + self.assertEqual(len(result), 4) + self.assertTrue(all(result.values()), result) + + def test_a_missing_lib_folder_fails(self) -> None: + with tempfile.TemporaryDirectory() as name: + directory = Path(name) + result = shape(directory, build_package(directory, folders=("net10.0",))) + self.assertFalse(result["lib folders equal declared frameworks"]) + + def test_an_extra_lib_folder_fails(self) -> None: + with tempfile.TemporaryDirectory() as name: + directory = Path(name) + result = shape( + directory, build_package(directory, folders=("net10.0", "net11.0", "net9.0")) + ) + self.assertFalse(result["lib folders equal declared frameworks"]) + + def test_a_wrong_nuspec_version_fails_and_build_metadata_is_ignored(self) -> None: + with tempfile.TemporaryDirectory() as name: + directory = Path(name) + package = build_package(directory, version="1.2.4") + self.assertFalse(shape(directory, package)["nuspec version equals the build version"]) + with tempfile.TemporaryDirectory() as name: + directory = Path(name) + package = build_package(directory, version="1.2.3-gabc123") + result = shape(directory, package, version="1.2.3-gabc123+0f0f") + self.assertTrue(result["nuspec version equals the build version"]) + + def test_a_missing_dependency_group_fails(self) -> None: + with tempfile.TemporaryDirectory() as name: + directory = Path(name) + result = shape(directory, build_package(directory, groups=("net10.0",))) + self.assertFalse(result["dependency group per framework"]) + + def test_dependency_groups_in_the_long_spelling_count(self) -> None: + with tempfile.TemporaryDirectory() as name: + directory = Path(name) + package = build_package( + directory, groups=(".NETCoreApp,Version=v10.0", ".NETCoreApp,Version=v11.0") + ) + self.assertTrue(shape(directory, package)["dependency group per framework"]) + + def test_a_missing_symbol_package_fails_only_where_symbols_are_enabled(self) -> None: + with tempfile.TemporaryDirectory() as name: + directory = Path(name) + package = build_package(directory, symbols=False) + self.assertFalse(shape(directory, package)["symbol package exists"]) + (directory / "Contoso.Other.9.9.9.snupkg").write_bytes(b"sibling") + self.assertFalse(shape(directory, package)["symbol package exists"]) + self.assertNotIn( + "symbol package exists", shape(directory, package, symbols_expected=False) + ) + + def test_the_symbol_package_name_follows_the_format(self) -> None: + with tempfile.TemporaryDirectory() as name: + directory = Path(name) + package = build_package(directory) + self.assertFalse( + shape(directory, package, symbol_format="symbols.nupkg")["symbol package exists"] + ) + + +class AssetsTests(unittest.TestCase): + @staticmethod + def assets(folder: str, extra: tuple[str, ...] = ()) -> dict[str, object]: + runtime: dict[str, object] = { + f"lib/{folder}/Contoso.Widget.dll": {}, + **{f"lib/{x}/Contoso.Widget.dll": {} for x in extra}, + } + return { + "targets": { + ".NETCoreApp,Version=v10.0": { + "Contoso.Widget/1.2.3": {"compile": runtime, "runtime": runtime} + } + } + } + + def test_the_resolved_folder_and_assembly_are_read(self) -> None: + self.assertEqual( + pcn.resolved_folder(self.assets("net10.0"), "contoso.widget"), + ("net10.0", ["Contoso.Widget"]), + ) + + def test_an_ambiguous_or_missing_package_is_refused(self) -> None: + with self.assertRaises(ValueError): + pcn.resolved_folder(self.assets("net10.0", ("net11.0",)), "Contoso.Widget") + with self.assertRaises(ValueError): + pcn.resolved_folder(self.assets("net10.0"), "Other.Package") + with self.assertRaises(ValueError): + pcn.resolved_folder({"targets": {}}, "Contoso.Widget") + + +class ReportTests(unittest.TestCase): + def test_a_failure_is_an_escaped_annotation_and_a_table_row(self) -> None: + report = pcn.Report() + buffer = io.StringIO() + with contextlib.redirect_stdout(buffer): + report.add("net10.0", "check", False, "a|b\n::error::forged") + lines = buffer.getvalue().splitlines() + self.assertEqual(len([line for line in lines if line.startswith("::error::")]), 1) + self.assertIn("%0A", lines[1]) + self.assertTrue(report.failed) + self.assertIn("a\\|b", report.table()) + self.assertEqual(len(report.table().splitlines()), 3) + + +class PackageSelectionTests(unittest.TestCase): + def test_a_referenced_project_package_does_not_hide_the_projects_own(self) -> None: + with tempfile.TemporaryDirectory() as name: + directory = Path(name) + own = build_package(directory) + other = directory / "Contoso.Other.1.0.0.nupkg" + with zipfile.ZipFile(other, "w") as archive: + archive.writestr( + "Contoso.Other.nuspec", + NUSPEC.format(version="1.0.0", groups="").replace( + "Contoso.Widget", "Contoso.Other" + ), + ) + self.assertEqual(pcn.find_package(directory, "Contoso.Widget"), own) + with self.assertRaises(SystemExit): + pcn.find_package(directory) + with self.assertRaises(SystemExit): + pcn.find_package(directory, "Contoso.Missing") + + +class InterruptTests(unittest.TestCase): + def setUp(self) -> None: + pcn.received.clear() + self.addCleanup(pcn.received.clear) + + def test_the_first_signal_is_recorded_and_a_later_one_is_passed_over(self) -> None: + with self.assertRaises(KeyboardInterrupt): + pcn.on_signal(15, None) + pcn.on_signal(2, None) + self.assertEqual(pcn.received, [15]) + + def test_an_interrupt_in_main_returns_the_recorded_signal(self) -> None: + def interrupt(_argv: object) -> int: + pcn.received.append(15) + raise KeyboardInterrupt + + with ( + mock.patch.object(pcn, "main", interrupt), + mock.patch.object(pcn.signal, "signal"), + contextlib.redirect_stderr(io.StringIO()) as err, + ): + self.assertEqual(pcn.entry([]), 15) + self.assertIn("interrupted by SIGTERM", err.getvalue()) + + +class WiringTests(unittest.TestCase): + """No hub run reaches the build-nuget job, so the step wiring is held here.""" + + ROOT = Path(__file__).resolve().parents[1] + + def test_the_fallback_line_matches_the_dotnet_sdk_action(self) -> None: + text = (self.ROOT / ".github/actions/dotnet-sdk/action.yml").read_text(encoding="utf-8") + match = re.search(r"fallback=(\d+)\.x", text) + self.assertIsNotNone(match) + assert match is not None + self.assertEqual(match.group(1), pcn.FALLBACK_LINE.split(".")[0]) + + def test_the_build_nuget_job_plans_installs_and_consumes_in_order(self) -> None: + text = (self.ROOT / ".github/workflows/build-release-task.yml").read_text(encoding="utf-8") + job = yaml.safe_load(text)["jobs"]["build-nuget"] + steps = {step["name"]: (index, step) for index, step in enumerate(job["steps"])} + build = steps["Run hub build-nuget default step"] + plan = steps["Plan package consume step"] + install = steps["Setup consumer .NET runtimes step"] + check = steps["Run package consume check step"] + hook = steps["Run caller package-consume hook step"] + self.assertLess(build[0], plan[0]) + self.assertLess(plan[0], install[0]) + self.assertLess(install[0], check[0]) + self.assertLess(check[0], hook[0]) + self.assertEqual(plan[1]["with"]["mode"], "plan") + self.assertEqual(check[1]["with"]["mode"], "check") + self.assertEqual( + install[1]["with"]["versions"], "${{ steps.package-consume-plan.outputs.sdk-versions }}" + ) + for _, step in (plan, install, check): + self.assertEqual(step["if"], build[1]["if"]) + self.assertIn( + "hashFiles('.github/actions/package-consume/action.yml') != ''", hook[1]["if"] + ) + for _, step in (plan, install, check, hook): + self.assertNotIn("upload-artifact", step.get("uses", "")) + + +if __name__ == "__main__": + unittest.main() From 1a8455aa7d866a169ca2cbff5e6bb5b711c26dda Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Thu, 3 Dec 2026 00:08:52 -0800 Subject: [PATCH 2/7] Consume the Built PyPI Package per Python Line Before It Publishes (#4613) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Part of #4609. Adds the PyPI half of the package consume check, mirroring the NuGet half from #4612. ## What changed - New composite action `.github/actions/package-consume-pypi/` with `package_consume_pypi.py`. For each `python-versions` line and for the wheel and the sdist separately, it creates a fresh `uv venv` outside the checkout and installs the artifact. It then installs the locked dependency groups without the project and asserts the installed version and that every top-level name imports from site-packages. It runs the caller's `tests/` against the installed copy with `--import-mode=importlib`, `pythonpath` cleared, and the cwd outside the project. It reports one row per line, artifact, and check, runs every line, and fails at the end. - `build-release-task.yml`: new `python-versions` input, validated like `validate-task.yml`'s, empty meaning the one line `.python-version` selects. The check runs after the hub default `pypi-build-default` step, same `if:`, in smoke and publish runs, and uploads nothing. `pypi-build-default` now exposes the PEP 440 version it computed as an output. - Spec: `python.version.consistent` states that a caller passing `python-versions` to both workflows passes the same value to each. `spec/audit.py` has no mechanical check for this id, so it stays judgment-checked. - WORKFLOW.md D1.8, a 5A sentence, scenario S16, the `pypi` row in section 6, `docs/reusable-workflows.md`, the catalog snippets and their documented stubs. - Hub self-test `scripts/package_consume_pypi_selftest.py` and job `pypi-consume-test` (in the aggregator `needs:`), unit tests `tests/test_package_consume_pypi.py`, and the `test_cli_usage.py` and mypy path registrations. ## Local proof Self-test, Python 3.13 and 3.14, trimmed: ```text Good package: PASS [wheel py3.13] version: installed 1.2.3.dev0, build wrote 1.2.3.dev0 PASS [wheel py3.13] import location: ['contoso_widget'] from site-packages PASS [wheel py3.13] tests: pytest exit 0 PASS [sdist py3.13] tests: pytest exit 0 PASS [wheel py3.14] tests: pytest exit 0 PASS [sdist py3.14] tests: pytest exit 0 Package whose wheel excludes the extra module: FAIL [wheel py3.13] tests: pytest exit 2 FAIL [sdist py3.13] tests: pytest exit 2 FAIL [wheel py3.14] tests: pytest exit 2 FAIL [sdist py3.14] tests: pytest exit 2 SELF-TEST OK ``` Also run locally: ruff check and format, mypy, actionlint, `repo_gate.py`, `spec/validate.py`, `build_dist.py --check`, `prose_lint.py --diff origin/develop`, and the full unit suite (the two `test_release_guards` failures it surfaced, the documented stubs, are fixed in this branch). ## Review notes Four local strict-review passes ran. Fixed: wrong D1.7 citations, the "failed step" wording, fallback-line wording, the no-lock dead branch, non-module wheel-root files, tests-run constraints stated in D1.8, pinned uv in the self-test, `consume()` unit tests, pytest cache option, install cwd. Declined or deferred, with reasons: - Aggregator `${{ needs.*.result }}` in a run script: mirrors the three existing lines, a fixed result enum. - Helper duplication with the NuGet action and with validate-task's input check: standalone actions by design, held equal by a unit test. - Empty `python-versions` with no `.python-version` uses the hub fallback line, as `validate-task.yml` does. Documented. - Coverage settings read from the working directory and workspace-member lock layout: stated as limits in D1.8. - Flat-layout self-test variant: deferred, the cwd split is held by a unit test. This PR carries `comments` label (added comment lines are why-comments). 🤖 Generated with [Claude Code](https://claude.com/claude-code) ## Summary by CodeRabbit * **New Features** * Release builds now install and test both the wheel and source distribution in fresh environments for each configured Python version. The build fails if either artifact’s checks fail. * Added a configurable Python-version input for these checks; when left empty, the selected build version is used. * **Documentation** * Updated workflow guidance to explain the package checks and how to keep Python versions consistent across validation and release workflows. * **Tests** * Added coverage for package-consumption checks, including detection of missing modules in built artifacts. --------- Co-authored-by: Claude Sonnet 5.5 --- .../references/d-guarantees.md | 1 + .../references/test-methodology.md | 5 +- .../.source-digests/workflow-ci-contract | 2 +- .../references/d-guarantees.md | 1 + .../references/test-methodology.md | 5 +- .../actions/package-consume-pypi/action.yml | 35 ++ .../package_consume_pypi.py | 444 ++++++++++++++++++ .github/actions/pypi-build-default/action.yml | 5 + .../references/d-guarantees.md | 1 + .../references/test-methodology.md | 5 +- .github/workflows/build-release-task.yml | 38 ++ .github/workflows/test-pull-request.yml | 34 +- WORKFLOW.md | 10 +- .../snippets/workflows/publish-release.yml | 2 + .../workflows/test-pull-request-smoke.yml | 2 + docs/reusable-workflows.md | 8 +- pyproject.toml | 2 +- scripts/package_consume_pypi_selftest.py | 202 ++++++++ spec/project-types.json | 2 +- tests/test_cli_usage.py | 2 + tests/test_package_consume_pypi.py | 380 +++++++++++++++ 21 files changed, 1175 insertions(+), 11 deletions(-) create mode 100644 .github/actions/package-consume-pypi/action.yml create mode 100755 .github/actions/package-consume-pypi/package_consume_pypi.py create mode 100755 scripts/package_consume_pypi_selftest.py create mode 100755 tests/test_package_consume_pypi.py diff --git a/.agents/skills/workflow-ci-contract/references/d-guarantees.md b/.agents/skills/workflow-ci-contract/references/d-guarantees.md index bdfdf1d53..e4a37f852 100644 --- a/.agents/skills/workflow-ci-contract/references/d-guarantees.md +++ b/.agents/skills/workflow-ci-contract/references/d-guarantees.md @@ -17,6 +17,7 @@ The required behaviors, organized by domain. Each is a **MUST**, and its `Output - **D1.5 One required aggregator gates merge.** Input: any PR. Output: a single aggregator job must **succeed**. It must run under `if: always()`, so a failed or skipped dependency cannot skip the gate itself. It must also `needs:` the validation job, and the `changes` and `smoke-build` jobs too wherever the repo has a smoke build. It must treat a **skipped** smoke build as pass, and **block** on `failure`/`cancelled`. Its name is ruleset-bound: the job `name:` and the ruleset `context:` are the same string and MUST be renamed together, never independently. The workflow holding it MUST trigger on `pull_request`. A gate without a `pull_request` trigger never runs the validator's pull-request-only steps, the prose gate among them. A workflow any other event also triggers yields that name only when `github.event_name == 'pull_request'`, through an expression `name:`. Otherwise a dispatch or push run on a PR's head posts the required context without the PR run's gates. *Prevents: a paths-filter error letting a target-changing PR merge unbuilt.* - **D1.6 Coverage is reported to Codecov (C# and Python).** Input: a C# or Python repo that has tests for that type. Output: the validation job runs those tests under coverage collection, and a `codecov/codecov-action` step uploads the report. The collection is `dotnet test --coverage --coverage-output-format cobertura --results-directory ./coverage`, leaving `--coverage-output` unset so each test project writes its own report rather than overwriting a shared one. A bare call resolves one workspace from the working directory, so it fails at a root holding none or more than one. Unless the repository root holds exactly one solution or project, the hub's validator therefore runs the collection once per tracked `*Tests*.csproj` with `--project`. It names no solution in that case, since a solution holding no test project fails the run. Or it is `pytest --cov-report=xml` in a Python directory with its own `uv.lock` or `requirements*.txt`, whose own `pyproject.toml` selects what to measure. Or it is `coverage run -m unittest discover -s tests` then `coverage xml` in a `lint-only` one. The upload is **best-effort** (`continue-on-error` and/or `fail_ci_if_error: false`), so a Codecov outage or an absent token never reds the gate. Each leg **fails its test step when the run wrote no report**. The reason is that the best-effort upload reads a missing report exactly as it reads a healthy run. A second reason is that, on the Python leg, `--cov-report=xml` alone selects nothing to measure. The C# leg renames each report to `coverage-.cobertura.xml` before the upload step reads the directory, since `codecov-cli`'s own finder does not match the default name. A repo owning its validator rather than calling the hub's owes that rename itself. `CODECOV_TOKEN` lives in the repo's **actions** and **dependabot** secret stores. The token is in the second because a run triggered by a Dependabot pull request reads the Dependabot store. Without the token there, the upload would otherwise skip silently on every bot pull request. A caller reaching the reusable validator across repositories names the secret it passes (`secrets:` with `CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}`). It does so on its pull request path and its publisher path alike. That is because `secrets: inherit` is documented for a caller in the same organization or enterprise, which a personal account is not. A call by local path stays inside one repository, where the caller's own store is the one the callee reads. So `secrets: inherit` is available there instead of naming each secret. The repo ships a **`.codecov.yml`** at the repository root. It sets the project and patch statuses to **`informational: true`**, so a coverage delta never gates a pull request. A repo whose quality bar requires a threshold may turn that off. The same file excludes intentionally-untested, non-shipped code (an example or benchmark project) from the denominator via `ignore`. Codecov reads its configuration under several names, but `.codecov.yml` is the only one the fleet accepts. So a copy under any other name is drift to rename. Coverage output is a build artifact, so `.gitignore` excludes it. The C# invocation runs under **Microsoft.Testing.Platform**, and the runner declaration, package references, and version floor an MTP-based test project needs are `CODESTYLE.md`'s .NET side. The Python invocation needs **`pytest-cov`** and a coverage selector, which are `CODESTYLE.md`'s Python side. A Python directory declared in the validator's `python-directories` input owes a `tests/` suite whatever its profile, so the validator fails one that has none. N/A for a repo carrying no tests for that type. *Prevents: coverage silently going unreported, and a coverage regression blocking an unrelated pull request.* - **D1.7 A built NuGet package is consumed before it publishes.** Input: a repo whose `build-nuget` job runs the hub's default leaf, in a smoke run or a publish run alike. Output: after the leaf packs, the job restores, builds, and runs a throwaway console project against that exact `.nupkg`. It does so once per target framework the project declares. Each consumer lives outside the checkout, so the caller's `global.json` and `Directory.Build.props` do not apply. Its `nuget.config` resolves the package ID, and the ID of each sibling package in the folder holding the build output, only from that folder. Every other ID resolves from nuget.org. Its package cache is its own, so neither a cached nor a published copy can stand in for the artifact under test. The consumer loads the package assembly and calls `GetExportedTypes()`. The check asserts from `obj/project.assets.json` that the package resolved from the `lib//` folder of the consumer's own framework. It also asserts that the loaded assembly's `TargetFrameworkAttribute` matches that folder. A `netstandard` framework is consumed under the SDK line `global.json` selects, or the newest declared line where there is none. It is asserted against the folder it resolved. A framework the check does not consume is reported skipped. Examples are .NET Framework, `netcoreapp3.1`, and a platform-specific `netX.Y-windows`. The attribute row of a `netstandard` consumer resolving such a folder is skipped too. Four static assertions join them. The package's `lib//` folders equal the declared frameworks. The nuspec `` equals the build version. The nuspec holds a dependency group per framework. A symbol package exists where the project enables symbols. Every declared `netX.Y` and `netstandard` framework is consumed and reported with one summary row per assertion. A failed step ends that framework's rows rather than the run. The job fails at the end if any failed. The check covers a library package, whose assemblies sit under `lib//`. The check uploads nothing, so it honors D1.3. It runs inside the build job, so a failure blocks the publish job that `needs:` that build. A caller's own `build-nuget` hook replaces the whole leaf and is outside the check. A caller's own `.github/actions/package-consume/action.yml` runs once after the default check. It receives the declared frameworks as JSON beside the package ID, version, and package folder. *Prevents: a defect that exists only in the packed form shipping. One example is one target framework's assembly packed under every `lib//` folder while the tests, which reach the library through a project reference, stay green.* +- **D1.8 A built PyPI package is consumed before it publishes.** Input: a repo whose `build-pypi` job runs the hub's default leaf, in a smoke run or a publish run alike. Output: after the leaf builds, the job installs the wheel and, separately, the sdist into a fresh `uv venv`. It does so for each line of the `python-versions` input of `build-release-task.yml`. Empty runs the one line the root `.python-version` selects. Where there is none it runs the hub's fallback line. A caller that sets `python-versions` for both `validate-task.yml` and `build-release-task.yml` passes the same value to each. So the lines its tests run under are the lines its artifact is consumed under. Each environment lives outside the checkout. It installs the artifact, then the project's locked dependency groups from `uv.lock` without the project itself. The check asserts that `importlib.metadata` reports the version the leaf computed. It also asserts that every top-level name the installed distribution provides imports from the environment's site-packages, not the source tree. A distribution providing none, such as one of scripts only, reports that row skipped. It then runs the caller's `tests/` folder against the installed copy with pytest in `importlib` import mode. That run has the source tree off `sys.path` and the project's `pythonpath` setting cleared. Its working directory is outside the project. So the caller's suite must not read a path relative to the project root, or a tool setting read from the working directory. It must import a sibling helper as part of a package. The project directory holds its own `uv.lock`. A project with no `tests/` folder, or a run collecting no tests, is reported skipped rather than passed. Every line and artifact reports one summary row per assertion. A failed environment, install, or metadata read ends that artifact's rows rather than the run. The job fails at the end if any failed. The check uploads nothing, so it honors D1.3. It runs inside the build job, so a failure blocks the publish job that `needs:` that build. A caller's own `build-pypi` hook replaces the whole leaf and is outside the check. *Prevents: a defect that exists only in the built form shipping. One example is a module left out of the wheel while the tests, which import it from the source tree, stay green.* ### D2 - Input/State Validation at Entry diff --git a/.agents/skills/workflow-ci-contract/references/test-methodology.md b/.agents/skills/workflow-ci-contract/references/test-methodology.md index d5030643e..2e88b46d5 100644 --- a/.agents/skills/workflow-ci-contract/references/test-methodology.md +++ b/.agents/skills/workflow-ci-contract/references/test-methodology.md @@ -16,11 +16,13 @@ Most of the evidence is in the workflow files and the composite actions they rea D1.7 is read in the build job. A step after the default leaf plans the declared frameworks, then the `dotnet-sdk` action installs those runtime lines, then the consume check runs. None of them uploads. +D1.8 is read in the build job. A step after the default leaf runs the consume check. It receives the build's computed version and the `python-versions` list. Empty becomes the one line the root `.python-version` selects, or the hub's fallback line where there is none. It uploads nothing. + Cite what each verdict rests on. That is `file:line` for a file in the audited repo. It is the evidence's own name where a setting, a ruleset, or a secret name rather than a file is the evidence. Where the guarantee binds a workflow or composite action the audited repo only reaches, it is `/@` plus the `file:line` in that repo. The callee is read at the SHA the caller pins. An **N/A** verdict names the absent construct instead, there being no line to cite. ### 5B. End-to-End Trace Scenarios (No Execution, Deterministic from the YAML) -For each *applicable* scenario, evaluate every job's `if:`/`needs:` against the inputs. Emit the predicted **run/skip + version + release + artifact-end-state** table, then compare to the expected. A scenario governing a construct the repo does not contain is N/A, per `WORKFLOW.md` section 1, and an absent trigger is such a construct. Each scenario's trigger belongs to one workflow, so read that workflow's own `on:` block rather than the repo's type. For S1 to S4 the block is the pull request workflow's. For S5 to S10 and S14 it is the publisher's. For S15 it is whichever workflow reaches the `build-nuget` job. For S11 the block is the upstream tracker's, and for S12 and S13 the deploy workflow's. A publisher carrying only `workflow_dispatch` therefore records S5, S6 and S9 N/A, their push and schedule paths never firing there. A repo with no publisher lacks a construct every repo owes. So S7, S8, S10 and S14 fail there, and none is excluded from the verdict. S5, S6 and S9 turn on the `on:` block that publisher has yet to state, so each is judged once it lands. A publisher whose schedule never publishes, per D4.1, records the schedule paths of S7 and S9 N/A as well. Where a scenario's path runs through a workflow or composite action the repo only **calls**, trace that callee as the repo reaches it. Read it at the SHA the caller pins rather than at the callee's current default branch, which is the same evidence rule 5A states. Predicting from the callee's `main` predicts a table for YAML the audited repo never runs. A self-repository (`$/`) call or a job-level local (`./`) reusable-workflow call carries no pin of its own. It resolves at the calling workflow file's commit, so it is traced at that file's own commit. That commit is the SHA fixed by the pin that reached that file. Where that file is one of the audited repository's own workflows, it is the audited commit instead. A local (`./`) action reference carries no pin either, but it resolves against whatever the job checked out. So it is traced at that checkout's commit. That is the caller's commit where a reusable workflow called from another repository checks out its caller. Minimum set: +For each *applicable* scenario, evaluate every job's `if:`/`needs:` against the inputs. Emit the predicted **run/skip + version + release + artifact-end-state** table, then compare to the expected. A scenario governing a construct the repo does not contain is N/A, per `WORKFLOW.md` section 1, and an absent trigger is such a construct. Each scenario's trigger belongs to one workflow, so read that workflow's own `on:` block rather than the repo's type. For S1 to S4 the block is the pull request workflow's. For S5 to S10 and S14 it is the publisher's. For S15 it is whichever workflow reaches the `build-nuget` job, and for S16 the one reaching `build-pypi`. For S11 the block is the upstream tracker's, and for S12 and S13 the deploy workflow's. A publisher carrying only `workflow_dispatch` therefore records S5, S6 and S9 N/A, their push and schedule paths never firing there. A repo with no publisher lacks a construct every repo owes. So S7, S8, S10 and S14 fail there, and none is excluded from the verdict. S5, S6 and S9 turn on the `on:` block that publisher has yet to state, so each is judged once it lands. A publisher whose schedule never publishes, per D4.1, records the schedule paths of S7 and S9 N/A as well. Where a scenario's path runs through a workflow or composite action the repo only **calls**, trace that callee as the repo reaches it. Read it at the SHA the caller pins rather than at the callee's current default branch, which is the same evidence rule 5A states. Predicting from the callee's `main` predicts a table for YAML the audited repo never runs. A self-repository (`$/`) call or a job-level local (`./`) reusable-workflow call carries no pin of its own. It resolves at the calling workflow file's commit, so it is traced at that file's own commit. That commit is the SHA fixed by the pin that reached that file. Where that file is one of the audited repository's own workflows, it is the audited commit instead. A local (`./`) action reference carries no pin either, but it resolves against whatever the job checked out. So it is traced at that checkout's commit. That is the caller's commit where a reusable workflow called from another repository checks out its caller. Minimum set: | # | Input | Expected output | Exercises | | --- | --- | --- | --- | @@ -39,6 +41,7 @@ For each *applicable* scenario, evaluate every job's `if:`/`needs:` against the | S13 | deploy dispatch of a production environment from a non-default ref | **fails fast**, before anything is installed or written | D2.1 | | S14 | publish whose branch head gained different `.github/workflows` content after the build began | every update since a release bot's push or merge: release-create **skipped** and the publisher dispatched on the branch. In that case this run ends **cancelled** with its package publish jobs skipped (a Docker image already pushed). The dispatched run releases the head, queueing behind this run only where the head's publisher evaluates this run's group for a dispatch. A push landing after the branch is confirmed unmoved and before the dispatch is released as if it were such an update. That is an accepted, bounded limit per D4.7. Any other update: the step **fails**, nothing is released or dispatched | D4.1, D4.2, D4.5, D4.7 | | S15 | a smoke or publish run whose `build-nuget` job runs the hub default leaf, for a project declaring `net10.0;net11.0`. The package holds one framework's assembly under both `lib/` folders | the job plans both runtime lines, installs them, and consumes the package once per framework. It **fails** on the `TargetFrameworkAttribute` of the `lib/` folder holding the other framework's assembly, after reporting every other row. A correct package **passes**. The check uploads nothing in either run. A publish run's leaf has uploaded its artifacts already, and a failure leaves them to their retention and the dependent publish job **skipped** | D1.3, D1.7 | +| S16 | a smoke or publish run whose `build-pypi` job runs the hub default leaf, for a project with a `tests/` folder and a `python-versions` of `["3.13", "3.14"]`. Its wheel leaves out a module the tests import | the job builds, then consumes the wheel and the sdist under each line. It **fails** on the tests row of each artifact lacking the module, after reporting every other row. A correct package **passes** under both lines. The check uploads nothing in either run. A publish run's leaf has uploaded its artifact already. A failure leaves it to its retention, and the dependent publish job is **skipped** | D1.3, D1.8 | ### 5C. Live Probe (Where Warranted) diff --git a/.claude-plugin/fleet-skills/.source-digests/workflow-ci-contract b/.claude-plugin/fleet-skills/.source-digests/workflow-ci-contract index 34815610b..fd526bce3 100644 --- a/.claude-plugin/fleet-skills/.source-digests/workflow-ci-contract +++ b/.claude-plugin/fleet-skills/.source-digests/workflow-ci-contract @@ -1 +1 @@ -1f8840231e1f50fb +23c6a153a42f8126 diff --git a/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/d-guarantees.md b/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/d-guarantees.md index bdfdf1d53..e4a37f852 100644 --- a/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/d-guarantees.md +++ b/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/d-guarantees.md @@ -17,6 +17,7 @@ The required behaviors, organized by domain. Each is a **MUST**, and its `Output - **D1.5 One required aggregator gates merge.** Input: any PR. Output: a single aggregator job must **succeed**. It must run under `if: always()`, so a failed or skipped dependency cannot skip the gate itself. It must also `needs:` the validation job, and the `changes` and `smoke-build` jobs too wherever the repo has a smoke build. It must treat a **skipped** smoke build as pass, and **block** on `failure`/`cancelled`. Its name is ruleset-bound: the job `name:` and the ruleset `context:` are the same string and MUST be renamed together, never independently. The workflow holding it MUST trigger on `pull_request`. A gate without a `pull_request` trigger never runs the validator's pull-request-only steps, the prose gate among them. A workflow any other event also triggers yields that name only when `github.event_name == 'pull_request'`, through an expression `name:`. Otherwise a dispatch or push run on a PR's head posts the required context without the PR run's gates. *Prevents: a paths-filter error letting a target-changing PR merge unbuilt.* - **D1.6 Coverage is reported to Codecov (C# and Python).** Input: a C# or Python repo that has tests for that type. Output: the validation job runs those tests under coverage collection, and a `codecov/codecov-action` step uploads the report. The collection is `dotnet test --coverage --coverage-output-format cobertura --results-directory ./coverage`, leaving `--coverage-output` unset so each test project writes its own report rather than overwriting a shared one. A bare call resolves one workspace from the working directory, so it fails at a root holding none or more than one. Unless the repository root holds exactly one solution or project, the hub's validator therefore runs the collection once per tracked `*Tests*.csproj` with `--project`. It names no solution in that case, since a solution holding no test project fails the run. Or it is `pytest --cov-report=xml` in a Python directory with its own `uv.lock` or `requirements*.txt`, whose own `pyproject.toml` selects what to measure. Or it is `coverage run -m unittest discover -s tests` then `coverage xml` in a `lint-only` one. The upload is **best-effort** (`continue-on-error` and/or `fail_ci_if_error: false`), so a Codecov outage or an absent token never reds the gate. Each leg **fails its test step when the run wrote no report**. The reason is that the best-effort upload reads a missing report exactly as it reads a healthy run. A second reason is that, on the Python leg, `--cov-report=xml` alone selects nothing to measure. The C# leg renames each report to `coverage-.cobertura.xml` before the upload step reads the directory, since `codecov-cli`'s own finder does not match the default name. A repo owning its validator rather than calling the hub's owes that rename itself. `CODECOV_TOKEN` lives in the repo's **actions** and **dependabot** secret stores. The token is in the second because a run triggered by a Dependabot pull request reads the Dependabot store. Without the token there, the upload would otherwise skip silently on every bot pull request. A caller reaching the reusable validator across repositories names the secret it passes (`secrets:` with `CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}`). It does so on its pull request path and its publisher path alike. That is because `secrets: inherit` is documented for a caller in the same organization or enterprise, which a personal account is not. A call by local path stays inside one repository, where the caller's own store is the one the callee reads. So `secrets: inherit` is available there instead of naming each secret. The repo ships a **`.codecov.yml`** at the repository root. It sets the project and patch statuses to **`informational: true`**, so a coverage delta never gates a pull request. A repo whose quality bar requires a threshold may turn that off. The same file excludes intentionally-untested, non-shipped code (an example or benchmark project) from the denominator via `ignore`. Codecov reads its configuration under several names, but `.codecov.yml` is the only one the fleet accepts. So a copy under any other name is drift to rename. Coverage output is a build artifact, so `.gitignore` excludes it. The C# invocation runs under **Microsoft.Testing.Platform**, and the runner declaration, package references, and version floor an MTP-based test project needs are `CODESTYLE.md`'s .NET side. The Python invocation needs **`pytest-cov`** and a coverage selector, which are `CODESTYLE.md`'s Python side. A Python directory declared in the validator's `python-directories` input owes a `tests/` suite whatever its profile, so the validator fails one that has none. N/A for a repo carrying no tests for that type. *Prevents: coverage silently going unreported, and a coverage regression blocking an unrelated pull request.* - **D1.7 A built NuGet package is consumed before it publishes.** Input: a repo whose `build-nuget` job runs the hub's default leaf, in a smoke run or a publish run alike. Output: after the leaf packs, the job restores, builds, and runs a throwaway console project against that exact `.nupkg`. It does so once per target framework the project declares. Each consumer lives outside the checkout, so the caller's `global.json` and `Directory.Build.props` do not apply. Its `nuget.config` resolves the package ID, and the ID of each sibling package in the folder holding the build output, only from that folder. Every other ID resolves from nuget.org. Its package cache is its own, so neither a cached nor a published copy can stand in for the artifact under test. The consumer loads the package assembly and calls `GetExportedTypes()`. The check asserts from `obj/project.assets.json` that the package resolved from the `lib//` folder of the consumer's own framework. It also asserts that the loaded assembly's `TargetFrameworkAttribute` matches that folder. A `netstandard` framework is consumed under the SDK line `global.json` selects, or the newest declared line where there is none. It is asserted against the folder it resolved. A framework the check does not consume is reported skipped. Examples are .NET Framework, `netcoreapp3.1`, and a platform-specific `netX.Y-windows`. The attribute row of a `netstandard` consumer resolving such a folder is skipped too. Four static assertions join them. The package's `lib//` folders equal the declared frameworks. The nuspec `` equals the build version. The nuspec holds a dependency group per framework. A symbol package exists where the project enables symbols. Every declared `netX.Y` and `netstandard` framework is consumed and reported with one summary row per assertion. A failed step ends that framework's rows rather than the run. The job fails at the end if any failed. The check covers a library package, whose assemblies sit under `lib//`. The check uploads nothing, so it honors D1.3. It runs inside the build job, so a failure blocks the publish job that `needs:` that build. A caller's own `build-nuget` hook replaces the whole leaf and is outside the check. A caller's own `.github/actions/package-consume/action.yml` runs once after the default check. It receives the declared frameworks as JSON beside the package ID, version, and package folder. *Prevents: a defect that exists only in the packed form shipping. One example is one target framework's assembly packed under every `lib//` folder while the tests, which reach the library through a project reference, stay green.* +- **D1.8 A built PyPI package is consumed before it publishes.** Input: a repo whose `build-pypi` job runs the hub's default leaf, in a smoke run or a publish run alike. Output: after the leaf builds, the job installs the wheel and, separately, the sdist into a fresh `uv venv`. It does so for each line of the `python-versions` input of `build-release-task.yml`. Empty runs the one line the root `.python-version` selects. Where there is none it runs the hub's fallback line. A caller that sets `python-versions` for both `validate-task.yml` and `build-release-task.yml` passes the same value to each. So the lines its tests run under are the lines its artifact is consumed under. Each environment lives outside the checkout. It installs the artifact, then the project's locked dependency groups from `uv.lock` without the project itself. The check asserts that `importlib.metadata` reports the version the leaf computed. It also asserts that every top-level name the installed distribution provides imports from the environment's site-packages, not the source tree. A distribution providing none, such as one of scripts only, reports that row skipped. It then runs the caller's `tests/` folder against the installed copy with pytest in `importlib` import mode. That run has the source tree off `sys.path` and the project's `pythonpath` setting cleared. Its working directory is outside the project. So the caller's suite must not read a path relative to the project root, or a tool setting read from the working directory. It must import a sibling helper as part of a package. The project directory holds its own `uv.lock`. A project with no `tests/` folder, or a run collecting no tests, is reported skipped rather than passed. Every line and artifact reports one summary row per assertion. A failed environment, install, or metadata read ends that artifact's rows rather than the run. The job fails at the end if any failed. The check uploads nothing, so it honors D1.3. It runs inside the build job, so a failure blocks the publish job that `needs:` that build. A caller's own `build-pypi` hook replaces the whole leaf and is outside the check. *Prevents: a defect that exists only in the built form shipping. One example is a module left out of the wheel while the tests, which import it from the source tree, stay green.* ### D2 - Input/State Validation at Entry diff --git a/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/test-methodology.md b/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/test-methodology.md index d5030643e..2e88b46d5 100644 --- a/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/test-methodology.md +++ b/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/test-methodology.md @@ -16,11 +16,13 @@ Most of the evidence is in the workflow files and the composite actions they rea D1.7 is read in the build job. A step after the default leaf plans the declared frameworks, then the `dotnet-sdk` action installs those runtime lines, then the consume check runs. None of them uploads. +D1.8 is read in the build job. A step after the default leaf runs the consume check. It receives the build's computed version and the `python-versions` list. Empty becomes the one line the root `.python-version` selects, or the hub's fallback line where there is none. It uploads nothing. + Cite what each verdict rests on. That is `file:line` for a file in the audited repo. It is the evidence's own name where a setting, a ruleset, or a secret name rather than a file is the evidence. Where the guarantee binds a workflow or composite action the audited repo only reaches, it is `/@` plus the `file:line` in that repo. The callee is read at the SHA the caller pins. An **N/A** verdict names the absent construct instead, there being no line to cite. ### 5B. End-to-End Trace Scenarios (No Execution, Deterministic from the YAML) -For each *applicable* scenario, evaluate every job's `if:`/`needs:` against the inputs. Emit the predicted **run/skip + version + release + artifact-end-state** table, then compare to the expected. A scenario governing a construct the repo does not contain is N/A, per `WORKFLOW.md` section 1, and an absent trigger is such a construct. Each scenario's trigger belongs to one workflow, so read that workflow's own `on:` block rather than the repo's type. For S1 to S4 the block is the pull request workflow's. For S5 to S10 and S14 it is the publisher's. For S15 it is whichever workflow reaches the `build-nuget` job. For S11 the block is the upstream tracker's, and for S12 and S13 the deploy workflow's. A publisher carrying only `workflow_dispatch` therefore records S5, S6 and S9 N/A, their push and schedule paths never firing there. A repo with no publisher lacks a construct every repo owes. So S7, S8, S10 and S14 fail there, and none is excluded from the verdict. S5, S6 and S9 turn on the `on:` block that publisher has yet to state, so each is judged once it lands. A publisher whose schedule never publishes, per D4.1, records the schedule paths of S7 and S9 N/A as well. Where a scenario's path runs through a workflow or composite action the repo only **calls**, trace that callee as the repo reaches it. Read it at the SHA the caller pins rather than at the callee's current default branch, which is the same evidence rule 5A states. Predicting from the callee's `main` predicts a table for YAML the audited repo never runs. A self-repository (`$/`) call or a job-level local (`./`) reusable-workflow call carries no pin of its own. It resolves at the calling workflow file's commit, so it is traced at that file's own commit. That commit is the SHA fixed by the pin that reached that file. Where that file is one of the audited repository's own workflows, it is the audited commit instead. A local (`./`) action reference carries no pin either, but it resolves against whatever the job checked out. So it is traced at that checkout's commit. That is the caller's commit where a reusable workflow called from another repository checks out its caller. Minimum set: +For each *applicable* scenario, evaluate every job's `if:`/`needs:` against the inputs. Emit the predicted **run/skip + version + release + artifact-end-state** table, then compare to the expected. A scenario governing a construct the repo does not contain is N/A, per `WORKFLOW.md` section 1, and an absent trigger is such a construct. Each scenario's trigger belongs to one workflow, so read that workflow's own `on:` block rather than the repo's type. For S1 to S4 the block is the pull request workflow's. For S5 to S10 and S14 it is the publisher's. For S15 it is whichever workflow reaches the `build-nuget` job, and for S16 the one reaching `build-pypi`. For S11 the block is the upstream tracker's, and for S12 and S13 the deploy workflow's. A publisher carrying only `workflow_dispatch` therefore records S5, S6 and S9 N/A, their push and schedule paths never firing there. A repo with no publisher lacks a construct every repo owes. So S7, S8, S10 and S14 fail there, and none is excluded from the verdict. S5, S6 and S9 turn on the `on:` block that publisher has yet to state, so each is judged once it lands. A publisher whose schedule never publishes, per D4.1, records the schedule paths of S7 and S9 N/A as well. Where a scenario's path runs through a workflow or composite action the repo only **calls**, trace that callee as the repo reaches it. Read it at the SHA the caller pins rather than at the callee's current default branch, which is the same evidence rule 5A states. Predicting from the callee's `main` predicts a table for YAML the audited repo never runs. A self-repository (`$/`) call or a job-level local (`./`) reusable-workflow call carries no pin of its own. It resolves at the calling workflow file's commit, so it is traced at that file's own commit. That commit is the SHA fixed by the pin that reached that file. Where that file is one of the audited repository's own workflows, it is the audited commit instead. A local (`./`) action reference carries no pin either, but it resolves against whatever the job checked out. So it is traced at that checkout's commit. That is the caller's commit where a reusable workflow called from another repository checks out its caller. Minimum set: | # | Input | Expected output | Exercises | | --- | --- | --- | --- | @@ -39,6 +41,7 @@ For each *applicable* scenario, evaluate every job's `if:`/`needs:` against the | S13 | deploy dispatch of a production environment from a non-default ref | **fails fast**, before anything is installed or written | D2.1 | | S14 | publish whose branch head gained different `.github/workflows` content after the build began | every update since a release bot's push or merge: release-create **skipped** and the publisher dispatched on the branch. In that case this run ends **cancelled** with its package publish jobs skipped (a Docker image already pushed). The dispatched run releases the head, queueing behind this run only where the head's publisher evaluates this run's group for a dispatch. A push landing after the branch is confirmed unmoved and before the dispatch is released as if it were such an update. That is an accepted, bounded limit per D4.7. Any other update: the step **fails**, nothing is released or dispatched | D4.1, D4.2, D4.5, D4.7 | | S15 | a smoke or publish run whose `build-nuget` job runs the hub default leaf, for a project declaring `net10.0;net11.0`. The package holds one framework's assembly under both `lib/` folders | the job plans both runtime lines, installs them, and consumes the package once per framework. It **fails** on the `TargetFrameworkAttribute` of the `lib/` folder holding the other framework's assembly, after reporting every other row. A correct package **passes**. The check uploads nothing in either run. A publish run's leaf has uploaded its artifacts already, and a failure leaves them to their retention and the dependent publish job **skipped** | D1.3, D1.7 | +| S16 | a smoke or publish run whose `build-pypi` job runs the hub default leaf, for a project with a `tests/` folder and a `python-versions` of `["3.13", "3.14"]`. Its wheel leaves out a module the tests import | the job builds, then consumes the wheel and the sdist under each line. It **fails** on the tests row of each artifact lacking the module, after reporting every other row. A correct package **passes** under both lines. The check uploads nothing in either run. A publish run's leaf has uploaded its artifact already. A failure leaves it to its retention, and the dependent publish job is **skipped** | D1.3, D1.8 | ### 5C. Live Probe (Where Warranted) diff --git a/.github/actions/package-consume-pypi/action.yml b/.github/actions/package-consume-pypi/action.yml new file mode 100644 index 000000000..65a1a899b --- /dev/null +++ b/.github/actions/package-consume-pypi/action.yml @@ -0,0 +1,35 @@ +name: Package consume PyPI +description: >- + Check the wheel and sdist a build produced by installing each into a fresh environment, once per declared Python line, before anything publishes. + Each environment installs the project's locked test dependencies, asserts the installed version and that the package imports from site-packages, and runs the caller's tests against the installed copy. + The environments live in the runner's temp folder, outside the checkout, so the source tree is never on the import path. + A caller's own build-pypi hook replaces the whole default build and is outside this check. + Nothing is uploaded, so a smoke run runs it unchanged. + +inputs: + project-dir: + description: Working directory of the PyPI project, whose dist folder holds the wheel and sdist, whose uv.lock names the test dependencies, and whose tests folder is run. + required: true + version: + description: The PEP 440 version the build wrote, which the installed distribution must report. + required: true + python-versions: + description: JSON array of the X.Y Python lines to consume under, one environment per line and artifact. + required: true + +runs: + using: composite + steps: + + - name: Consume the PyPI package step + shell: bash + env: + PROJECT_DIR: ${{ inputs.project-dir }} + PYPI_VERSION: ${{ inputs.version }} + PYTHON_VERSIONS: ${{ inputs.python-versions }} + run: | + set -Eeuo pipefail + # The environments live in the runner's temp folder, outside the checkout, so the source tree is never on the import path. + WORK_DIR="$(mktemp -d "$RUNNER_TEMP/package-consume.XXXXXX")" + export WORK_DIR + python3 "$GITHUB_ACTION_PATH/package_consume_pypi.py" diff --git a/.github/actions/package-consume-pypi/package_consume_pypi.py b/.github/actions/package-consume-pypi/package_consume_pypi.py new file mode 100755 index 000000000..56aa287ad --- /dev/null +++ b/.github/actions/package-consume-pypi/package_consume_pypi.py @@ -0,0 +1,444 @@ +#!/usr/bin/env python3 +"""Consume the built wheel and sdist once per declared Python line, before anything publishes. + +The unit tests reach the library through the source tree and never through the built artifact. +So a defect that exists only in the packaged form passes every other gate. +A module left out of a wheel is one such defect, since the tests still import it from `src/`. + +Each declared line and each artifact gets a fresh environment outside the repository. +The artifact is installed into it, then the project's locked dependency groups, without the project itself. +The checks that follow are that the installed version is the build's version, and that every top-level package imports from site-packages. +The caller's tests then run against the installed copy, from a directory that is not the project, so the source tree is not on `sys.path`. + +Every check runs and reports, then the exit status says whether any failed. +Nothing is uploaded. +""" + +from __future__ import annotations + +import argparse +import contextlib +import json +import os +import re +import signal +import subprocess +import sys +import tomllib +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, field +from pathlib import Path +from types import FrameType + +COMMAND_TIMEOUT_SECONDS = 900 +# The pytest rootdir is the project, so its own pythonpath setting would put the source tree back on sys.path. +# The cache goes to the work folder rather than off, so a caller's addopts naming a cache option still parses. +PYTEST_ARGUMENTS = ("--import-mode=importlib", "-o", "pythonpath=") +# Pytest's exit code for a run that collected nothing. +PYTEST_NO_TESTS = 5 +IDENTIFIER = re.compile(r"[A-Za-z_][A-Za-z0-9_]*") + +# Run inside the environment under test, with `-I` so neither the current directory nor PYTHONPATH reaches it. +FILES_PROBE = """import importlib.metadata as md, json, sys +dist = md.distribution(sys.argv[1]) +print("VERSION\\t" + dist.version) +print("FILES\\t" + json.dumps([str(f) for f in (dist.files or [])])) +""" +IMPORT_PROBE = """import importlib, os, sys, sysconfig + + +def emit(text): + # The import can leave a partial line on stdout, so each row starts on a line of its own. + print("\\n" + text) + + +roots = {os.path.realpath(sysconfig.get_paths()[key]) for key in ("purelib", "platlib")} +emit("ROOTS\\t" + "\\t".join(sorted(roots))) +for name in sys.argv[1:]: + try: + module = importlib.import_module(name) + except Exception as error: + text = str(error).splitlines() + emit(f"IMPORTFAIL\\t{name}\\t{type(error).__name__}: {text[0] if text else ''}") + continue + location = getattr(module, "__file__", None) + if location is None: + paths = list(getattr(module, "__path__", [])) + location = paths[0] if paths else "" + emit(f"IMPORT\\t{name}\\t{os.path.realpath(location) if location else ''}") +""" + + +def escape_command(value: str) -> str: + """Encode a value for a workflow command, percent first so the later escapes are not re-encoded.""" + return value.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A") + + +def neutralize(text: str) -> str: + """Break a workflow command that leads a line, indented or not, since the runner trims leading whitespace before it parses one.""" + return re.sub(r"(?m)^([ \t]*)::", r"\1: :", text) + + +def parse_versions(raw: str) -> list[str]: + """The declared Python lines, from a JSON array of non-empty strings, or a SystemExit naming why not.""" + try: + value = json.loads(raw) + except ValueError as error: + raise SystemExit(f"python-versions is not JSON: {error}") from error + if ( + not isinstance(value, list) + or not value + or not all(isinstance(v, str) and v.strip() for v in value) + ): + raise SystemExit("python-versions must be a non-empty JSON array of non-empty strings.") + seen: list[str] = [] + for entry in value: + line = entry.strip() + if line not in seen: + seen.append(line) + return seen + + +def top_level_names(files: Sequence[str]) -> list[str]: + """The importable top-level names an installed distribution's file list provides, in order.""" + names: list[str] = [] + for entry in files: + parts = [p for p in entry.replace("\\", "/").split("/") if p] + if not parts or parts[0] == ".." or "__pycache__" in parts: + continue + head = parts[0] + if head.endswith((".dist-info", ".data", ".pth")): + continue + # A single-file module or an extension module carries its suffix after the first dot. + if len(parts) == 1: + # A data file at the wheel root, such as a force-included LICENSE, is not importable. + if not head.endswith((".py", ".pyc", ".so", ".pyd")): + continue + name = head.split(".", 1)[0] + else: + name = head + if IDENTIFIER.fullmatch(name) and name not in names: + names.append(name) + return names + + +def is_under(path: str, roots: Sequence[str]) -> bool: + """Whether a resolved path sits inside one of the resolved site-packages roots.""" + target = Path(path) + return any(target.is_relative_to(Path(root)) for root in roots if root) + + +def project_name(pyproject: Path) -> str: + """The distribution name the project declares.""" + with pyproject.open("rb") as handle: + name = tomllib.load(handle).get("project", {}).get("name") + if not isinstance(name, str) or not name: + raise SystemExit(f"{pyproject} declares no [project] name.") + return name + + +def find_artifacts(dist: Path) -> dict[str, Path]: + """The one wheel and the one sdist the build wrote, or a SystemExit naming what is missing.""" + found = {"wheel": sorted(dist.glob("*.whl")), "sdist": sorted(dist.glob("*.tar.gz"))} + for kind, paths in found.items(): + if len(paths) != 1: + raise SystemExit(f"Expected exactly one {kind} in {dist}, found {len(paths)}.") + return {kind: paths[0] for kind, paths in found.items()} + + +def probe_rows(output: str) -> dict[str, list[list[str]]]: + """The tab-separated rows a probe printed, keyed by their first column.""" + rows: dict[str, list[list[str]]] = {} + for line in output.splitlines(): + parts = line.split("\t") + if len(parts) > 1: + rows.setdefault(parts[0], []).append(parts[1:]) + return rows + + +@dataclass +class Result: + target: str + check: str + ok: bool + detail: str + skipped: bool = False + + +@dataclass +class Report: + results: list[Result] = field(default_factory=list) + + def add(self, target: str, check: str, ok: bool, detail: str, skipped: bool = False) -> bool: + self.results.append(Result(target, check, ok, detail, skipped)) + # A detail can carry command output, so a line break must not start a line of its own and forge a command. + print( + f"{'SKIP' if skipped else 'PASS' if ok else 'FAIL'} [{target}] {check}: {escape_command(detail)}" + ) + if not ok: + print(f"::error::{escape_command(f'package-consume [{target}] {check}: {detail}')}") + return ok + + def table(self) -> str: + def cell(value: str) -> str: + return value.replace("|", "\\|").replace("\r", " ").replace("\n", " ") + + rows = ["| Target | Check | Result | Detail |", "| --- | --- | --- | --- |"] + rows += [ + f"| {cell(r.target)} | {cell(r.check)} | {'skip' if r.skipped else 'pass' if r.ok else 'fail'} | {cell(r.detail)} |" + for r in self.results + ] + return "\n".join(rows) + "\n" + + @property + def failed(self) -> bool: + return any(not r.ok for r in self.results) + + +def run( + command: Sequence[str], cwd: Path, env: Mapping[str, str] +) -> subprocess.CompletedProcess[str]: + print("$ " + " ".join(command)) + result = subprocess.run( + list(command), + cwd=cwd, + env=dict(env), + capture_output=True, + text=True, + encoding="utf-8", + check=False, + timeout=COMMAND_TIMEOUT_SECONDS, + ) + print(neutralize(result.stdout + result.stderr), end="") + return result + + +def clean_environment() -> dict[str, str]: + """The caller's environment without anything that would steer a child onto the source tree or another environment.""" + env = dict(os.environ) + for name in ("PYTHONPATH", "PYTHONHOME", "VIRTUAL_ENV", "UV_PROJECT_ENVIRONMENT"): + env.pop(name, None) + return env + + +def venv_python(venv: Path) -> Path: + return venv / ("Scripts/python.exe" if os.name == "nt" else "bin/python") + + +def export_requirements(project: Path, destination: Path, env: Mapping[str, str]) -> list[str]: + """The pip arguments that install the project's locked dependency groups without the project itself. + + The lock sits in the project directory itself, which a workspace member's does not. + """ + if not (project / "uv.lock").is_file(): + raise OSError("the project has no uv.lock to read its test dependencies from") + result = run( + [ + "uv", + "export", + "--frozen", + "--all-groups", + "--no-emit-project", + "--no-hashes", + "--output-file", + str(destination), + ], + project, + env, + ) + if result.returncode != 0: + raise OSError("uv export of the locked dependency groups failed") + return ["-r", str(destination)] + + +def consume( + kind: str, + artifact: Path, + line: str, + name: str, + version: str, + project: Path, + requirements: Sequence[str], + work: Path, + env: Mapping[str, str], + report: Report, +) -> None: + """Install one artifact into a fresh environment for one line, then assert and run the tests against it.""" + target = f"{kind} py{line}" + venv = work / f"{kind}-{line}" + created = run(["uv", "venv", "--python", line, str(venv)], work, env) + if not report.add(target, "environment", created.returncode == 0, f"uv venv --python {line}"): + return + python = str(venv_python(venv)) + # Both installs run from the project, so uv reads the project's own index settings and resolves a path dependency. + installed = run(["uv", "pip", "install", "--python", python, str(artifact)], project, env) + if not report.add(target, "install", installed.returncode == 0, artifact.name): + return + # The project is excluded from the groups, so only its dependencies and tools are added to the artifact's. + groups = run(["uv", "pip", "install", "--python", python, *requirements], project, env) + report.add(target, "test dependencies", groups.returncode == 0, "locked groups, no project") + + files = run([python, "-I", "-c", FILES_PROBE, name], work, env) + metadata = probe_rows(files.stdout) + if files.returncode != 0 or "VERSION" not in metadata: + report.add(target, "version", False, f"{name} is not installed") + return + got = metadata["VERSION"][0][0] + report.add(target, "version", got == version, f"installed {got}, build wrote {version}") + names = top_level_names(json.loads(metadata["FILES"][0][0])) + if not names: + # A distribution holding only scripts or data is valid, so nothing here can be imported or fail. + report.add( + target, + "import location", + True, + "the artifact provides no importable name", + skipped=True, + ) + else: + imported = run([python, "-I", "-c", IMPORT_PROBE, *names], work, env) + rows = probe_rows(imported.stdout) + roots = rows.get("ROOTS", [[]])[0] + bad = [f"{r[0]} failed {r[1]}" for r in rows.get("IMPORTFAIL", [])] + bad += [ + f"{r[0]} is at {r[1]}" + for r in rows.get("IMPORT", []) + if not r[1] or not is_under(r[1], roots) + ] + # A package that ends the probe early, with SystemExit(0) for one, prints no row for the names after it. + answered = {r[0] for key in ("IMPORT", "IMPORTFAIL") for r in rows.get(key, [])} + bad += [f"{n} was never reported" for n in names if n not in answered] + if imported.returncode != 0 and not bad: + bad.append("the import probe failed") + report.add( + target, + "import location", + not bad, + f"{names} from site-packages" if not bad else "; ".join(bad), + ) + + tests = project / "tests" + if not tests.is_dir(): + report.add(target, "tests", True, f"{tests.name} folder is absent", skipped=True) + return + # The working directory is outside the project, so the source tree is not on sys.path. + cache = f"cache_dir={work / '.pytest_cache'}" + outcome = run([python, "-m", "pytest", str(tests), *PYTEST_ARGUMENTS, "-o", cache], work, env) + if outcome.returncode == PYTEST_NO_TESTS: + report.add(target, "tests", True, "pytest collected no tests", skipped=True) + else: + report.add(target, "tests", outcome.returncode == 0, f"pytest exit {outcome.returncode}") + + +def check(project: Path, version: str, lines: Sequence[str], work: Path) -> int: + report = Report() + env = clean_environment() + name = project_name(project / "pyproject.toml") + artifacts = find_artifacts(project / "dist") + try: + requirements = export_requirements(project, work / "requirements.txt", env) + except OSError as error: + report.add("all", "test dependencies", False, str(error)) + requirements = [] + for line in lines: + print(f"::group::{escape_command(f'consume py{line}')}") + try: + for kind, artifact in artifacts.items(): + try: + consume( + kind, + artifact, + line, + name, + version, + project, + requirements, + work, + env, + report, + ) + except (OSError, ValueError, KeyError, subprocess.SubprocessError) as error: + # One artifact's unexpected failure must not hide the rows of the others. + report.add( + f"{kind} py{line}", "consume", False, f"{type(error).__name__}: {error}" + ) + finally: + print("::endgroup::") + summary = os.environ.get("GITHUB_STEP_SUMMARY") + if summary: + with open(summary, "a", encoding="utf-8") as handle: + handle.write(f"### Package consume check for {name} {version}\n\n{report.table()}\n") + return 1 if report.failed else 0 + + +def main(argv: Sequence[str] = ()) -> int: + argparse.ArgumentParser( + description=(__doc__ or "").splitlines()[0], + epilog="Reads PROJECT_DIR, PYPI_VERSION, PYTHON_VERSIONS (a JSON array), and WORK_DIR from the environment.", + ).parse_args(list(argv)) + project = Path(os.environ.get("PROJECT_DIR", "")).resolve() + version = os.environ.get("PYPI_VERSION", "") + work_dir = os.environ.get("WORK_DIR", "") + if not os.environ.get("PROJECT_DIR") or not project.is_dir() or not version or not work_dir: + print( + "::error::package-consume needs PROJECT_DIR, PYPI_VERSION, PYTHON_VERSIONS, and WORK_DIR." + ) + return 1 + try: + lines = parse_versions(os.environ.get("PYTHON_VERSIONS", "")) + except SystemExit as error: + print(f"::error::{escape_command(str(error))}") + return 1 + return check(project, version, lines, Path(work_dir).resolve()) + + +received: list[int] = [] + + +def on_signal(signum: int, frame: FrameType | None) -> None: + """Record the signal and raise KeyboardInterrupt, so every signal unwinds one path. + + A later signal is passed over, since it would cut the unwinding short. + A later signal can start inside this handler, so a call from this frame returns too. + """ + if received or (frame is not None and frame.f_code is on_signal.__code__): + return + received.append(signum) + raise KeyboardInterrupt + + +def interrupted() -> int: + """Name the recorded signal, and return it as the status the caller re-raises.""" + signum = signal.Signals(received[0] if received else signal.SIGINT) + print(f"{Path(__file__).name}: interrupted by {signum.name}.", file=sys.stderr) + return signum + + +def reraise(signum: signal.Signals) -> None: + """End this process by `signum`, so a caller sees the signal rather than an exit status.""" + with contextlib.suppress(OSError): + sys.stdout.flush() + sys.stderr.flush() + if sys.platform == "win32": + sys.exit(130) + signal.signal(signum, signal.SIG_DFL) + os.kill(os.getpid(), signum) + sys.exit(128 + signum) + + +def entry(argv: Sequence[str]) -> int: + """Run main with one handler for both signals, returning the signal's number where one arrived.""" + signal.signal(signal.SIGTERM, on_signal) + if signal.getsignal(signal.SIGINT) is signal.default_int_handler: + signal.signal(signal.SIGINT, on_signal) + try: + return main(argv) + except KeyboardInterrupt: + return interrupted() + + +if __name__ == "__main__": + status = entry(sys.argv[1:]) + if received: + reraise(signal.Signals(received[0])) + sys.exit(status) diff --git a/.github/actions/pypi-build-default/action.yml b/.github/actions/pypi-build-default/action.yml index 708b7e801..3670d287c 100644 --- a/.github/actions/pypi-build-default/action.yml +++ b/.github/actions/pypi-build-default/action.yml @@ -27,6 +27,11 @@ inputs: required: false default: "0.11.8" +outputs: + version: + description: The PEP 440 version written into the build, which the built wheel and sdist carry. + value: ${{ steps.pypiver.outputs.version }} + runs: using: composite steps: diff --git a/.github/skills/workflow-ci-contract/references/d-guarantees.md b/.github/skills/workflow-ci-contract/references/d-guarantees.md index bdfdf1d53..e4a37f852 100644 --- a/.github/skills/workflow-ci-contract/references/d-guarantees.md +++ b/.github/skills/workflow-ci-contract/references/d-guarantees.md @@ -17,6 +17,7 @@ The required behaviors, organized by domain. Each is a **MUST**, and its `Output - **D1.5 One required aggregator gates merge.** Input: any PR. Output: a single aggregator job must **succeed**. It must run under `if: always()`, so a failed or skipped dependency cannot skip the gate itself. It must also `needs:` the validation job, and the `changes` and `smoke-build` jobs too wherever the repo has a smoke build. It must treat a **skipped** smoke build as pass, and **block** on `failure`/`cancelled`. Its name is ruleset-bound: the job `name:` and the ruleset `context:` are the same string and MUST be renamed together, never independently. The workflow holding it MUST trigger on `pull_request`. A gate without a `pull_request` trigger never runs the validator's pull-request-only steps, the prose gate among them. A workflow any other event also triggers yields that name only when `github.event_name == 'pull_request'`, through an expression `name:`. Otherwise a dispatch or push run on a PR's head posts the required context without the PR run's gates. *Prevents: a paths-filter error letting a target-changing PR merge unbuilt.* - **D1.6 Coverage is reported to Codecov (C# and Python).** Input: a C# or Python repo that has tests for that type. Output: the validation job runs those tests under coverage collection, and a `codecov/codecov-action` step uploads the report. The collection is `dotnet test --coverage --coverage-output-format cobertura --results-directory ./coverage`, leaving `--coverage-output` unset so each test project writes its own report rather than overwriting a shared one. A bare call resolves one workspace from the working directory, so it fails at a root holding none or more than one. Unless the repository root holds exactly one solution or project, the hub's validator therefore runs the collection once per tracked `*Tests*.csproj` with `--project`. It names no solution in that case, since a solution holding no test project fails the run. Or it is `pytest --cov-report=xml` in a Python directory with its own `uv.lock` or `requirements*.txt`, whose own `pyproject.toml` selects what to measure. Or it is `coverage run -m unittest discover -s tests` then `coverage xml` in a `lint-only` one. The upload is **best-effort** (`continue-on-error` and/or `fail_ci_if_error: false`), so a Codecov outage or an absent token never reds the gate. Each leg **fails its test step when the run wrote no report**. The reason is that the best-effort upload reads a missing report exactly as it reads a healthy run. A second reason is that, on the Python leg, `--cov-report=xml` alone selects nothing to measure. The C# leg renames each report to `coverage-.cobertura.xml` before the upload step reads the directory, since `codecov-cli`'s own finder does not match the default name. A repo owning its validator rather than calling the hub's owes that rename itself. `CODECOV_TOKEN` lives in the repo's **actions** and **dependabot** secret stores. The token is in the second because a run triggered by a Dependabot pull request reads the Dependabot store. Without the token there, the upload would otherwise skip silently on every bot pull request. A caller reaching the reusable validator across repositories names the secret it passes (`secrets:` with `CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}`). It does so on its pull request path and its publisher path alike. That is because `secrets: inherit` is documented for a caller in the same organization or enterprise, which a personal account is not. A call by local path stays inside one repository, where the caller's own store is the one the callee reads. So `secrets: inherit` is available there instead of naming each secret. The repo ships a **`.codecov.yml`** at the repository root. It sets the project and patch statuses to **`informational: true`**, so a coverage delta never gates a pull request. A repo whose quality bar requires a threshold may turn that off. The same file excludes intentionally-untested, non-shipped code (an example or benchmark project) from the denominator via `ignore`. Codecov reads its configuration under several names, but `.codecov.yml` is the only one the fleet accepts. So a copy under any other name is drift to rename. Coverage output is a build artifact, so `.gitignore` excludes it. The C# invocation runs under **Microsoft.Testing.Platform**, and the runner declaration, package references, and version floor an MTP-based test project needs are `CODESTYLE.md`'s .NET side. The Python invocation needs **`pytest-cov`** and a coverage selector, which are `CODESTYLE.md`'s Python side. A Python directory declared in the validator's `python-directories` input owes a `tests/` suite whatever its profile, so the validator fails one that has none. N/A for a repo carrying no tests for that type. *Prevents: coverage silently going unreported, and a coverage regression blocking an unrelated pull request.* - **D1.7 A built NuGet package is consumed before it publishes.** Input: a repo whose `build-nuget` job runs the hub's default leaf, in a smoke run or a publish run alike. Output: after the leaf packs, the job restores, builds, and runs a throwaway console project against that exact `.nupkg`. It does so once per target framework the project declares. Each consumer lives outside the checkout, so the caller's `global.json` and `Directory.Build.props` do not apply. Its `nuget.config` resolves the package ID, and the ID of each sibling package in the folder holding the build output, only from that folder. Every other ID resolves from nuget.org. Its package cache is its own, so neither a cached nor a published copy can stand in for the artifact under test. The consumer loads the package assembly and calls `GetExportedTypes()`. The check asserts from `obj/project.assets.json` that the package resolved from the `lib//` folder of the consumer's own framework. It also asserts that the loaded assembly's `TargetFrameworkAttribute` matches that folder. A `netstandard` framework is consumed under the SDK line `global.json` selects, or the newest declared line where there is none. It is asserted against the folder it resolved. A framework the check does not consume is reported skipped. Examples are .NET Framework, `netcoreapp3.1`, and a platform-specific `netX.Y-windows`. The attribute row of a `netstandard` consumer resolving such a folder is skipped too. Four static assertions join them. The package's `lib//` folders equal the declared frameworks. The nuspec `` equals the build version. The nuspec holds a dependency group per framework. A symbol package exists where the project enables symbols. Every declared `netX.Y` and `netstandard` framework is consumed and reported with one summary row per assertion. A failed step ends that framework's rows rather than the run. The job fails at the end if any failed. The check covers a library package, whose assemblies sit under `lib//`. The check uploads nothing, so it honors D1.3. It runs inside the build job, so a failure blocks the publish job that `needs:` that build. A caller's own `build-nuget` hook replaces the whole leaf and is outside the check. A caller's own `.github/actions/package-consume/action.yml` runs once after the default check. It receives the declared frameworks as JSON beside the package ID, version, and package folder. *Prevents: a defect that exists only in the packed form shipping. One example is one target framework's assembly packed under every `lib//` folder while the tests, which reach the library through a project reference, stay green.* +- **D1.8 A built PyPI package is consumed before it publishes.** Input: a repo whose `build-pypi` job runs the hub's default leaf, in a smoke run or a publish run alike. Output: after the leaf builds, the job installs the wheel and, separately, the sdist into a fresh `uv venv`. It does so for each line of the `python-versions` input of `build-release-task.yml`. Empty runs the one line the root `.python-version` selects. Where there is none it runs the hub's fallback line. A caller that sets `python-versions` for both `validate-task.yml` and `build-release-task.yml` passes the same value to each. So the lines its tests run under are the lines its artifact is consumed under. Each environment lives outside the checkout. It installs the artifact, then the project's locked dependency groups from `uv.lock` without the project itself. The check asserts that `importlib.metadata` reports the version the leaf computed. It also asserts that every top-level name the installed distribution provides imports from the environment's site-packages, not the source tree. A distribution providing none, such as one of scripts only, reports that row skipped. It then runs the caller's `tests/` folder against the installed copy with pytest in `importlib` import mode. That run has the source tree off `sys.path` and the project's `pythonpath` setting cleared. Its working directory is outside the project. So the caller's suite must not read a path relative to the project root, or a tool setting read from the working directory. It must import a sibling helper as part of a package. The project directory holds its own `uv.lock`. A project with no `tests/` folder, or a run collecting no tests, is reported skipped rather than passed. Every line and artifact reports one summary row per assertion. A failed environment, install, or metadata read ends that artifact's rows rather than the run. The job fails at the end if any failed. The check uploads nothing, so it honors D1.3. It runs inside the build job, so a failure blocks the publish job that `needs:` that build. A caller's own `build-pypi` hook replaces the whole leaf and is outside the check. *Prevents: a defect that exists only in the built form shipping. One example is a module left out of the wheel while the tests, which import it from the source tree, stay green.* ### D2 - Input/State Validation at Entry diff --git a/.github/skills/workflow-ci-contract/references/test-methodology.md b/.github/skills/workflow-ci-contract/references/test-methodology.md index d5030643e..2e88b46d5 100644 --- a/.github/skills/workflow-ci-contract/references/test-methodology.md +++ b/.github/skills/workflow-ci-contract/references/test-methodology.md @@ -16,11 +16,13 @@ Most of the evidence is in the workflow files and the composite actions they rea D1.7 is read in the build job. A step after the default leaf plans the declared frameworks, then the `dotnet-sdk` action installs those runtime lines, then the consume check runs. None of them uploads. +D1.8 is read in the build job. A step after the default leaf runs the consume check. It receives the build's computed version and the `python-versions` list. Empty becomes the one line the root `.python-version` selects, or the hub's fallback line where there is none. It uploads nothing. + Cite what each verdict rests on. That is `file:line` for a file in the audited repo. It is the evidence's own name where a setting, a ruleset, or a secret name rather than a file is the evidence. Where the guarantee binds a workflow or composite action the audited repo only reaches, it is `/@` plus the `file:line` in that repo. The callee is read at the SHA the caller pins. An **N/A** verdict names the absent construct instead, there being no line to cite. ### 5B. End-to-End Trace Scenarios (No Execution, Deterministic from the YAML) -For each *applicable* scenario, evaluate every job's `if:`/`needs:` against the inputs. Emit the predicted **run/skip + version + release + artifact-end-state** table, then compare to the expected. A scenario governing a construct the repo does not contain is N/A, per `WORKFLOW.md` section 1, and an absent trigger is such a construct. Each scenario's trigger belongs to one workflow, so read that workflow's own `on:` block rather than the repo's type. For S1 to S4 the block is the pull request workflow's. For S5 to S10 and S14 it is the publisher's. For S15 it is whichever workflow reaches the `build-nuget` job. For S11 the block is the upstream tracker's, and for S12 and S13 the deploy workflow's. A publisher carrying only `workflow_dispatch` therefore records S5, S6 and S9 N/A, their push and schedule paths never firing there. A repo with no publisher lacks a construct every repo owes. So S7, S8, S10 and S14 fail there, and none is excluded from the verdict. S5, S6 and S9 turn on the `on:` block that publisher has yet to state, so each is judged once it lands. A publisher whose schedule never publishes, per D4.1, records the schedule paths of S7 and S9 N/A as well. Where a scenario's path runs through a workflow or composite action the repo only **calls**, trace that callee as the repo reaches it. Read it at the SHA the caller pins rather than at the callee's current default branch, which is the same evidence rule 5A states. Predicting from the callee's `main` predicts a table for YAML the audited repo never runs. A self-repository (`$/`) call or a job-level local (`./`) reusable-workflow call carries no pin of its own. It resolves at the calling workflow file's commit, so it is traced at that file's own commit. That commit is the SHA fixed by the pin that reached that file. Where that file is one of the audited repository's own workflows, it is the audited commit instead. A local (`./`) action reference carries no pin either, but it resolves against whatever the job checked out. So it is traced at that checkout's commit. That is the caller's commit where a reusable workflow called from another repository checks out its caller. Minimum set: +For each *applicable* scenario, evaluate every job's `if:`/`needs:` against the inputs. Emit the predicted **run/skip + version + release + artifact-end-state** table, then compare to the expected. A scenario governing a construct the repo does not contain is N/A, per `WORKFLOW.md` section 1, and an absent trigger is such a construct. Each scenario's trigger belongs to one workflow, so read that workflow's own `on:` block rather than the repo's type. For S1 to S4 the block is the pull request workflow's. For S5 to S10 and S14 it is the publisher's. For S15 it is whichever workflow reaches the `build-nuget` job, and for S16 the one reaching `build-pypi`. For S11 the block is the upstream tracker's, and for S12 and S13 the deploy workflow's. A publisher carrying only `workflow_dispatch` therefore records S5, S6 and S9 N/A, their push and schedule paths never firing there. A repo with no publisher lacks a construct every repo owes. So S7, S8, S10 and S14 fail there, and none is excluded from the verdict. S5, S6 and S9 turn on the `on:` block that publisher has yet to state, so each is judged once it lands. A publisher whose schedule never publishes, per D4.1, records the schedule paths of S7 and S9 N/A as well. Where a scenario's path runs through a workflow or composite action the repo only **calls**, trace that callee as the repo reaches it. Read it at the SHA the caller pins rather than at the callee's current default branch, which is the same evidence rule 5A states. Predicting from the callee's `main` predicts a table for YAML the audited repo never runs. A self-repository (`$/`) call or a job-level local (`./`) reusable-workflow call carries no pin of its own. It resolves at the calling workflow file's commit, so it is traced at that file's own commit. That commit is the SHA fixed by the pin that reached that file. Where that file is one of the audited repository's own workflows, it is the audited commit instead. A local (`./`) action reference carries no pin either, but it resolves against whatever the job checked out. So it is traced at that checkout's commit. That is the caller's commit where a reusable workflow called from another repository checks out its caller. Minimum set: | # | Input | Expected output | Exercises | | --- | --- | --- | --- | @@ -39,6 +41,7 @@ For each *applicable* scenario, evaluate every job's `if:`/`needs:` against the | S13 | deploy dispatch of a production environment from a non-default ref | **fails fast**, before anything is installed or written | D2.1 | | S14 | publish whose branch head gained different `.github/workflows` content after the build began | every update since a release bot's push or merge: release-create **skipped** and the publisher dispatched on the branch. In that case this run ends **cancelled** with its package publish jobs skipped (a Docker image already pushed). The dispatched run releases the head, queueing behind this run only where the head's publisher evaluates this run's group for a dispatch. A push landing after the branch is confirmed unmoved and before the dispatch is released as if it were such an update. That is an accepted, bounded limit per D4.7. Any other update: the step **fails**, nothing is released or dispatched | D4.1, D4.2, D4.5, D4.7 | | S15 | a smoke or publish run whose `build-nuget` job runs the hub default leaf, for a project declaring `net10.0;net11.0`. The package holds one framework's assembly under both `lib/` folders | the job plans both runtime lines, installs them, and consumes the package once per framework. It **fails** on the `TargetFrameworkAttribute` of the `lib/` folder holding the other framework's assembly, after reporting every other row. A correct package **passes**. The check uploads nothing in either run. A publish run's leaf has uploaded its artifacts already, and a failure leaves them to their retention and the dependent publish job **skipped** | D1.3, D1.7 | +| S16 | a smoke or publish run whose `build-pypi` job runs the hub default leaf, for a project with a `tests/` folder and a `python-versions` of `["3.13", "3.14"]`. Its wheel leaves out a module the tests import | the job builds, then consumes the wheel and the sdist under each line. It **fails** on the tests row of each artifact lacking the module, after reporting every other row. A correct package **passes** under both lines. The check uploads nothing in either run. A publish run's leaf has uploaded its artifact already. A failure leaves it to its retention, and the dependent publish job is **skipped** | D1.3, D1.8 | ### 5C. Live Probe (Where Warranted) diff --git a/.github/workflows/build-release-task.yml b/.github/workflows/build-release-task.yml index ecfa994a5..e9dd80999 100644 --- a/.github/workflows/build-release-task.yml +++ b/.github/workflows/build-release-task.yml @@ -107,6 +107,13 @@ on: required: false type: string default: '' + # Read by the build-pypi job's package consume check, which installs the built wheel and sdist once per entry. + # A caller passes validate-task.yml the same value, so the lines its tests run under are the lines the artifact is consumed under (WORKFLOW.md D1.8). + python-versions: + description: JSON array of the Python versions the built wheel and sdist are installed and tested under, one environment per entry and artifact, for example ["3.13", "3.14"]. Pass the same value as validate-task.yml's python-versions. Quote each entry, since an unquoted one is a JSON number rather than a version string. Empty consumes under the one line the caller's root .python-version selects, or the hub's fallback line, where it carries none. + required: false + type: string + default: '' secrets: # Not needed when enable_docker is false. DOCKER_HUB_USERNAME: @@ -319,6 +326,25 @@ jobs: assembly-file-version: ${{ needs.get-version.outputs.AssemblyFileVersion }} project-dir: ${{ inputs.pypi_project_dir }} + # The consume check refuses a whitespace-only or unquoted entry too, but only after the build has run. + # Checking here fails the job before the build, as validate-task.yml does for its own copy of the input. + - name: Validate python-versions input step + if: ${{ inputs.python-versions != '' && hashFiles('.github/actions/build-pypi/action.yml') == '' }} + env: + PYTHON_VERSIONS: ${{ inputs.python-versions }} + run: | + set -Eeuo pipefail + if ! jq -e -s 'length == 1 and (.[0] | type == "array" and length > 0 and all(.[]; type == "string" and test("\\S")))' <<<"$PYTHON_VERSIONS" >/dev/null 2>&1; then + # The annotation carries the rejected value, so it is escaped per the workflow command encoding rules first. + # A raw newline would end the annotation and let whatever follows it start a command of its own. + # The percent substitution runs first, since running it after the others would re-encode the percent each of them just introduced. + escaped=${PYTHON_VERSIONS//'%'/%25} + escaped=${escaped//$'\r'/%0D} + escaped=${escaped//$'\n'/%0A} + echo "::error::The python-versions input must be a non-empty JSON array of non-empty quoted version strings, for example '[\"3.13\", \"3.14\"]', got: $escaped" + exit 1 + fi + - name: Select Python version step id: python-version if: ${{ hashFiles('.github/actions/build-pypi/action.yml') == '' }} @@ -327,6 +353,7 @@ jobs: warn: 'false' - name: Run hub build-pypi default step + id: pypi-build-default if: ${{ hashFiles('.github/actions/build-pypi/action.yml') == '' }} uses: $/.github/actions/pypi-build-default with: @@ -337,6 +364,17 @@ jobs: version-file: ${{ inputs.pypi_version_file }} python-version: ${{ steps.python-version.outputs.selected }} + # The wheel and sdist are installed into fresh environments and the caller's tests run against them, before anything publishes, in smoke and publish runs alike. + # It uploads nothing, so D1.3 holds. + # A caller's own build-pypi hook is outside the check, since the hub cannot know where that hook wrote its distributions. + - name: Run package consume check step + if: ${{ hashFiles('.github/actions/build-pypi/action.yml') == '' }} + uses: $/.github/actions/package-consume-pypi + with: + project-dir: ${{ inputs.pypi_project_dir }} + version: ${{ steps.pypi-build-default.outputs.version }} + python-versions: ${{ inputs.python-versions || format('["{0}"]', steps.python-version.outputs.version) }} + # The hook only writes files, so the upload, its smoke gate (D1.3), and its retention (D5.4) stay here for every caller. build-release-asset: name: Build release asset job diff --git a/.github/workflows/test-pull-request.yml b/.github/workflows/test-pull-request.yml index bb7a61344..aa343e48b 100644 --- a/.github/workflows/test-pull-request.yml +++ b/.github/workflows/test-pull-request.yml @@ -84,6 +84,34 @@ jobs: set -Eeuo pipefail python3 scripts/package_consume_nuget_selftest.py + # The hub holds no shippable Python project, so this builds a constructed two-module package, builds it, and runs the package consume check against it. + # A correct package must pass, and one whose wheel excludes a module its tests import must fail. + # That proves the check can still see the defect it exists for. + pypi-consume-test: + name: PyPI package consume self-test job + runs-on: ubuntu-latest + timeout-minutes: 30 + permissions: + contents: read + steps: + + - name: Checkout code step + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + # The uv line the hub's PyPI leaf pins, so the flags the check relies on are proven on the uv a caller runs it under. + - name: Setup uv step + uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 + with: + version: 0.11.8 + ignore-nothing-to-cache: true + + - name: Run package consume self-test step + run: | + set -Eeuo pipefail + python3 scripts/package_consume_pypi_selftest.py + # GitHub Actions does not support required status checks on conditional jobs, so a single always-run aggregator gates the merge. # Its name is the ruleset-bound required status-check context, so rename it and the ruleset context together. # Only a pull_request run takes that name. @@ -91,7 +119,7 @@ jobs: check-workflow-status: name: ${{ github.event_name == 'pull_request' && 'Check pull request workflow status job' || 'Check workflow status job' }} runs-on: ubuntu-latest - needs: [ validate, windows-test, nuget-consume-test ] + needs: [ validate, windows-test, nuget-consume-test, pypi-consume-test ] if: always() steps: - name: Check workflow results step @@ -109,3 +137,7 @@ jobs: echo "Job 'nuget-consume-test' did not succeed (${{ needs.nuget-consume-test.result }}); refusing to pass." exit 1 fi + if [[ "${{ needs.pypi-consume-test.result }}" != "success" ]]; then + echo "Job 'pypi-consume-test' did not succeed (${{ needs.pypi-consume-test.result }}); refusing to pass." + exit 1 + fi diff --git a/WORKFLOW.md b/WORKFLOW.md index da050bcef..6bfd15ce0 100644 --- a/WORKFLOW.md +++ b/WORKFLOW.md @@ -145,6 +145,7 @@ The required behaviors, organized by domain. Each is a **MUST**, and its `Output - **D1.5 One required aggregator gates merge.** Input: any PR. Output: a single aggregator job must **succeed**. It must run under `if: always()`, so a failed or skipped dependency cannot skip the gate itself. It must also `needs:` the validation job, and the `changes` and `smoke-build` jobs too wherever the repo has a smoke build. It must treat a **skipped** smoke build as pass, and **block** on `failure`/`cancelled`. Its name is ruleset-bound: the job `name:` and the ruleset `context:` are the same string and MUST be renamed together, never independently. The workflow holding it MUST trigger on `pull_request`. A gate without a `pull_request` trigger never runs the validator's pull-request-only steps, the prose gate among them. A workflow any other event also triggers yields that name only when `github.event_name == 'pull_request'`, through an expression `name:`. Otherwise a dispatch or push run on a PR's head posts the required context without the PR run's gates. *Prevents: a paths-filter error letting a target-changing PR merge unbuilt.* - **D1.6 Coverage is reported to Codecov (C# and Python).** Input: a C# or Python repo that has tests for that type. Output: the validation job runs those tests under coverage collection, and a `codecov/codecov-action` step uploads the report. The collection is `dotnet test --coverage --coverage-output-format cobertura --results-directory ./coverage`, leaving `--coverage-output` unset so each test project writes its own report rather than overwriting a shared one. A bare call resolves one workspace from the working directory, so it fails at a root holding none or more than one. Unless the repository root holds exactly one solution or project, the hub's validator therefore runs the collection once per tracked `*Tests*.csproj` with `--project`. It names no solution in that case, since a solution holding no test project fails the run. Or it is `pytest --cov-report=xml` in a Python directory with its own `uv.lock` or `requirements*.txt`, whose own `pyproject.toml` selects what to measure. Or it is `coverage run -m unittest discover -s tests` then `coverage xml` in a `lint-only` one. The upload is **best-effort** (`continue-on-error` and/or `fail_ci_if_error: false`), so a Codecov outage or an absent token never reds the gate. Each leg **fails its test step when the run wrote no report**. The reason is that the best-effort upload reads a missing report exactly as it reads a healthy run. A second reason is that, on the Python leg, `--cov-report=xml` alone selects nothing to measure. The C# leg renames each report to `coverage-.cobertura.xml` before the upload step reads the directory, since `codecov-cli`'s own finder does not match the default name. A repo owning its validator rather than calling the hub's owes that rename itself. `CODECOV_TOKEN` lives in the repo's **actions** and **dependabot** secret stores. The token is in the second because a run triggered by a Dependabot pull request reads the Dependabot store. Without the token there, the upload would otherwise skip silently on every bot pull request. A caller reaching the reusable validator across repositories names the secret it passes (`secrets:` with `CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}`). It does so on its pull request path and its publisher path alike. That is because `secrets: inherit` is documented for a caller in the same organization or enterprise, which a personal account is not. A call by local path stays inside one repository, where the caller's own store is the one the callee reads. So `secrets: inherit` is available there instead of naming each secret. The repo ships a **`.codecov.yml`** at the repository root. It sets the project and patch statuses to **`informational: true`**, so a coverage delta never gates a pull request. A repo whose quality bar requires a threshold may turn that off. The same file excludes intentionally-untested, non-shipped code (an example or benchmark project) from the denominator via `ignore`. Codecov reads its configuration under several names, but `.codecov.yml` is the only one the fleet accepts. So a copy under any other name is drift to rename. Coverage output is a build artifact, so `.gitignore` excludes it. The C# invocation runs under **Microsoft.Testing.Platform**, and the runner declaration, package references, and version floor an MTP-based test project needs are `CODESTYLE.md`'s .NET side. The Python invocation needs **`pytest-cov`** and a coverage selector, which are `CODESTYLE.md`'s Python side. A Python directory declared in the validator's `python-directories` input owes a `tests/` suite whatever its profile, so the validator fails one that has none. N/A for a repo carrying no tests for that type. *Prevents: coverage silently going unreported, and a coverage regression blocking an unrelated pull request.* - **D1.7 A built NuGet package is consumed before it publishes.** Input: a repo whose `build-nuget` job runs the hub's default leaf, in a smoke run or a publish run alike. Output: after the leaf packs, the job restores, builds, and runs a throwaway console project against that exact `.nupkg`. It does so once per target framework the project declares. Each consumer lives outside the checkout, so the caller's `global.json` and `Directory.Build.props` do not apply. Its `nuget.config` resolves the package ID, and the ID of each sibling package in the folder holding the build output, only from that folder. Every other ID resolves from nuget.org. Its package cache is its own, so neither a cached nor a published copy can stand in for the artifact under test. The consumer loads the package assembly and calls `GetExportedTypes()`. The check asserts from `obj/project.assets.json` that the package resolved from the `lib//` folder of the consumer's own framework. It also asserts that the loaded assembly's `TargetFrameworkAttribute` matches that folder. A `netstandard` framework is consumed under the SDK line `global.json` selects, or the newest declared line where there is none. It is asserted against the folder it resolved. A framework the check does not consume is reported skipped. Examples are .NET Framework, `netcoreapp3.1`, and a platform-specific `netX.Y-windows`. The attribute row of a `netstandard` consumer resolving such a folder is skipped too. Four static assertions join them. The package's `lib//` folders equal the declared frameworks. The nuspec `` equals the build version. The nuspec holds a dependency group per framework. A symbol package exists where the project enables symbols. Every declared `netX.Y` and `netstandard` framework is consumed and reported with one summary row per assertion. A failed step ends that framework's rows rather than the run. The job fails at the end if any failed. The check covers a library package, whose assemblies sit under `lib//`. The check uploads nothing, so it honors D1.3. It runs inside the build job, so a failure blocks the publish job that `needs:` that build. A caller's own `build-nuget` hook replaces the whole leaf and is outside the check. A caller's own `.github/actions/package-consume/action.yml` runs once after the default check. It receives the declared frameworks as JSON beside the package ID, version, and package folder. *Prevents: a defect that exists only in the packed form shipping. One example is one target framework's assembly packed under every `lib//` folder while the tests, which reach the library through a project reference, stay green.* +- **D1.8 A built PyPI package is consumed before it publishes.** Input: a repo whose `build-pypi` job runs the hub's default leaf, in a smoke run or a publish run alike. Output: after the leaf builds, the job installs the wheel and, separately, the sdist into a fresh `uv venv`. It does so for each line of the `python-versions` input of `build-release-task.yml`. Empty runs the one line the root `.python-version` selects. Where there is none it runs the hub's fallback line. A caller that sets `python-versions` for both `validate-task.yml` and `build-release-task.yml` passes the same value to each. So the lines its tests run under are the lines its artifact is consumed under. Each environment lives outside the checkout. It installs the artifact, then the project's locked dependency groups from `uv.lock` without the project itself. The check asserts that `importlib.metadata` reports the version the leaf computed. It also asserts that every top-level name the installed distribution provides imports from the environment's site-packages, not the source tree. A distribution providing none, such as one of scripts only, reports that row skipped. It then runs the caller's `tests/` folder against the installed copy with pytest in `importlib` import mode. That run has the source tree off `sys.path` and the project's `pythonpath` setting cleared. Its working directory is outside the project. So the caller's suite must not read a path relative to the project root, or a tool setting read from the working directory. It must import a sibling helper as part of a package. The project directory holds its own `uv.lock`. A project with no `tests/` folder, or a run collecting no tests, is reported skipped rather than passed. Every line and artifact reports one summary row per assertion. A failed environment, install, or metadata read ends that artifact's rows rather than the run. The job fails at the end if any failed. The check uploads nothing, so it honors D1.3. It runs inside the build job, so a failure blocks the publish job that `needs:` that build. A caller's own `build-pypi` hook replaces the whole leaf and is outside the check. *Prevents: a defect that exists only in the built form shipping. One example is a module left out of the wheel while the tests, which import it from the source tree, stay green.* ### D2 - Input/State Validation at Entry @@ -226,11 +227,13 @@ Most of the evidence is in the workflow files and the composite actions they rea D1.7 is read in the build job. A step after the default leaf plans the declared frameworks, then the `dotnet-sdk` action installs those runtime lines, then the consume check runs. None of them uploads. +D1.8 is read in the build job. A step after the default leaf runs the consume check. It receives the build's computed version and the `python-versions` list. Empty becomes the one line the root `.python-version` selects, or the hub's fallback line where there is none. It uploads nothing. + Cite what each verdict rests on. That is `file:line` for a file in the audited repo. It is the evidence's own name where a setting, a ruleset, or a secret name rather than a file is the evidence. Where the guarantee binds a workflow or composite action the audited repo only reaches, it is `/@` plus the `file:line` in that repo. The callee is read at the SHA the caller pins. An **N/A** verdict names the absent construct instead, there being no line to cite. ### 5B. End-to-End Trace Scenarios (No Execution, Deterministic from the YAML) -For each *applicable* scenario, evaluate every job's `if:`/`needs:` against the inputs. Emit the predicted **run/skip + version + release + artifact-end-state** table, then compare to the expected. A scenario governing a construct the repo does not contain is N/A, per `WORKFLOW.md` section 1, and an absent trigger is such a construct. Each scenario's trigger belongs to one workflow, so read that workflow's own `on:` block rather than the repo's type. For S1 to S4 the block is the pull request workflow's. For S5 to S10 and S14 it is the publisher's. For S15 it is whichever workflow reaches the `build-nuget` job. For S11 the block is the upstream tracker's, and for S12 and S13 the deploy workflow's. A publisher carrying only `workflow_dispatch` therefore records S5, S6 and S9 N/A, their push and schedule paths never firing there. A repo with no publisher lacks a construct every repo owes. So S7, S8, S10 and S14 fail there, and none is excluded from the verdict. S5, S6 and S9 turn on the `on:` block that publisher has yet to state, so each is judged once it lands. A publisher whose schedule never publishes, per D4.1, records the schedule paths of S7 and S9 N/A as well. Where a scenario's path runs through a workflow or composite action the repo only **calls**, trace that callee as the repo reaches it. Read it at the SHA the caller pins rather than at the callee's current default branch, which is the same evidence rule 5A states. Predicting from the callee's `main` predicts a table for YAML the audited repo never runs. A self-repository (`$/`) call or a job-level local (`./`) reusable-workflow call carries no pin of its own. It resolves at the calling workflow file's commit, so it is traced at that file's own commit. That commit is the SHA fixed by the pin that reached that file. Where that file is one of the audited repository's own workflows, it is the audited commit instead. A local (`./`) action reference carries no pin either, but it resolves against whatever the job checked out. So it is traced at that checkout's commit. That is the caller's commit where a reusable workflow called from another repository checks out its caller. Minimum set: +For each *applicable* scenario, evaluate every job's `if:`/`needs:` against the inputs. Emit the predicted **run/skip + version + release + artifact-end-state** table, then compare to the expected. A scenario governing a construct the repo does not contain is N/A, per `WORKFLOW.md` section 1, and an absent trigger is such a construct. Each scenario's trigger belongs to one workflow, so read that workflow's own `on:` block rather than the repo's type. For S1 to S4 the block is the pull request workflow's. For S5 to S10 and S14 it is the publisher's. For S15 it is whichever workflow reaches the `build-nuget` job, and for S16 the one reaching `build-pypi`. For S11 the block is the upstream tracker's, and for S12 and S13 the deploy workflow's. A publisher carrying only `workflow_dispatch` therefore records S5, S6 and S9 N/A, their push and schedule paths never firing there. A repo with no publisher lacks a construct every repo owes. So S7, S8, S10 and S14 fail there, and none is excluded from the verdict. S5, S6 and S9 turn on the `on:` block that publisher has yet to state, so each is judged once it lands. A publisher whose schedule never publishes, per D4.1, records the schedule paths of S7 and S9 N/A as well. Where a scenario's path runs through a workflow or composite action the repo only **calls**, trace that callee as the repo reaches it. Read it at the SHA the caller pins rather than at the callee's current default branch, which is the same evidence rule 5A states. Predicting from the callee's `main` predicts a table for YAML the audited repo never runs. A self-repository (`$/`) call or a job-level local (`./`) reusable-workflow call carries no pin of its own. It resolves at the calling workflow file's commit, so it is traced at that file's own commit. That commit is the SHA fixed by the pin that reached that file. Where that file is one of the audited repository's own workflows, it is the audited commit instead. A local (`./`) action reference carries no pin either, but it resolves against whatever the job checked out. So it is traced at that checkout's commit. That is the caller's commit where a reusable workflow called from another repository checks out its caller. Minimum set: | # | Input | Expected output | Exercises | | --- | --- | --- | --- | @@ -249,6 +252,7 @@ For each *applicable* scenario, evaluate every job's `if:`/`needs:` against the | S13 | deploy dispatch of a production environment from a non-default ref | **fails fast**, before anything is installed or written | D2.1 | | S14 | publish whose branch head gained different `.github/workflows` content after the build began | every update since a release bot's push or merge: release-create **skipped** and the publisher dispatched on the branch. In that case this run ends **cancelled** with its package publish jobs skipped (a Docker image already pushed). The dispatched run releases the head, queueing behind this run only where the head's publisher evaluates this run's group for a dispatch. A push landing after the branch is confirmed unmoved and before the dispatch is released as if it were such an update. That is an accepted, bounded limit per D4.7. Any other update: the step **fails**, nothing is released or dispatched | D4.1, D4.2, D4.5, D4.7 | | S15 | a smoke or publish run whose `build-nuget` job runs the hub default leaf, for a project declaring `net10.0;net11.0`. The package holds one framework's assembly under both `lib/` folders | the job plans both runtime lines, installs them, and consumes the package once per framework. It **fails** on the `TargetFrameworkAttribute` of the `lib/` folder holding the other framework's assembly, after reporting every other row. A correct package **passes**. The check uploads nothing in either run. A publish run's leaf has uploaded its artifacts already, and a failure leaves them to their retention and the dependent publish job **skipped** | D1.3, D1.7 | +| S16 | a smoke or publish run whose `build-pypi` job runs the hub default leaf, for a project with a `tests/` folder and a `python-versions` of `["3.13", "3.14"]`. Its wheel leaves out a module the tests import | the job builds, then consumes the wheel and the sdist under each line. It **fails** on the tests row of each artifact lacking the module, after reporting every other row. A correct package **passes** under both lines. The check uploads nothing in either run. A publish run's leaf has uploaded its artifact already. A failure leaves it to its retention, and the dependent publish job is **skipped** | D1.3, D1.8 | ### 5C. Live Probe (Where Warranted) @@ -285,7 +289,7 @@ The table files each scenario in section 5B's table under exactly one row, which | Construct the repo contains | Scenarios it reaches | | --- | --- | | A pull request workflow with a validation job and the required aggregator | S2, S3 | -| A build target: a `changes` filter entry, a smoke build, and a leaf that builds it | S1, S4, and S15 for the hub default NuGet leaf | +| A build target: a `changes` filter entry, a smoke build, and a leaf that builds it | S1, S4, S15 for the hub default NuGet leaf, and S16 for the hub default PyPI leaf | | A publisher, meaning a workflow that cuts the release | S7, S8, S10, S14, plus S5 and S6 wherever its own `on:` admits a push, and S9 wherever it admits a push or a schedule | | An upstream-version tracker and its merge-bot | S11 | | A deploy workflow targeting a filesystem on a host the project owns | S12, S13 | @@ -296,7 +300,7 @@ What each type adds beyond that, and how its leaf behaves, is below. - **`dotnet-publish`.** The target runs a sequential `dotnet publish` runtime loop inside one composite-action job. Configuration is Release on the default branch and Debug otherwise. A non-smoke run builds the full runtime set, archives the combined output as a `.7z`, and uploads it as `release-asset--dotnet-publish`. The archive is named from the project file stem unless `dotnet_publish_asset_name` overrides it. A smoke run builds a **strict, non-empty subset** of that runtime set and skips the archive and upload steps, so it uploads nothing. S1 smoke-builds that subset after a .NET project change. S7 attaches the 7z from a non-smoke run. The non-default leg sets `prerelease=true`, and the default leg sets `prerelease=false`. GitHub marks the stable default release "Latest" automatically. - **`nuget`.** The leaf uploads both `release-asset--nuget` and `nuget-build-` on a non-smoke run and pushes nothing. A separate `publish-nuget` job in the repo's own publisher consumes the second and runs `dotnet nuget push *.nupkg --skip-duplicate`. It then deletes that artifact under the download step's own success (D5.2). Section 3's `Output Seam by Destination` says why the push sits there rather than in the leaf. Configuration is Release on the default branch, Debug otherwise. The default leaf is followed by the D1.7 package consume check in smoke and publish runs alike. A caller's own `build-nuget` hook is outside it. The release-asset `.7z` carries the packages alone, never the loose build output, since each package already holds every target framework's build under its own `lib//`. Where symbols are enabled (`snupkg`), the push auto-carries the paired `.snupkg` to NuGet.org's symbol server and the release-asset `.7z` also contains it, a triple surface. NuGet.org derives `isPrerelease` from the SemVer2 `-g` suffix (the workflow sets no such flag). Test: S15 consumes the package per framework. S7 non-default leg publishes a prerelease package + asset, default a stable. S9 re-run is a server-side `--skip-duplicate` no-op. 5C: query NuGet.org for both versions and the symbol package. -- **`pypi`.** The leaf builds and uploads `pypi-build-`. A **separate** `publish-pypi` job (with `environment: pypi`, `id-token: write`, `actions: write`) does the OIDC Trusted-Publishing upload with `skip-existing: true`. It then **consume-then-deletes** the build artifact under the download step's own success (D5.2). So on S9 the build artifact is deleted even though the `release-asset-*` delete is skipped. The version is the `X.Y.Z` core of `SemVer2` with `.dev0` appended on `develop` only, per D3.4. PyPI contributes no `release-asset-*`. A PyPI-only repo sets `expect_release_assets: false` at the caller. Test: S7 default leg publishes a release, non-default a `.dev0`. S9 is a `skip-existing` no-op. 5C inspects the `dist/*` filenames and the compute-version log. +- **`pypi`.** The leaf builds and uploads `pypi-build-`. A **separate** `publish-pypi` job (with `environment: pypi`, `id-token: write`, `actions: write`) does the OIDC Trusted-Publishing upload with `skip-existing: true`. It then **consume-then-deletes** the build artifact under the download step's own success (D5.2). So on S9 the build artifact is deleted even though the `release-asset-*` delete is skipped. The version is the `X.Y.Z` core of `SemVer2` with `.dev0` appended on `develop` only, per D3.4. PyPI contributes no `release-asset-*`. The default leaf is followed by the D1.8 package consume check in smoke and publish runs alike. A caller's own `build-pypi` hook is outside it. A PyPI-only repo sets `expect_release_assets: false` at the caller. Test: S16 consumes the wheel and the sdist per Python line. S7 default leg publishes a release, non-default a `.dev0`. S9 is a `skip-existing` no-op. 5C inspects the `dist/*` filenames and the compute-version log. - **`docker`.** The leaf pushes the default branch multi-arch (amd64+arm64) and any other branch `amd64`-only, with a per-branch registry buildcache. A single-image repo caches to `:buildcache-`. A multi-image repo varies the cache **repository** rather than the tag, `:buildcache-` for each image, since the tag alone cannot distinguish two images. `cache-to` writes only the built branch and only on push, and `cache-from` reads both branches. It contributes no `release-asset-*`, so a Docker-only repo's caller passes `expect_release_assets: false`. The readme job (`peter-evans/dockerhub-description`, `DOCKER_HUB_ACCESS_TOKEN`) runs **only** when the default branch publishes, whether called directly or reached through the hub-hosted `publish-docker-readme-task.yml`. Where the Docker Hub overview differs from the project README, the repo publishes a `Docker/README.md` through that task, the Hub description being size-limited. The docker-readme task validates its two mutually-exclusive input sources, `repositories` against `manifest`+`manifest-jq`. It defaults to the calling repository where neither is supplied. A multi-image repo derives its publish matrix from the manifest. Docker **always re-pushes** the image, independently of a skipped release-create (S9). The tests that follow assume the default tag matrix, which a caller-supplied `matrix` or `docker-prepare` hook replaces. Test: S7 default leg pushes `latest` + the version tag and updates the readme. Non-default pushes `develop` + the version tag (amd64 only). S9 still re-pushes. 5C Docker probe needs `DOCKER_HUB_*` secrets and same-repo (not fork) runs. - **`library` (a worked example, not a fleet type).** No such leaf ships, so this row walks D6.4's add-a-target procedure rather than an existing shape. The target is a single new leaf that validates, zips, and uploads `release-asset--library` (`retention-days: 1` per D5.4, upload gated on smoke being false per D1.3). Adding it means a new `enable_library` input, and a `build-library` job and its `github-release` and `build-docker` `needs:` entries, in the release task. In the PR workflow it means a `library` paths-filter entry, `changes` output, and `smoke-build` enable-forward. Without that last one, D1.1 never smoke-builds the library. In the publisher, it means the `enable_library` value the publisher passes, and the library's paths in its `on.push.paths` where it carries a `push` trigger. **Only a repo that owns its release task can make the release-task half of that edit.** The hub-hosted release task declares a closed input set, and a call passing an input it does not declare fails. So a repo calling it sets `enable_release_asset` instead and carries the leaf as its `build-release-asset` hook. The hook writes the zip, and the task uploads it under `release-asset--build-release-asset`, skipping the upload on a smoke run. Keep `expect_release_assets: true` (it has a file target, unlike Docker). The caller's own validation job is replaced by a type-appropriate validator only where the reusable one cannot express this repo's validation. The aggregator is then re-pointed to the replacement (D1.2). `smoke-build` keeps `needs: [changes]`, as D1.2 has it. `version.json` and the NBGV `get-version` **job** are retained (they own the tag). Test: S1 smoke runs validate+zip and uploads nothing. S7 attaches the zip, prerelease on the non-default leg. S9 on a push re-run skips release-create and the asset-delete (the existing zip is untouched, no registry push). A `workflow_dispatch` re-run, by contrast, is D4.4's refresh case rather than S9's, re-uploading then re-deleting the asset. - **`upstream-wrapper`.** The repo tracks an upstream project's releases rather than versioning its own code. A scheduled resolver writes a `name -> version` state file and opens a per-branch bump pull request. The merge-bot auto-merges it, or leaves it for the maintainer where the tracker sets `auto-merge: false` (D8.3). The build leaf MUST read that state file for its build or image version instead of `SemVer2`, while NBGV still tags the release (D3.5). That is because the tracker ships without this consumer wiring. Test: S11 traces the bump from resolver to the publish that ships it, which for a merge-bot-merged `main` pin is D8.3's gated publish. Nothing in this row depends on which build-target types the wrapper also declares. diff --git a/catalog/snippets/workflows/publish-release.yml b/catalog/snippets/workflows/publish-release.yml index b6c847e4f..4da75858a 100644 --- a/catalog/snippets/workflows/publish-release.yml +++ b/catalog/snippets/workflows/publish-release.yml @@ -64,6 +64,8 @@ jobs: github: true enable_docker: false enable_pypi: false + # A PyPI caller sets python-versions here to the value it passes validate-task.yml. + # The built wheel and sdist are then consumed under the lines its tests run under (WORKFLOW.md D1.8). enable_dotnet_publish: false nuget_project: ./Widget/Widget.csproj diff --git a/catalog/snippets/workflows/test-pull-request-smoke.yml b/catalog/snippets/workflows/test-pull-request-smoke.yml index b42253436..b4184be12 100644 --- a/catalog/snippets/workflows/test-pull-request-smoke.yml +++ b/catalog/snippets/workflows/test-pull-request-smoke.yml @@ -69,6 +69,8 @@ jobs: # This one-target caller turns off the ones it does not build and leaves its own on that default, the same set its publish-release.yml passes. enable_docker: false enable_pypi: false + # A PyPI caller sets python-versions here to the value it passes validate-task.yml. + # The built wheel and sdist are then consumed under the lines its tests run under (WORKFLOW.md D1.8). enable_dotnet_publish: false nuget_project: ./Widget/Widget.csproj # On a pull_request event github.ref_name is the PR ref (for example 123/merge), never the target branch. diff --git a/docs/reusable-workflows.md b/docs/reusable-workflows.md index d3608932a..57a98124e 100644 --- a/docs/reusable-workflows.md +++ b/docs/reusable-workflows.md @@ -89,7 +89,7 @@ The target set. A row exists once its hub task ships, and until then the row is | `merge-bot-task.yml` | none, extra bot rules are a `with:` input | not applicable | | `validate-task.yml` | `validate` (a repo's own domain checks, beyond the fleet doc-lint block and the generic unit-test job), `install-test-deps` (a `test-matrix` leg's dependency install and per-leg checks). Also `pre-test`, for system tools the .NET tests need | no-op for `validate`, none for `install-test-deps`, which is required where `test-matrix` or `test-matrix-file` is set. None for `pre-test` | | `get-version-task.yml`, `publish-plan-task.yml` | none | not applicable | -| `build-release-task.yml` | `dotnet-publish`, `build-nuget`, `build-pypi`, `build-release-asset` | `dotnet-publish-default`, `nuget-build-default` followed by `package-consume-nuget`, `pypi-build-default`, none for `build-release-asset`, which is required where `enable_release_asset` is set | +| `build-release-task.yml` | `dotnet-publish`, `build-nuget`, `build-pypi`, `build-release-asset` | `dotnet-publish-default`, `nuget-build-default` followed by `package-consume-nuget`, `pypi-build-default` followed by `package-consume-pypi`, none for `build-release-asset`, which is required where `enable_release_asset` is set | | `build-docker-task.yml` | `docker-prepare` (extra tags, build-args, matrix), `docker-build-base` | vanilla single-target from `image`, base build required when `build-base` | | `publish-docker-readme-task.yml` | `docker-readme-transform` | publish `Docker/README.md` or `README.md` as-is | | `check-upstream-version-task.yml` | `resolve-upstream` | none, required | @@ -392,6 +392,8 @@ jobs: # This one-target caller turns off the ones it does not build and leaves its own on that default, the same set its publish-release.yml passes. enable_docker: false enable_pypi: false + # A PyPI caller sets python-versions here to the value it passes validate-task.yml. + # The built wheel and sdist are then consumed under the lines its tests run under (WORKFLOW.md D1.8). enable_dotnet_publish: false nuget_project: ./Widget/Widget.csproj # On a pull_request event github.ref_name is the PR ref (for example 123/merge), never the target branch. @@ -507,6 +509,8 @@ The .NET upload carries one fixed `dotnet` flag, the same in every leg. A caller A repo whose .NET projects multi-target names every line they build in `dotnet-versions`, such as `'["11.0", "10.0"]'` for `net10.0;net11.0`. It is the .NET counterpart of `python-versions`, and it adds no matrix leg. One SDK builds every target framework, and one `dotnet test` runs each framework's tests under that framework's own runtime. So the one `unit-test` job installs every listed line beside the selected one. The first entry is the `X.Y` line the root `global.json` selects, the highest target framework's, since the release builds on it. The `dotnet-sdk` action refuses a first entry naming another line, with a named cause. It also refuses an entry that is not a quoted `X.Y` line. The `Build test matrix job` runs that check first, before any job builds, as it does for `python-versions`. The `lint` job repeats it, since it does not wait on that job. A caller carrying no `global.json` `sdk.version` installs every entry instead of the fallback line. Without the input, a lower framework's tests run only where the runner image happens to carry its runtime. +A PyPI repo names the lines its built package must work under in the `python-versions` input of `build-release-task.yml`, as it does for `validate-task.yml`. The two inputs hold the same value, so the lines its tests run under are the lines its wheel and sdist are consumed under. The input is validated like the unit-test one. Empty consumes under the one line the root `.python-version` selects. Where there is none it consumes under the hub's fallback line. After the hub default builds, the `build-pypi` job installs the wheel and, separately, the sdist into a fresh environment per line, outside the checkout. It then installs the project's locked dependency groups without the project. It asserts the installed version and that the package imports from site-packages. It runs the caller's `tests/` folder against the installed copy, from outside the project. The suite must read no path relative to the project root, and no tool setting from the working directory. It must import a sibling helper as part of a package. The project directory must hold its own `uv.lock`. A smoke run runs it unchanged and uploads nothing, and a caller's own `build-pypi` hook is outside it. WORKFLOW.md D1.8 states the guarantee. + A repo whose pytest legs differ by dependency versions names them in `test-matrix`, a JSON array of objects, one leg per entry. It replaces the `python-versions` legs. Each entry needs a string `label` naming the leg and its Codecov flag. It may carry a `python-version`, defaulting to the first `python-versions` entry, or to the selected line where `python-versions` is empty. Any other key is the repo's own, passed through to its hook. ```yaml @@ -630,6 +634,8 @@ jobs: github: true enable_docker: false enable_pypi: false + # A PyPI caller sets python-versions here to the value it passes validate-task.yml. + # The built wheel and sdist are then consumed under the lines its tests run under (WORKFLOW.md D1.8). enable_dotnet_publish: false nuget_project: ./Widget/Widget.csproj diff --git a/pyproject.toml b/pyproject.toml index 32487808f..383ab1193 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -15,7 +15,7 @@ python_version = "3.13" # That is because mypy's own flow analysis does not narrow it away. platform = "linux" files = ["spec", "host-setup", "scripts", "tests"] -mypy_path = [".github/actions/package-consume-nuget", ".github/actions/prose-gate", ".github/actions/python-directories", ".github/actions/repo-gate"] +mypy_path = [".github/actions/package-consume-nuget", ".github/actions/package-consume-pypi", ".github/actions/prose-gate", ".github/actions/python-directories", ".github/actions/repo-gate"] exclude = 'scripts/(prose_lint|repo_gate)\.py' # A script declaring a library inline runs through uv. diff --git a/scripts/package_consume_pypi_selftest.py b/scripts/package_consume_pypi_selftest.py new file mode 100755 index 000000000..8576c1fc2 --- /dev/null +++ b/scripts/package_consume_pypi_selftest.py @@ -0,0 +1,202 @@ +#!/usr/bin/env python3 +"""Prove the PyPI package consume check passes a good package and fails one whose wheel leaves out a module. + +The hub holds no shippable Python project, so this builds a constructed `src/` package in a temporary directory. +The package has two modules and a tests folder importing both, and it is built with hatchling as the fleet does. +The first run must pass on every Python line. +The second package's wheel excludes one module through hatch build configuration. +Its tests still pass from `src/`, while the packaged form lacks the module. +That run must fail on every line. + +Needs uv and network access, since uv downloads the interpreters and the build backend. +Exits 1 when any run does not behave as expected. +""" + +from __future__ import annotations + +import argparse +import contextlib +import os +import signal +import subprocess +import sys +import tempfile +from collections.abc import Sequence +from pathlib import Path +from types import FrameType + +from run_deadline import run_with_deadline + +ACTION = Path(__file__).resolve().parents[1] / ".github/actions/package-consume-pypi" +VERSION = "1.2.3.dev0" +LINES = ("3.13", "3.14") +PYPROJECT = """[project] +name = "contoso-widget" +dynamic = ["version"] +requires-python = ">=3.13" + +[dependency-groups] +dev = ["pytest"] + +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[tool.hatch.version] +path = "src/contoso_widget/_version.py" + +[tool.hatch.build.targets.wheel] +packages = ["src/contoso_widget"] +{extra} +[tool.pytest.ini_options] +pythonpath = ["src"] +""" +EXCLUDE = 'exclude = ["src/contoso_widget/extra.py"]\n' +FILES = { + "src/contoso_widget/__init__.py": "", + "src/contoso_widget/_version.py": f'__version__ = "{VERSION}"\n', + "src/contoso_widget/core.py": 'def name() -> str:\n return "core"\n', + "src/contoso_widget/extra.py": 'def name() -> str:\n return "extra"\n', + "tests/test_widget.py": ( + "from contoso_widget import core, extra\n\n\n" + "def test_names() -> None:\n" + ' assert (core.name(), extra.name()) == ("core", "extra")\n' + ), +} + + +def run(command: Sequence[str], cwd: Path, env: dict[str, str] | None = None) -> tuple[int, str]: + result = run_with_deadline( + list(command), 900, cwd=cwd, env=env, text=True, encoding="utf-8", stderr=subprocess.STDOUT + ) + return result.returncode, result.stdout + + +def build(root: Path, extra: str) -> Path | None: + """Write the constructed project, lock it, and build it, returning its folder or None on a build failure.""" + project = root + project.mkdir(parents=True) + (project / "pyproject.toml").write_text(PYPROJECT.format(extra=extra), encoding="utf-8") + for name, text in FILES.items(): + path = project / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + for command in (["uv", "lock"], ["uv", "build"]): + code, output = run(command, project) + if code != 0: + print(output) + print(f"`{' '.join(command)}` failed on the constructed project.") + return None + return project + + +def consume(project: Path, work: Path) -> tuple[int, str]: + env = { + **os.environ, + "PROJECT_DIR": str(project), + "PYPI_VERSION": VERSION, + "PYTHON_VERSIONS": '["' + '", "'.join(LINES) + '"]', + "WORK_DIR": str(work), + } + env.pop("GITHUB_STEP_SUMMARY", None) + work.mkdir(parents=True) + return run([sys.executable, str(ACTION / "package_consume_pypi.py")], work, env) + + +def verdicts(output: str) -> list[str]: + return [line for line in output.splitlines() if line.startswith(("PASS ", "FAIL ", "SKIP "))] + + +def main(argv: Sequence[str] = ()) -> int: + argparse.ArgumentParser(description=(__doc__ or "").splitlines()[0]).parse_args(list(argv)) + failures = 0 + with tempfile.TemporaryDirectory(prefix="package-consume-selftest.") as name: + root = Path(name) + good = build(root / "good", "") + bad = build(root / "bad", EXCLUDE) + if good is None or bad is None: + return 1 + code, output = consume(good, root / "work-good") + print("Good package:") + print("\n".join(verdicts(output))) + # A healthy run covers every artifact and line, so an empty or skip-only output is not a pass. + joined = "\n".join(verdicts(output)) + absent = [ + f"{kind} py{line}" + for line in LINES + for kind in ("wheel", "sdist") + if f"PASS [{kind} py{line}] tests:" not in joined + ] + if code != 0 or any(line.startswith("FAIL ") for line in verdicts(output)) or absent: + print(output) + print(f"EXPECTED PASS on every tests row and the check failed, missing {absent}.") + failures += 1 + code, output = consume(bad, root / "work-bad") + print("Package whose wheel excludes the extra module:") + print("\n".join(verdicts(output))) + # Every line must see both artifacts fail, since the sdist's build reads the same configuration as the wheel's. + joined = "\n".join(verdicts(output)) + missed = [ + f"{kind} py{line}" + for line in LINES + for kind in ("wheel", "sdist") + if f"FAIL [{kind} py{line}] tests:" not in joined + ] + if code == 0 or missed: + print(output) + print(f"EXPECTED FAIL on the tests row for {missed} and it did not.") + failures += 1 + print("SELF-TEST " + ("FAILED" if failures else "OK")) + return 1 if failures else 0 + + +received: list[int] = [] + + +def on_signal(signum: int, frame: FrameType | None) -> None: + """Record the signal and raise KeyboardInterrupt, so every signal unwinds one path. + + A later signal is passed over, since it would cut the unwinding short. + A later signal can start inside this handler, so a call from this frame returns too. + """ + if received or (frame is not None and frame.f_code is on_signal.__code__): + return + received.append(signum) + raise KeyboardInterrupt + + +def interrupted() -> int: + """Name the recorded signal, and return it as the status the caller re-raises.""" + signum = signal.Signals(received[0] if received else signal.SIGINT) + print(f"{Path(__file__).name}: interrupted by {signum.name}.", file=sys.stderr) + return signum + + +def reraise(signum: signal.Signals) -> None: + """End this process by `signum`, so a caller sees the signal rather than an exit status.""" + with contextlib.suppress(OSError): + sys.stdout.flush() + sys.stderr.flush() + if sys.platform == "win32": + sys.exit(130) + signal.signal(signum, signal.SIG_DFL) + os.kill(os.getpid(), signum) + sys.exit(128 + signum) + + +def entry(argv: Sequence[str]) -> int: + """Run main with one handler for both signals, returning the signal's number where one arrived.""" + signal.signal(signal.SIGTERM, on_signal) + if signal.getsignal(signal.SIGINT) is signal.default_int_handler: + signal.signal(signal.SIGINT, on_signal) + try: + return main(argv) + except KeyboardInterrupt: + return interrupted() + + +if __name__ == "__main__": + status = entry(sys.argv[1:]) + if received: + reraise(signal.Signals(received[0])) + sys.exit(status) diff --git a/spec/project-types.json b/spec/project-types.json index 563d90a0c..57fb41922 100644 --- a/spec/project-types.json +++ b/spec/project-types.json @@ -46,7 +46,7 @@ { "id": "python.coverage.codecov", "verdict": "letter", "assert": "Every Python directory with tests runs them under coverage and uploads the report to Codecov via codecov/codecov-action, best-effort (continue-on-error and fail_ci_if_error: false). A directory with a uv.lock or a requirements*.txt runs pytest --cov-report=xml, and because --cov-report=xml alone measures nothing and writes no file, it declares pytest-cov among its test dependencies, a dev dependency group in a uv project and a requirements*.txt entry on pip, and selects the coverage source in its own pyproject.toml, an addopts --cov= entry in practice. A lint-only directory runs coverage run -m unittest discover -s tests, then coverage xml. The validator's Python leg runs in each directory the caller declares in python-directories, or at the root where it declares none and a root pyproject.toml is tracked. It deletes the directory's coverage.xml before the run and fails the test step when the run did not write it, and it fails a declared directory that has no tests/. CODECOV_TOKEN is stored in both the repo actions and dependabot secrets stores, the second so the upload does not skip on a Dependabot PR, and the caller maps it to the reusable validator by name. N/A for a repo carrying no tests for this type, which the validator permits only at an undeclared root. In a mixed repo the .codecov.yml file-presence is still required by any co-present type that has tests, e.g. csharp.", "intentRef": "WORKFLOW.md" }, { "id": "python.directories.declared", "verdict": "letter", "assert": "A repository carrying a tracked .py file other than the catalog's carried hub_fetch_run.py or its former name hub-fetch-run.py declares the python type, or suppresses that discovery advisory with a driftNote naming (python.directories.declared) and its reason, per spec/type-model.md. Every such file sits in a directory the registry's pythonDirectories names, or anywhere under the root where it names none and a root pyproject.toml is tracked. Every caller of the hub's validate-task.yml passes exactly those directories in its python-directories input, as a literal (|) block or a single value, so the audit can see a missing declaration the validator itself only warns about. A root tests/ suite with no root uv.lock or requirements*.txt is never run by the undeclared root default, so a lint-only root declares '.' and a root declaring [project] adds a manifest. spec/audit.py checks each of these mechanically.", "intentRef": "WORKFLOW.md" }, { "id": "python.uvlock.pinned", "verdict": "letter", "assert": "Build profile: the committed uv.lock resolves to LF through the repository-wide .editorconfig and .gitattributes defaults. A CRLF-native operational repo adds a narrow uv.lock LF override only if it adopts the uv build profile. N/A for a non-uv Python repo (a Home Assistant integration on pip/requirements) and for the lint-only profile (no uv.lock by definition).", "intentRef": "GOVERNANCE.md#line-endings", "minProfile": "build" }, - { "id": "python.version.consistent", "verdict": "letter", "assert": "Where a root .python-version is present, it names the repository's Python line as X.Y on its first line that is neither blank nor a comment. The line is the repository's own and need not be the hub's fallback line. A directory whose pyproject.toml has a [project] table sets its requires-python floor to that line and sets none of ruff target-version, mypy python_version, or pyright pythonVersion, since ruff reads its target from requires-python and each checker from the interpreter it runs under. A directory with no [project] table has nothing to derive them from, so it sets each of the three it configures to that line. A carried Python devcontainer's image tag names the same line. So does the first entry of any python-versions value a caller passes the hub's validate-task.yml. N/A for a repo carrying no .python-version.", "intentRef": "CODESTYLE.md" }, + { "id": "python.version.consistent", "verdict": "letter", "assert": "Where a root .python-version is present, it names the repository's Python line as X.Y on its first line that is neither blank nor a comment. The line is the repository's own and need not be the hub's fallback line. A directory whose pyproject.toml has a [project] table sets its requires-python floor to that line and sets none of ruff target-version, mypy python_version, or pyright pythonVersion, since ruff reads its target from requires-python and each checker from the interpreter it runs under. A directory with no [project] table has nothing to derive them from, so it sets each of the three it configures to that line. A carried Python devcontainer's image tag names the same line. So does the first entry of any python-versions value a caller passes the hub's validate-task.yml. A caller that passes python-versions to both validate-task.yml and build-release-task.yml passes the same value to each, so the lines its tests run under are the lines its built artifact is consumed under (WORKFLOW.md D1.8). N/A for a repo carrying no .python-version.", "intentRef": "CODESTYLE.md" }, { "id": "python.scripts.uvx", "verdict": "letter", "assert": "Lint-only profile only: the tools run via uvx (no project install, no lockfile). A uvx @ literal in a run: step is not Dependabot-trackable, and the fleet rule pins only what Dependabot auto-updates and otherwise runs latest, never a manual pin that goes stale. So CI runs ruff at the version the hub validator's python-tool-pins action reads from its requirements.txt, which the hub's Dependabot pip ecosystem bumps, and runs uvx mypy@latest. A carrier's VS Code tasks and README run the unpinned latest, and the hub's own tasks take that requirements.txt as a requirement. N/A for the build profile, whose uv form pins tool versions via uv.lock + uv sync --frozen instead, and whose pip form takes a tool's version from the requirements*.txt that Dependabot's pip ecosystem bumps where a directory declared in python-directories installs that tool into its .venv.", "intentRef": "CODESTYLE.md" } ] }, diff --git a/tests/test_cli_usage.py b/tests/test_cli_usage.py index 6f74bdd47..d2b73429f 100755 --- a/tests/test_cli_usage.py +++ b/tests/test_cli_usage.py @@ -107,6 +107,7 @@ NO_REQUIRED_ARGUMENT = frozenset( { ".github/actions/package-consume-nuget/package_consume_nuget.py", + ".github/actions/package-consume-pypi/package_consume_pypi.py", ".github/actions/prose-gate/prose_lint.py", ".github/actions/python-directories/python_directories.py", ".github/actions/repo-gate/repo_gate.py", @@ -139,6 +140,7 @@ "scripts/enable_hooks.py", "scripts/host_gate.py", "scripts/package_consume_nuget_selftest.py", + "scripts/package_consume_pypi_selftest.py", "scripts/pr_review_copilot.py", "scripts/prose_lint.py", "scripts/repo_gate.py", diff --git a/tests/test_package_consume_pypi.py b/tests/test_package_consume_pypi.py new file mode 100755 index 000000000..1593cda31 --- /dev/null +++ b/tests/test_package_consume_pypi.py @@ -0,0 +1,380 @@ +#!/usr/bin/env python3 +"""Drive the PyPI package consume check's pure logic against constructed projects. + +Nothing here builds or installs a package. +The end-to-end proof is the hub's own self-test job in test-pull-request.yml. + +Run as `python3 tests/test_package_consume_pypi.py`, or under `python3 -m unittest discover -s tests`. +""" + +from __future__ import annotations + +import contextlib +import io +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +import yaml + +sys.path.insert( + 0, str(Path(__file__).resolve().parents[1] / ".github/actions/package-consume-pypi") +) +import package_consume_pypi as pcp + + +class VersionsTests(unittest.TestCase): + def test_a_json_array_of_strings_is_the_list_without_duplicates(self) -> None: + self.assertEqual(pcp.parse_versions('["3.13", " 3.14 ", "3.13"]'), ["3.13", "3.14"]) + + def test_anything_else_is_refused(self) -> None: + for raw in ("", "not json", "[]", "[3.13]", '[" "]', '"3.13"', '{"a": "3.13"}'): + with self.subTest(raw=raw), self.assertRaises(SystemExit): + pcp.parse_versions(raw) + + +class TopLevelNamesTests(unittest.TestCase): + def test_packages_modules_and_extensions_are_names_and_metadata_is_not(self) -> None: + files = [ + "contoso_widget/__init__.py", + "contoso_widget/core.py", + "contoso_widget/__pycache__/core.cpython-313.pyc", + "single.py", + "speedups.cpython-313-x86_64-linux-gnu.so", + "contoso_widget-1.2.3.dist-info/METADATA", + "contoso_widget-1.2.3.data/scripts/tool", + "contoso_widget.pth", + "../../../bin/contoso-tool", + "not-an-identifier/x.py", + "LICENSE", + "README.md", + ] + self.assertEqual(pcp.top_level_names(files), ["contoso_widget", "single", "speedups"]) + + def test_windows_separators_are_read(self) -> None: + self.assertEqual(pcp.top_level_names(["contoso_widget\\core.py"]), ["contoso_widget"]) + + +class OutputTests(unittest.TestCase): + def test_a_line_leading_workflow_command_in_child_output_is_broken(self) -> None: + text = "ok\n::error::forged\n ::notice::indented\nmid ::x\n::stop-commands::t" + out = pcp.neutralize(text) + self.assertFalse(any(line.lstrip().startswith("::") for line in out.splitlines())) + self.assertIn(" : :notice::indented", out) + self.assertIn("mid ::x", out) + self.assertIn(": :error::forged", out) + + +class ProbeTests(unittest.TestCase): + def test_an_import_that_leaves_a_partial_line_does_not_swallow_the_row(self) -> None: + with tempfile.TemporaryDirectory() as name: + (Path(name) / "noisy.py").write_text("import sys\nsys.stdout.write('loading')\n") + result = subprocess.run( + [sys.executable, "-c", pcp.IMPORT_PROBE, "noisy"], + cwd=name, + env={**os.environ, "PYTHONIOENCODING": "utf-8"}, + capture_output=True, + text=True, + encoding="utf-8", + check=False, + timeout=60, + ) + rows = pcp.probe_rows(result.stdout) + self.assertEqual([r[0] for r in rows["IMPORT"]], ["noisy"]) + + +class LocationTests(unittest.TestCase): + def test_under_a_root_is_inside_and_a_sibling_prefix_is_not(self) -> None: + roots = ["/venv/lib/site-packages"] + self.assertTrue(pcp.is_under("/venv/lib/site-packages/contoso_widget/__init__.py", roots)) + self.assertFalse(pcp.is_under("/venv/lib/site-packages-other/contoso_widget.py", roots)) + self.assertFalse(pcp.is_under("/work/src/contoso_widget/__init__.py", roots)) + self.assertFalse(pcp.is_under("/venv/lib/site-packages/x.py", [])) + + def test_probe_rows_group_by_their_first_column(self) -> None: + rows = pcp.probe_rows("noise\nIMPORT\ta\t/x\nIMPORT\tb\t/y\nROOTS\t/r\n") + self.assertEqual(rows["IMPORT"], [["a", "/x"], ["b", "/y"]]) + self.assertEqual(rows["ROOTS"], [["/r"]]) + + +class ProjectTests(unittest.TestCase): + def test_name_and_groups_are_read_from_the_pyproject(self) -> None: + with tempfile.TemporaryDirectory() as name: + path = Path(name) / "pyproject.toml" + path.write_text( + '[project]\nname = "contoso-widget"\n\n[dependency-groups]\ndev = ["pytest"]\n' + 'docs = ["mkdocs"]\n', + encoding="utf-8", + ) + self.assertEqual(pcp.project_name(path), "contoso-widget") + path.write_text("[tool.x]\n", encoding="utf-8") + with self.assertRaises(SystemExit): + pcp.project_name(path) + + def test_one_wheel_and_one_sdist_are_required(self) -> None: + with tempfile.TemporaryDirectory() as name: + dist = Path(name) + with self.assertRaises(SystemExit): + pcp.find_artifacts(dist) + (dist / "contoso_widget-1.0-py3-none-any.whl").write_bytes(b"") + with self.assertRaises(SystemExit): + pcp.find_artifacts(dist) + (dist / "contoso_widget-1.0.tar.gz").write_bytes(b"") + self.assertEqual(sorted(pcp.find_artifacts(dist)), ["sdist", "wheel"]) + (dist / "contoso_widget-1.1-py3-none-any.whl").write_bytes(b"") + with self.assertRaises(SystemExit): + pcp.find_artifacts(dist) + + def test_a_project_without_a_lock_is_an_error(self) -> None: + with tempfile.TemporaryDirectory() as name, self.assertRaises(OSError): + pcp.export_requirements(Path(name), Path(name) / "r.txt", {}) + + def test_a_project_with_a_lock_installs_the_exported_file(self) -> None: + with tempfile.TemporaryDirectory() as name: + project = Path(name) + (project / "uv.lock").write_text("", encoding="utf-8") + done = mock.Mock(returncode=0, stdout="", stderr="") + with ( + mock.patch.object(pcp.subprocess, "run", return_value=done) as runner, + contextlib.redirect_stdout(io.StringIO()), + ): + arguments = pcp.export_requirements(project, project / "r.txt", {}) + command = runner.call_args.args[0] + self.assertEqual(arguments, ["-r", str(project / "r.txt")]) + for flag in ("--frozen", "--all-groups", "--no-emit-project"): + self.assertIn(flag, command) + + def test_a_failed_export_is_an_error(self) -> None: + with tempfile.TemporaryDirectory() as name: + project = Path(name) + (project / "uv.lock").write_text("", encoding="utf-8") + done = mock.Mock(returncode=2, stdout="", stderr="") + with ( + mock.patch.object(pcp.subprocess, "run", return_value=done), + contextlib.redirect_stdout(io.StringIO()), + self.assertRaises(OSError), + ): + pcp.export_requirements(project, project / "r.txt", {}) + + +class ConsumeTests(unittest.TestCase): + """consume() with its commands stubbed, so each early return and skip is driven.""" + + def drive( + self, project: Path, probes: dict[str, str], pytest_status: int = 0 + ) -> dict[str, str]: + def fake_run(command: list[str], cwd: Path, env: dict[str, str]) -> mock.Mock: + self.cwds.append((command, cwd)) + if "-c" in command: + probe = command[command.index("-c") + 1] + key = "files" if "dist.version" in probe else "import" + return mock.Mock(returncode=0, stdout=probes[key], stderr="") + if "pytest" in command: + return mock.Mock(returncode=pytest_status, stdout="", stderr="") + return mock.Mock(returncode=0, stdout="", stderr="") + + report = pcp.Report() + with ( + mock.patch.object(pcp, "run", fake_run), + contextlib.redirect_stdout(io.StringIO()), + ): + pcp.consume( + "wheel", + Path("w.whl"), + "3.13", + "contoso-widget", + "1.2.3", + project, + [], + project, + {}, + report, + ) + return { + r.check: ("skip" if r.skipped else "pass" if r.ok else "fail") for r in report.results + } + + cwds: list[tuple[list[str], Path]] + + def setUp(self) -> None: + self.cwds = [] + + def test_installs_run_in_the_project_and_the_tests_run_outside_it(self) -> None: + with tempfile.TemporaryDirectory() as name: + project = Path(name) / "project" + work = Path(name) / "work" + (project / "tests").mkdir(parents=True) + work.mkdir() + report = pcp.Report() + probes = {"files": self.FILES, "import": self.GOOD} + + def fake_run(command: list[str], cwd: Path, env: dict[str, str]) -> mock.Mock: + self.cwds.append((command, cwd)) + if "-c" in command: + key = ( + "files" if "dist.version" in command[command.index("-c") + 1] else "import" + ) + return mock.Mock(returncode=0, stdout=probes[key], stderr="") + return mock.Mock(returncode=0, stdout="", stderr="") + + with mock.patch.object(pcp, "run", fake_run), contextlib.redirect_stdout(io.StringIO()): + pcp.consume( + "wheel", + Path("w.whl"), + "3.13", + "contoso-widget", + "1.2.3", + project, + ["-r", "x"], + work, + {}, + report, + ) + installs = [cwd for command, cwd in self.cwds if command[:3] == ["uv", "pip", "install"]] + pytests = [cwd for command, cwd in self.cwds if "pytest" in command] + self.assertEqual(installs, [project, project]) + self.assertEqual(pytests, [work]) + + FILES = 'VERSION\t1.2.3\nFILES\t["contoso_widget/__init__.py"]\n' + GOOD = "ROOTS\t/venv/site\nIMPORT\tcontoso_widget\t/venv/site/contoso_widget/__init__.py\n" + + def test_a_source_tree_import_fails_the_location_row(self) -> None: + with tempfile.TemporaryDirectory() as name: + rows = self.drive( + Path(name), + { + "files": self.FILES, + "import": "ROOTS\t/venv/site\nIMPORT\tcontoso_widget\t/src/contoso_widget/__init__.py\n", + }, + ) + self.assertEqual(rows["import location"], "fail") + + def test_a_distribution_with_no_importable_name_skips_the_location_row(self) -> None: + with tempfile.TemporaryDirectory() as name: + rows = self.drive( + Path(name), + { + "files": 'VERSION\t1.2.3\nFILES\t["contoso_widget-1.2.3.dist-info/METADATA"]\n', + "import": "", + }, + ) + self.assertEqual(rows["import location"], "skip") + + def test_a_name_the_probe_never_reported_fails_the_location_row(self) -> None: + with tempfile.TemporaryDirectory() as name: + rows = self.drive(Path(name), {"files": self.FILES, "import": "ROOTS\t/venv/site\n"}) + self.assertEqual(rows["import location"], "fail") + + def test_a_version_mismatch_fails_and_a_missing_tests_folder_skips(self) -> None: + with tempfile.TemporaryDirectory() as name: + rows = self.drive( + Path(name), {"files": self.FILES.replace("1.2.3", "9.9.9"), "import": self.GOOD} + ) + self.assertEqual(rows["version"], "fail") + self.assertEqual(rows["import location"], "pass") + self.assertEqual(rows["tests"], "skip") + + def test_pytest_collecting_nothing_skips_and_a_failing_run_fails(self) -> None: + with tempfile.TemporaryDirectory() as name: + project = Path(name) + (project / "tests").mkdir() + probes = {"files": self.FILES, "import": self.GOOD} + self.assertEqual(self.drive(project, probes, 5)["tests"], "skip") + self.assertEqual(self.drive(project, probes, 1)["tests"], "fail") + self.assertEqual(self.drive(project, probes, 0)["tests"], "pass") + + +class ReportTests(unittest.TestCase): + def test_a_failure_is_an_escaped_annotation_and_a_table_row(self) -> None: + report = pcp.Report() + buffer = io.StringIO() + with contextlib.redirect_stdout(buffer): + report.add("wheel py3.13", "tests", False, "a|b\n::error::forged") + lines = buffer.getvalue().splitlines() + self.assertEqual(len([line for line in lines if line.startswith("::error::")]), 1) + self.assertIn("%0A", lines[1]) + self.assertTrue(report.failed) + self.assertIn("a\\|b", report.table()) + + def test_a_skipped_row_is_not_a_failure_and_reads_skip(self) -> None: + report = pcp.Report() + with contextlib.redirect_stdout(io.StringIO()): + report.add("wheel py3.13", "tests", True, "no tests", skipped=True) + self.assertFalse(report.failed) + self.assertIn("| skip |", report.table()) + + +class InterruptTests(unittest.TestCase): + def setUp(self) -> None: + pcp.received.clear() + self.addCleanup(pcp.received.clear) + + def test_the_first_signal_is_recorded_and_a_later_one_is_passed_over(self) -> None: + with self.assertRaises(KeyboardInterrupt): + pcp.on_signal(15, None) + pcp.on_signal(2, None) + self.assertEqual(pcp.received, [15]) + + def test_an_interrupt_in_main_returns_the_recorded_signal(self) -> None: + def interrupt(_argv: object) -> int: + pcp.received.append(15) + raise KeyboardInterrupt + + with ( + mock.patch.object(pcp, "main", interrupt), + mock.patch.object(pcp.signal, "signal"), + contextlib.redirect_stderr(io.StringIO()) as err, + ): + self.assertEqual(pcp.entry([]), 15) + self.assertIn("interrupted by SIGTERM", err.getvalue()) + + +class WiringTests(unittest.TestCase): + """No hub run reaches the build-pypi job, so the step wiring is held here.""" + + ROOT = Path(__file__).resolve().parents[1] + + def workflow(self) -> dict: + text = (self.ROOT / ".github/workflows/build-release-task.yml").read_text(encoding="utf-8") + return yaml.safe_load(text) + + def test_the_check_follows_the_hub_default_under_its_condition_and_uploads_nothing( + self, + ) -> None: + job = self.workflow()["jobs"]["build-pypi"] + steps = {step["name"]: (index, step) for index, step in enumerate(job["steps"])} + build = steps["Run hub build-pypi default step"] + check = steps["Run package consume check step"] + self.assertLess(build[0], check[0]) + self.assertEqual(check[1]["if"], build[1]["if"]) + self.assertNotIn("upload-artifact", check[1]["uses"]) + self.assertEqual( + check[1]["with"]["version"], "${{ steps.pypi-build-default.outputs.version }}" + ) + self.assertEqual(build[1]["id"], "pypi-build-default") + + def test_the_default_build_exports_the_version_it_wrote(self) -> None: + text = (self.ROOT / ".github/actions/pypi-build-default/action.yml").read_text("utf-8") + outputs = yaml.safe_load(text)["outputs"] + self.assertEqual(outputs["version"]["value"], "${{ steps.pypiver.outputs.version }}") + + def test_the_input_is_validated_like_the_unit_test_input(self) -> None: + workflow = self.workflow() + declared = workflow[True]["workflow_call"]["inputs"]["python-versions"] + self.assertEqual(declared["type"], "string") + self.assertEqual(declared["default"], "") + validate = (self.ROOT / ".github/workflows/validate-task.yml").read_text(encoding="utf-8") + job = workflow["jobs"]["build-pypi"] + step = next(s for s in job["steps"] if s["name"] == "Validate python-versions input step") + jq = next(line for line in step["run"].splitlines() if "jq -e -s" in line) + self.assertIn(jq.split("<<<")[0].split("if ! ")[1].strip(), validate) + self.assertEqual(step["env"]["PYTHON_VERSIONS"], "${{ inputs.python-versions }}") + self.assertIn("%25", step["run"]) + + +if __name__ == "__main__": + unittest.main() From e8582dcd8122ab6ad23279c4c01c6e03914b19ea Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Thu, 3 Dec 2026 07:42:16 -0800 Subject: [PATCH 3/7] Upload the PyPI Default Leaf's Wheel and Sdist as a Release Asset (#4616) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Part of #4609 ## What changes - The hub default PyPI leaf uploads `release-asset--pypi`, the wheel and sdist unzipped, gated on smoke being false, with `retention-days: 1`. - The github-release job already downloads `release-asset--*` with `merge-multiple` into `./Publish` and attaches `./Publish/*`, so the files land on the release directly. - WORKFLOW.md (D4.3, D6.1, section 3 seam text and diagram, section 6 `pypi` row), `docs/reusable-workflows.md`, the release-publish-mechanics reference, and the input comments in `build-release-task.yml` no longer say PyPI contributes no release asset. - A PyPI caller on the default leaf keeps `expect_release_assets` true. - `tests/test_release_guards.py` gains a test holding both default leaves to the name pattern, the smoke gate, and `retention-days: 1`. ## Local review findings left open after the edit budget - `pre-existing`, not filed: the PyPI leaf cannot see `expect_release_assets`, and the fleet's one PyPI caller carries its own hook. - `pre-existing`, not filed: no test holds that the build-pypi and build-nuget jobs forward `smoke` to the leaf. - `pre-existing`, not filed: the develop `.dev0` wheel keeps one filename across prereleases. - Not filed here: a spec/project-types.json assertion that a PyPI caller on the default leaf does not pass `expect_release_assets: false`. ## Rollout note A PyPI caller still passing `expect_release_assets: false` on the default leaf leaves an unconsumed artifact that retention reaps after a day. 🤖 Generated with [Claude Code](https://claude.com/claude-code) ## Summary by CodeRabbit * **New Features** * PyPI releases now include the built wheel and source distribution as downloadable assets in the corresponding GitHub release, alongside the existing PyPI publishing flow. * The default PyPI build skips both artifact uploads in smoke mode. * **Documentation** * Updated release workflow guidance to clarify when PyPI builds contribute release assets, including cases where custom publishing hooks do not upload them. --------- Co-authored-by: Claude Sonnet 5.5 --- .../references/release-publish-mechanics.md | 21 +++++++----- .../references/architecture.md | 7 ++-- .../references/d-guarantees.md | 4 +-- .../references/test-methodology.md | 2 +- .../branching-and-release-model | 2 +- .../.source-digests/workflow-ci-contract | 2 +- .../references/release-publish-mechanics.md | 21 +++++++----- .../references/architecture.md | 7 ++-- .../references/d-guarantees.md | 4 +-- .../references/test-methodology.md | 2 +- .github/actions/pypi-build-default/action.yml | 18 ++++++++-- .../references/release-publish-mechanics.md | 21 +++++++----- .../references/architecture.md | 7 ++-- .../references/d-guarantees.md | 4 +-- .../references/test-methodology.md | 2 +- .github/workflows/build-release-task.yml | 11 ++++--- WORKFLOW.md | 15 +++++---- docs/reusable-workflows.md | 4 +-- tests/test_release_guards.py | 33 +++++++++++++++++++ 19 files changed, 124 insertions(+), 63 deletions(-) diff --git a/.agents/skills/branching-and-release-model/references/release-publish-mechanics.md b/.agents/skills/branching-and-release-model/references/release-publish-mechanics.md index b3af6488d..0d3fce9f7 100644 --- a/.agents/skills/branching-and-release-model/references/release-publish-mechanics.md +++ b/.agents/skills/branching-and-release-model/references/release-publish-mechanics.md @@ -45,10 +45,12 @@ project-path inputs among them. Pick by where each artifact *goes*, not by language: - **Files attached to the GitHub Release** (zips, binaries, packaged libraries): a dotnet-publish - hook or a build-nuget hook per output, each uploading `release-asset--`. This is where the - .NET `dotnet publish` or `dotnet build` lives, though a package push does not. The hub default takes an explicit - project path, and a project needing different build behavior replaces the hook. A data-only - repo's own output (e.g. a symbol library) is a file target, which the `build-release-asset` hook + hook or a build-nuget hook per output, each uploading `release-asset--`. + The default PyPI leaf uploads one too. + The .NET `dotnet publish` lives in the dotnet-publish hook and `dotnet build` in the build-nuget hook, though a package push lives in neither. + The hub default takes an explicit project path. + A project needing different build behavior replaces the hook. + A data-only repo's own output (e.g. a symbol library) is a file target, which the `build-release-asset` hook builds when the caller sets `enable_release_asset: true`. The hook has no hub default, so the caller provides `.github/actions/build-release-asset/action.yml` and the task fails without it. - **Package-registry pushes** (NuGet.org, PyPI): each is split, and the push never sits in the @@ -61,11 +63,12 @@ Pick by where each artifact *goes*, not by language: build-nuget hook uploads a `nuget-build-` artifact for a separate `publish-nuget` job in the caller's own `publish-release.yml`. That job authenticates through `NuGet/login` and therefore carries `id-token: write` (plus `actions: write` to delete the artifact it consumed). The hook - *also* uploads a `release-asset-*` (.7z) for the GitHub release. PyPI is the same shape: the build-pypi hook only builds and uploads the - `pypi-build-` artifact. The separate `publish-pypi` job in the caller's own - `publish-release.yml` does the OIDC Trusted-Publishing upload, behind an `environment: pypi` - gate and with `skip-existing: true`. The `id-token: write` permission is granted only at that - one entry point. PyPI contributes **no** `release-asset-*`. + *also* uploads a `release-asset-*` (.7z) for the GitHub release. + PyPI is the same shape. + The hub default leaf uploads the `pypi-build-` artifact and a `release-asset--pypi` carrying the wheel and sdist. + The separate `publish-pypi` job in the caller's own `publish-release.yml` does the OIDC Trusted-Publishing upload. + It runs behind an `environment: pypi` gate and with `skip-existing: true`. + The `id-token: write` permission is granted only at that one entry point. - **Image-registry pushes** (Docker Hub): `build-docker-task.yml`, hub-hosted like `build-release-task.yml`, pushes the default branch multi-arch (amd64+arm64) and any other branch `amd64`-only, and contributes **no** `release-asset-*`. The image set comes from a docker-prepare hook (the hub default emits the diff --git a/.agents/skills/workflow-ci-contract/references/architecture.md b/.agents/skills/workflow-ci-contract/references/architecture.md index 07d73c83e..d887558d7 100644 --- a/.agents/skills/workflow-ci-contract/references/architecture.md +++ b/.agents/skills/workflow-ci-contract/references/architecture.md @@ -44,9 +44,10 @@ A target contributes a file to the GitHub release by uploading a workflow artifa flowchart LR dotnet[dotnet-publish] -->|release-asset-BRANCH-dotnet-publish| store[(run artifacts)] nuget[build-nuget] -->|release-asset-BRANCH-nuget| store + pypi[build-pypi] -->|release-asset-BRANCH-pypi| store store -->|pattern + merge-multiple| rel["github-release job (D6)"] nuget -->|nuget-build-BRANCH| pub["publish-TARGET job in the repo's own publisher"] - pypi[build-pypi] -->|pypi-build-BRANCH| pub + pypi -->|pypi-build-BRANCH| pub pub -->|push| registries[(registries)] docker[build-docker] -->|push| registries ``` @@ -102,10 +103,10 @@ flowchart TD Pick each output's path by **where the artifact goes**: - **File on the GitHub release** (zip, binary, packaged library): one leaf per output uploading `release-asset--`. For a repo calling the hub-hosted task, the path is instead the files its `build-release-asset` hook writes, which the task uploads as one such artifact. The repo keeps `expect_release_assets: true` (its default). -- **Package-registry push** (NuGet, PyPI): the leaf builds and uploads a build artifact (`nuget-build-` / `pypi-build-`). A separate `publish-` job in the **publishing repository's own** publisher consumes it and pushes. Each registry publishes through OIDC Trusted Publishing, never a stored API key, and that push sits outside the leaf for the reasons that follow. Trusted publishing validates the OIDC token's `job_workflow_ref` claim, which names the workflow the job actually ran from. So a push made from a reusable workflow a *different* repository hosts is rejected at the token exchange. There NuGet.org answers `HTTP 401` with `does not start with //.github/workflows/`. That alone rules out a leaf another repository hosts. A leaf this repository hosts clears the claim, and the split still applies to it. That is because a called job declaring no `permissions:` runs under the calling job's whole grant. So a push anywhere inside the release task would put `id-token: write` on every job in it, rather than at the one entry point D7.2 requires. The registered trusted-publishing policy therefore names the publisher, `publish-release.yml`. PyPI additionally gates its publish job behind an environment. NuGet.org binds its policy to the workflow file rather than to an environment and needs none. NuGet's leaf also uploads a `release-asset-*` carrying the package, and PyPI contributes none. +- **Package-registry push** (NuGet, PyPI): the leaf builds and uploads a build artifact (`nuget-build-` / `pypi-build-`). A separate `publish-` job in the **publishing repository's own** publisher consumes it and pushes. Each registry publishes through OIDC Trusted Publishing, never a stored API key, and that push sits outside the leaf for the reasons that follow. Trusted publishing validates the OIDC token's `job_workflow_ref` claim, which names the workflow the job actually ran from. So a push made from a reusable workflow a *different* repository hosts is rejected at the token exchange. There NuGet.org answers `HTTP 401` with `does not start with //.github/workflows/`. That alone rules out a leaf another repository hosts. A leaf this repository hosts clears the claim, and the split still applies to it. That is because a called job declaring no `permissions:` runs under the calling job's whole grant. So a push anywhere inside the release task would put `id-token: write` on every job in it, rather than at the one entry point D7.2 requires. The registered trusted-publishing policy therefore names the publisher, `publish-release.yml`. PyPI additionally gates its publish job behind an environment. NuGet.org binds its policy to the workflow file rather than to an environment and needs none. NuGet's and PyPI's default leaves also upload a `release-asset-*` carrying the package files. - **Image-registry push** (Docker): the leaf pushes the default branch multi-arch (amd64+arm64) and any other branch `amd64`-only, and contributes no `release-asset-*`. The arm64 emulation is reserved for the released image. - **Filesystem on a host the project owns** (a static site, a config tree): the leaf builds the tree and ships it to the host. It contributes no `release-asset-*`. The transport is the repo's own. The contract fixes the rest. The deploy is a **separate `workflow_dispatch`** from the release, so a redeploy of an unchanged commit mints no tag. A host rebuild, a rollback, or proving a branch on a non-production environment then costs nothing. Its credentials come from a **per-environment GitHub Environment** rather than the repository secret store. The deploy also ends by asserting **what the host serves** rather than the transport's exit status (D4.6). Retention at the destination is bounded by a declared count, with one side recorded as owning the prune. That side is the deploy where its credential can observe the destination, and the host where that credential is deliberately write-only (D5.6). -- **No file target via the release task** (Docker-only, PyPI-only, source-only): the release is tag + source zip + README + LICENSE. The caller **MUST pass `expect_release_assets: false`** to the release task. A publisher with file targets retains the default `true`. This setting is caller-specific. The default `true` fails on `fail_on_unmatched_files` when no assets exist. A **source-only** repo also passes every `enable_*` input as false because it has no build leaf (see `WORKFLOW.md` section 6). +- **No file target** (Docker-only, source-only, or PyPI-only with a no-asset hook): the release is tag + source zip + README + LICENSE. The caller **MUST pass `expect_release_assets: false`** to the release task. A publisher with file targets retains the default `true`. This setting is caller-specific. The default `true` fails on `fail_on_unmatched_files` when no assets exist. A **source-only** repo also passes every `enable_*` input as false because it has no build leaf (see `WORKFLOW.md` section 6). `WORKFLOW.md` section 3 keeps the architecture. The `workflow-ci-contract` Skill carries this section whole as a generated include, at `.agents/skills/workflow-ci-contract/references/architecture.md` in the hub. That path is not a repo-relative link, since it is hub-local and not carried into every fleet repo. diff --git a/.agents/skills/workflow-ci-contract/references/d-guarantees.md b/.agents/skills/workflow-ci-contract/references/d-guarantees.md index e4a37f852..327dd5149 100644 --- a/.agents/skills/workflow-ci-contract/references/d-guarantees.md +++ b/.agents/skills/workflow-ci-contract/references/d-guarantees.md @@ -39,7 +39,7 @@ The required behaviors, organized by domain. Each is a **MUST**, and its `Output - **D4.1 Gated single-branch publish.** Output: PRs smoke-test and publish nothing. A **human merge never auto-publishes**. A `plan` job (`publish-plan-task.yml`) decides once. A job downstream of it either gates on the plan's outputs or inherits the skip through `needs:`. A gate on an output compares it against `'true'` rather than testing it bare, since a job output is always a string. A publish runs on a **code-affecting bot push to `main`**, gated to the codegen App / Dependabot `github.actor`. On that trigger, an Actions-only bump matches no release path and publishes nothing. A publish also runs on a **dispatch** of `main`/`develop`, or on a **main-only weekly schedule** (Docker). A source-only repo publishes on dispatch only. The plan reports every `schedule` as a publish, so a publisher with no `push` trigger whose schedule retests and never publishes gates its release itself. Each of its jobs calling `build-release-task.yml` carries `github.event_name == 'workflow_dispatch'` as an `&&` term of its job-level `if:` holding no `||` or negated group. Each run builds one branch. The D4.7 supersede dispatch has one accepted, bounded window that publishes without the allowlist check. - **D4.2 Tag the built commit.** Output: the release `target_commitish` is the built commit's SHA (NBGV's `GitCommitId`), never a branch name or a separately re-resolved ref. *Prevents: the tag landing on the default branch instead of the built tree.* -- **D4.3 Release contents.** Output: every release contains a tag on the built commit plus the auto source zip, README, and LICENSE. File targets attach `release-asset-*`. The `prerelease` value equals `branch != default`. A no-file-target caller sets `expect_release_assets: false` to reach the no-asset shape. This applies to Docker-only, PyPI-only, and source-only repos. A NuGet target is not among them, since its leaf uploads a `release-asset-*` carrying the package, so a NuGet-only caller keeps the default `true`. The setting relaxes `fail_on_unmatched_files` and skips the asset download. The release-create step fails when no assets exist and the setting retains its default `true`. A source-only caller also sets every `enable_*` input false. +- **D4.3 Release contents.** Output: every release contains a tag on the built commit plus the auto source zip, README, and LICENSE. File targets attach `release-asset-*`. The `prerelease` value equals `branch != default`. A no-file-target caller sets `expect_release_assets: false` to reach the no-asset shape. This applies to Docker-only and source-only repos, and to a PyPI-only caller whose own `build-pypi` hook uploads none. A NuGet or PyPI target on the hub default leaf is not among them. That leaf uploads a `release-asset-*` carrying the package files, so such a caller keeps the default `true`. The setting relaxes `fail_on_unmatched_files` and skips the asset download. The release-create step fails when no assets exist and the setting retains its default `true`. A source-only caller also sets every `enable_*` input false. - **D4.4 No-op republish.** Input: a re-run whose version is unchanged, on a schedule or push trigger. Output: no second release is cut, because the release-create step is skipped when `gh release view` finds a release for the tag. The paired asset-delete is skipped with it. A **dispatch** re-run refreshes the release instead and runs that delete with it. That is why a dispatch-only publisher records this item's skip leg as unreachable rather than failed. Package-registry pushes are no-ops. The NuGet/PyPI publish steps are **not** statically gated on existence. They run and the **server** dedupes (`dotnet nuget push --skip-duplicate` turns a 409 into success, and PyPI does the same under `skip-existing: true`). **Docker always re-pushes** the image (base-image refresh), independently of the release-create skip, within the same run. *Prevents: duplicate releases and wasted pushes.* - **D4.5 A build failure blocks every publish target, within the Docker limit below.** Input: a real publish where one enabled build fails. Output: nothing publishes. The limit applies where a Docker target builds a shared base or more than one image. Its task then pushes the base and each image leg as it builds. So a leg failing after the base or a sibling leg pushed leaves those images in the registry with no release. `github-release` needs every build and carries the same `!failure() && !cancelled()` guard the terminal registry pusher (Docker) does. Without that guard, the implicit `success()` would skip both on every run that disables a target, rather than only on a failed one. A failed build therefore skips the release (no tag, no release). Docker, which needs every other build, skips with it (no image push). By contrast, a **disabled** target, skipped rather than failed, still lets docker push. A package target's separate publish job needs its own gate for the same reason, since it sits outside the `github-release` and Docker `needs:` chains. That gate is that it `needs:` the release-task call, so a failed build skips it with the rest. The push itself is what no gate can cover, because it runs after the whole release task and therefore after `github-release`. It runs there for the trusted-publishing reason `WORKFLOW.md` section 3's "Output Seam by Destination" package-registry bullet gives. So a rejected token exchange, a registry outage, or a trusted-publishing policy naming the wrong workflow file leaves a published release and tag. That release and tag are for a version that never reached the registry. The recovery is a re-dispatch or a full re-run rather than a cleanup. **A full re-run is always available inside its window and is the only route once the branch tip has moved.** The `Re-run failed jobs` shortcut is not a third route here, D5.2's delete having already removed the artifact it would download. `GOVERNANCE.md` "Release Model", and the skill it routes to, carry the mechanics of each route, how to choose, and the window. *Prevents: a partial publish, e.g. a Docker image pushed while .NET publish failed and no release was cut.* - **D4.6 Deploy verification names the release.** Input: a deploy to a filesystem on a host the project owns that completes without error. Output: a check against the running host asserts **which release is answering**, not merely that it answers. The artifact stamps its own version into the configuration it ships, and the check compares that against the version just installed. The check **waits for convergence to a bounded timeout** rather than sampling once. That is because content goes live the instant a pointer moves, while server rules wait on an asynchronous reload. The same check asserts **which environment** answered. That is because several environments serve a byte-identical artifact, and a proxy rule aimed at the wrong one answers healthily under the right hostname. An unreachable host is reported distinctly from an HTTP status. *Prevents: a green deploy over a host still serving the previous release's configuration, and a URL contract checked against the wrong environment. It also prevents a dead config watcher read as a routing fault.* @@ -56,7 +56,7 @@ The required behaviors, organized by domain. Each is a **MUST**, and its `Output ### D6 - Seam / Architecture Conformance -- **D6.1 Pattern handoff.** Output: the release job downloads by `pattern:`/`merge-multiple:`, not `artifact-ids:`. **File** targets upload `release-asset--`. A file target the hub-hosted task builds through the `build-release-asset` hook fills `` with `build-release-asset`. A target contributing no file to the release (Docker, PyPI) uploads no `release-asset-*` of its own, per D4.3, whatever other transfer artifact it uploads. The `pattern:` download is canonical for a single-target repo too, which does not special-case itself to `artifact-ids:`. +- **D6.1 Pattern handoff.** Output: the release job downloads by `pattern:`/`merge-multiple:`, not `artifact-ids:`. **File** targets upload `release-asset--`. A file target the hub-hosted task builds through the `build-release-asset` hook fills `` with `build-release-asset`. A target contributing no file to the release (Docker) uploads no `release-asset-*` of its own, per D4.3, whatever other transfer artifact it uploads. The `pattern:` download is canonical for a single-target repo too, which does not special-case itself to `artifact-ids:`. - **D6.2 Branch drives config.** Output: a called workflow's branch-derived config reads `inputs.branch`, never `github.ref_name`. - **D6.3 Branch-named artifacts.** Output: every artifact name carries the branch, so a branch's artifacts do not collide with another branch's. - **D6.4 Target add/drop is consistent.** Output: adding or dropping a target updates **all** of the following. The list is the `enable_` value the publisher passes to the release task, and the publisher's `on.push.paths` entries where it carries a `push` trigger. The list continues with the `changes` paths-filter entry + output and the `smoke-build` enable-forward. The list includes `expect_release_assets` where the change adds the first file target or drops the last (D4.3). For a package target, the list also includes the separate `publish-` job. A repo owning its release task also updates the target's build job there, `build-` or `dotnet-publish` for the .NET target. It also updates the target's `github-release` and `build-docker` `needs:` entries. Everything in the `github-release` job **except its `needs:` list** stays verbatim, and so does the version and publish-plan logic. "Verbatim" never reaches the surfaces this item requires editing, that `needs:` list, the release task's job list, and the paths-filter among them. *Prevents: a partial subset that startup-fails on a missing leaf or never smoke-builds a target.* diff --git a/.agents/skills/workflow-ci-contract/references/test-methodology.md b/.agents/skills/workflow-ci-contract/references/test-methodology.md index 2e88b46d5..6381fc559 100644 --- a/.agents/skills/workflow-ci-contract/references/test-methodology.md +++ b/.agents/skills/workflow-ci-contract/references/test-methodology.md @@ -41,7 +41,7 @@ For each *applicable* scenario, evaluate every job's `if:`/`needs:` against the | S13 | deploy dispatch of a production environment from a non-default ref | **fails fast**, before anything is installed or written | D2.1 | | S14 | publish whose branch head gained different `.github/workflows` content after the build began | every update since a release bot's push or merge: release-create **skipped** and the publisher dispatched on the branch. In that case this run ends **cancelled** with its package publish jobs skipped (a Docker image already pushed). The dispatched run releases the head, queueing behind this run only where the head's publisher evaluates this run's group for a dispatch. A push landing after the branch is confirmed unmoved and before the dispatch is released as if it were such an update. That is an accepted, bounded limit per D4.7. Any other update: the step **fails**, nothing is released or dispatched | D4.1, D4.2, D4.5, D4.7 | | S15 | a smoke or publish run whose `build-nuget` job runs the hub default leaf, for a project declaring `net10.0;net11.0`. The package holds one framework's assembly under both `lib/` folders | the job plans both runtime lines, installs them, and consumes the package once per framework. It **fails** on the `TargetFrameworkAttribute` of the `lib/` folder holding the other framework's assembly, after reporting every other row. A correct package **passes**. The check uploads nothing in either run. A publish run's leaf has uploaded its artifacts already, and a failure leaves them to their retention and the dependent publish job **skipped** | D1.3, D1.7 | -| S16 | a smoke or publish run whose `build-pypi` job runs the hub default leaf, for a project with a `tests/` folder and a `python-versions` of `["3.13", "3.14"]`. Its wheel leaves out a module the tests import | the job builds, then consumes the wheel and the sdist under each line. It **fails** on the tests row of each artifact lacking the module, after reporting every other row. A correct package **passes** under both lines. The check uploads nothing in either run. A publish run's leaf has uploaded its artifact already. A failure leaves it to its retention, and the dependent publish job is **skipped** | D1.3, D1.8 | +| S16 | a smoke or publish run whose `build-pypi` job runs the hub default leaf, for a project with a `tests/` folder and a `python-versions` of `["3.13", "3.14"]`. Its wheel leaves out a module the tests import | the job builds, then consumes the wheel and the sdist under each line. It **fails** on the tests row of each artifact lacking the module, after reporting every other row. A correct package **passes** under both lines. The check uploads nothing in either run. A publish run's leaf has uploaded its artifacts already. A failure leaves them to their retention, and the dependent publish job is **skipped** | D1.3, D1.8 | ### 5C. Live Probe (Where Warranted) diff --git a/.claude-plugin/fleet-skills/.source-digests/branching-and-release-model b/.claude-plugin/fleet-skills/.source-digests/branching-and-release-model index d54768412..c502fa2ac 100644 --- a/.claude-plugin/fleet-skills/.source-digests/branching-and-release-model +++ b/.claude-plugin/fleet-skills/.source-digests/branching-and-release-model @@ -1 +1 @@ -c18b4ff8c13f0ac7 +c1cda920d95449ef diff --git a/.claude-plugin/fleet-skills/.source-digests/workflow-ci-contract b/.claude-plugin/fleet-skills/.source-digests/workflow-ci-contract index fd526bce3..4553344d0 100644 --- a/.claude-plugin/fleet-skills/.source-digests/workflow-ci-contract +++ b/.claude-plugin/fleet-skills/.source-digests/workflow-ci-contract @@ -1 +1 @@ -23c6a153a42f8126 +750bae5d66dc9c1d diff --git a/.claude-plugin/fleet-skills/skills/branching-and-release-model/references/release-publish-mechanics.md b/.claude-plugin/fleet-skills/skills/branching-and-release-model/references/release-publish-mechanics.md index b3af6488d..0d3fce9f7 100644 --- a/.claude-plugin/fleet-skills/skills/branching-and-release-model/references/release-publish-mechanics.md +++ b/.claude-plugin/fleet-skills/skills/branching-and-release-model/references/release-publish-mechanics.md @@ -45,10 +45,12 @@ project-path inputs among them. Pick by where each artifact *goes*, not by language: - **Files attached to the GitHub Release** (zips, binaries, packaged libraries): a dotnet-publish - hook or a build-nuget hook per output, each uploading `release-asset--`. This is where the - .NET `dotnet publish` or `dotnet build` lives, though a package push does not. The hub default takes an explicit - project path, and a project needing different build behavior replaces the hook. A data-only - repo's own output (e.g. a symbol library) is a file target, which the `build-release-asset` hook + hook or a build-nuget hook per output, each uploading `release-asset--`. + The default PyPI leaf uploads one too. + The .NET `dotnet publish` lives in the dotnet-publish hook and `dotnet build` in the build-nuget hook, though a package push lives in neither. + The hub default takes an explicit project path. + A project needing different build behavior replaces the hook. + A data-only repo's own output (e.g. a symbol library) is a file target, which the `build-release-asset` hook builds when the caller sets `enable_release_asset: true`. The hook has no hub default, so the caller provides `.github/actions/build-release-asset/action.yml` and the task fails without it. - **Package-registry pushes** (NuGet.org, PyPI): each is split, and the push never sits in the @@ -61,11 +63,12 @@ Pick by where each artifact *goes*, not by language: build-nuget hook uploads a `nuget-build-` artifact for a separate `publish-nuget` job in the caller's own `publish-release.yml`. That job authenticates through `NuGet/login` and therefore carries `id-token: write` (plus `actions: write` to delete the artifact it consumed). The hook - *also* uploads a `release-asset-*` (.7z) for the GitHub release. PyPI is the same shape: the build-pypi hook only builds and uploads the - `pypi-build-` artifact. The separate `publish-pypi` job in the caller's own - `publish-release.yml` does the OIDC Trusted-Publishing upload, behind an `environment: pypi` - gate and with `skip-existing: true`. The `id-token: write` permission is granted only at that - one entry point. PyPI contributes **no** `release-asset-*`. + *also* uploads a `release-asset-*` (.7z) for the GitHub release. + PyPI is the same shape. + The hub default leaf uploads the `pypi-build-` artifact and a `release-asset--pypi` carrying the wheel and sdist. + The separate `publish-pypi` job in the caller's own `publish-release.yml` does the OIDC Trusted-Publishing upload. + It runs behind an `environment: pypi` gate and with `skip-existing: true`. + The `id-token: write` permission is granted only at that one entry point. - **Image-registry pushes** (Docker Hub): `build-docker-task.yml`, hub-hosted like `build-release-task.yml`, pushes the default branch multi-arch (amd64+arm64) and any other branch `amd64`-only, and contributes **no** `release-asset-*`. The image set comes from a docker-prepare hook (the hub default emits the diff --git a/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/architecture.md b/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/architecture.md index 07d73c83e..d887558d7 100644 --- a/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/architecture.md +++ b/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/architecture.md @@ -44,9 +44,10 @@ A target contributes a file to the GitHub release by uploading a workflow artifa flowchart LR dotnet[dotnet-publish] -->|release-asset-BRANCH-dotnet-publish| store[(run artifacts)] nuget[build-nuget] -->|release-asset-BRANCH-nuget| store + pypi[build-pypi] -->|release-asset-BRANCH-pypi| store store -->|pattern + merge-multiple| rel["github-release job (D6)"] nuget -->|nuget-build-BRANCH| pub["publish-TARGET job in the repo's own publisher"] - pypi[build-pypi] -->|pypi-build-BRANCH| pub + pypi -->|pypi-build-BRANCH| pub pub -->|push| registries[(registries)] docker[build-docker] -->|push| registries ``` @@ -102,10 +103,10 @@ flowchart TD Pick each output's path by **where the artifact goes**: - **File on the GitHub release** (zip, binary, packaged library): one leaf per output uploading `release-asset--`. For a repo calling the hub-hosted task, the path is instead the files its `build-release-asset` hook writes, which the task uploads as one such artifact. The repo keeps `expect_release_assets: true` (its default). -- **Package-registry push** (NuGet, PyPI): the leaf builds and uploads a build artifact (`nuget-build-` / `pypi-build-`). A separate `publish-` job in the **publishing repository's own** publisher consumes it and pushes. Each registry publishes through OIDC Trusted Publishing, never a stored API key, and that push sits outside the leaf for the reasons that follow. Trusted publishing validates the OIDC token's `job_workflow_ref` claim, which names the workflow the job actually ran from. So a push made from a reusable workflow a *different* repository hosts is rejected at the token exchange. There NuGet.org answers `HTTP 401` with `does not start with //.github/workflows/`. That alone rules out a leaf another repository hosts. A leaf this repository hosts clears the claim, and the split still applies to it. That is because a called job declaring no `permissions:` runs under the calling job's whole grant. So a push anywhere inside the release task would put `id-token: write` on every job in it, rather than at the one entry point D7.2 requires. The registered trusted-publishing policy therefore names the publisher, `publish-release.yml`. PyPI additionally gates its publish job behind an environment. NuGet.org binds its policy to the workflow file rather than to an environment and needs none. NuGet's leaf also uploads a `release-asset-*` carrying the package, and PyPI contributes none. +- **Package-registry push** (NuGet, PyPI): the leaf builds and uploads a build artifact (`nuget-build-` / `pypi-build-`). A separate `publish-` job in the **publishing repository's own** publisher consumes it and pushes. Each registry publishes through OIDC Trusted Publishing, never a stored API key, and that push sits outside the leaf for the reasons that follow. Trusted publishing validates the OIDC token's `job_workflow_ref` claim, which names the workflow the job actually ran from. So a push made from a reusable workflow a *different* repository hosts is rejected at the token exchange. There NuGet.org answers `HTTP 401` with `does not start with //.github/workflows/`. That alone rules out a leaf another repository hosts. A leaf this repository hosts clears the claim, and the split still applies to it. That is because a called job declaring no `permissions:` runs under the calling job's whole grant. So a push anywhere inside the release task would put `id-token: write` on every job in it, rather than at the one entry point D7.2 requires. The registered trusted-publishing policy therefore names the publisher, `publish-release.yml`. PyPI additionally gates its publish job behind an environment. NuGet.org binds its policy to the workflow file rather than to an environment and needs none. NuGet's and PyPI's default leaves also upload a `release-asset-*` carrying the package files. - **Image-registry push** (Docker): the leaf pushes the default branch multi-arch (amd64+arm64) and any other branch `amd64`-only, and contributes no `release-asset-*`. The arm64 emulation is reserved for the released image. - **Filesystem on a host the project owns** (a static site, a config tree): the leaf builds the tree and ships it to the host. It contributes no `release-asset-*`. The transport is the repo's own. The contract fixes the rest. The deploy is a **separate `workflow_dispatch`** from the release, so a redeploy of an unchanged commit mints no tag. A host rebuild, a rollback, or proving a branch on a non-production environment then costs nothing. Its credentials come from a **per-environment GitHub Environment** rather than the repository secret store. The deploy also ends by asserting **what the host serves** rather than the transport's exit status (D4.6). Retention at the destination is bounded by a declared count, with one side recorded as owning the prune. That side is the deploy where its credential can observe the destination, and the host where that credential is deliberately write-only (D5.6). -- **No file target via the release task** (Docker-only, PyPI-only, source-only): the release is tag + source zip + README + LICENSE. The caller **MUST pass `expect_release_assets: false`** to the release task. A publisher with file targets retains the default `true`. This setting is caller-specific. The default `true` fails on `fail_on_unmatched_files` when no assets exist. A **source-only** repo also passes every `enable_*` input as false because it has no build leaf (see `WORKFLOW.md` section 6). +- **No file target** (Docker-only, source-only, or PyPI-only with a no-asset hook): the release is tag + source zip + README + LICENSE. The caller **MUST pass `expect_release_assets: false`** to the release task. A publisher with file targets retains the default `true`. This setting is caller-specific. The default `true` fails on `fail_on_unmatched_files` when no assets exist. A **source-only** repo also passes every `enable_*` input as false because it has no build leaf (see `WORKFLOW.md` section 6). `WORKFLOW.md` section 3 keeps the architecture. The `workflow-ci-contract` Skill carries this section whole as a generated include, at `.agents/skills/workflow-ci-contract/references/architecture.md` in the hub. That path is not a repo-relative link, since it is hub-local and not carried into every fleet repo. diff --git a/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/d-guarantees.md b/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/d-guarantees.md index e4a37f852..327dd5149 100644 --- a/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/d-guarantees.md +++ b/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/d-guarantees.md @@ -39,7 +39,7 @@ The required behaviors, organized by domain. Each is a **MUST**, and its `Output - **D4.1 Gated single-branch publish.** Output: PRs smoke-test and publish nothing. A **human merge never auto-publishes**. A `plan` job (`publish-plan-task.yml`) decides once. A job downstream of it either gates on the plan's outputs or inherits the skip through `needs:`. A gate on an output compares it against `'true'` rather than testing it bare, since a job output is always a string. A publish runs on a **code-affecting bot push to `main`**, gated to the codegen App / Dependabot `github.actor`. On that trigger, an Actions-only bump matches no release path and publishes nothing. A publish also runs on a **dispatch** of `main`/`develop`, or on a **main-only weekly schedule** (Docker). A source-only repo publishes on dispatch only. The plan reports every `schedule` as a publish, so a publisher with no `push` trigger whose schedule retests and never publishes gates its release itself. Each of its jobs calling `build-release-task.yml` carries `github.event_name == 'workflow_dispatch'` as an `&&` term of its job-level `if:` holding no `||` or negated group. Each run builds one branch. The D4.7 supersede dispatch has one accepted, bounded window that publishes without the allowlist check. - **D4.2 Tag the built commit.** Output: the release `target_commitish` is the built commit's SHA (NBGV's `GitCommitId`), never a branch name or a separately re-resolved ref. *Prevents: the tag landing on the default branch instead of the built tree.* -- **D4.3 Release contents.** Output: every release contains a tag on the built commit plus the auto source zip, README, and LICENSE. File targets attach `release-asset-*`. The `prerelease` value equals `branch != default`. A no-file-target caller sets `expect_release_assets: false` to reach the no-asset shape. This applies to Docker-only, PyPI-only, and source-only repos. A NuGet target is not among them, since its leaf uploads a `release-asset-*` carrying the package, so a NuGet-only caller keeps the default `true`. The setting relaxes `fail_on_unmatched_files` and skips the asset download. The release-create step fails when no assets exist and the setting retains its default `true`. A source-only caller also sets every `enable_*` input false. +- **D4.3 Release contents.** Output: every release contains a tag on the built commit plus the auto source zip, README, and LICENSE. File targets attach `release-asset-*`. The `prerelease` value equals `branch != default`. A no-file-target caller sets `expect_release_assets: false` to reach the no-asset shape. This applies to Docker-only and source-only repos, and to a PyPI-only caller whose own `build-pypi` hook uploads none. A NuGet or PyPI target on the hub default leaf is not among them. That leaf uploads a `release-asset-*` carrying the package files, so such a caller keeps the default `true`. The setting relaxes `fail_on_unmatched_files` and skips the asset download. The release-create step fails when no assets exist and the setting retains its default `true`. A source-only caller also sets every `enable_*` input false. - **D4.4 No-op republish.** Input: a re-run whose version is unchanged, on a schedule or push trigger. Output: no second release is cut, because the release-create step is skipped when `gh release view` finds a release for the tag. The paired asset-delete is skipped with it. A **dispatch** re-run refreshes the release instead and runs that delete with it. That is why a dispatch-only publisher records this item's skip leg as unreachable rather than failed. Package-registry pushes are no-ops. The NuGet/PyPI publish steps are **not** statically gated on existence. They run and the **server** dedupes (`dotnet nuget push --skip-duplicate` turns a 409 into success, and PyPI does the same under `skip-existing: true`). **Docker always re-pushes** the image (base-image refresh), independently of the release-create skip, within the same run. *Prevents: duplicate releases and wasted pushes.* - **D4.5 A build failure blocks every publish target, within the Docker limit below.** Input: a real publish where one enabled build fails. Output: nothing publishes. The limit applies where a Docker target builds a shared base or more than one image. Its task then pushes the base and each image leg as it builds. So a leg failing after the base or a sibling leg pushed leaves those images in the registry with no release. `github-release` needs every build and carries the same `!failure() && !cancelled()` guard the terminal registry pusher (Docker) does. Without that guard, the implicit `success()` would skip both on every run that disables a target, rather than only on a failed one. A failed build therefore skips the release (no tag, no release). Docker, which needs every other build, skips with it (no image push). By contrast, a **disabled** target, skipped rather than failed, still lets docker push. A package target's separate publish job needs its own gate for the same reason, since it sits outside the `github-release` and Docker `needs:` chains. That gate is that it `needs:` the release-task call, so a failed build skips it with the rest. The push itself is what no gate can cover, because it runs after the whole release task and therefore after `github-release`. It runs there for the trusted-publishing reason `WORKFLOW.md` section 3's "Output Seam by Destination" package-registry bullet gives. So a rejected token exchange, a registry outage, or a trusted-publishing policy naming the wrong workflow file leaves a published release and tag. That release and tag are for a version that never reached the registry. The recovery is a re-dispatch or a full re-run rather than a cleanup. **A full re-run is always available inside its window and is the only route once the branch tip has moved.** The `Re-run failed jobs` shortcut is not a third route here, D5.2's delete having already removed the artifact it would download. `GOVERNANCE.md` "Release Model", and the skill it routes to, carry the mechanics of each route, how to choose, and the window. *Prevents: a partial publish, e.g. a Docker image pushed while .NET publish failed and no release was cut.* - **D4.6 Deploy verification names the release.** Input: a deploy to a filesystem on a host the project owns that completes without error. Output: a check against the running host asserts **which release is answering**, not merely that it answers. The artifact stamps its own version into the configuration it ships, and the check compares that against the version just installed. The check **waits for convergence to a bounded timeout** rather than sampling once. That is because content goes live the instant a pointer moves, while server rules wait on an asynchronous reload. The same check asserts **which environment** answered. That is because several environments serve a byte-identical artifact, and a proxy rule aimed at the wrong one answers healthily under the right hostname. An unreachable host is reported distinctly from an HTTP status. *Prevents: a green deploy over a host still serving the previous release's configuration, and a URL contract checked against the wrong environment. It also prevents a dead config watcher read as a routing fault.* @@ -56,7 +56,7 @@ The required behaviors, organized by domain. Each is a **MUST**, and its `Output ### D6 - Seam / Architecture Conformance -- **D6.1 Pattern handoff.** Output: the release job downloads by `pattern:`/`merge-multiple:`, not `artifact-ids:`. **File** targets upload `release-asset--`. A file target the hub-hosted task builds through the `build-release-asset` hook fills `` with `build-release-asset`. A target contributing no file to the release (Docker, PyPI) uploads no `release-asset-*` of its own, per D4.3, whatever other transfer artifact it uploads. The `pattern:` download is canonical for a single-target repo too, which does not special-case itself to `artifact-ids:`. +- **D6.1 Pattern handoff.** Output: the release job downloads by `pattern:`/`merge-multiple:`, not `artifact-ids:`. **File** targets upload `release-asset--`. A file target the hub-hosted task builds through the `build-release-asset` hook fills `` with `build-release-asset`. A target contributing no file to the release (Docker) uploads no `release-asset-*` of its own, per D4.3, whatever other transfer artifact it uploads. The `pattern:` download is canonical for a single-target repo too, which does not special-case itself to `artifact-ids:`. - **D6.2 Branch drives config.** Output: a called workflow's branch-derived config reads `inputs.branch`, never `github.ref_name`. - **D6.3 Branch-named artifacts.** Output: every artifact name carries the branch, so a branch's artifacts do not collide with another branch's. - **D6.4 Target add/drop is consistent.** Output: adding or dropping a target updates **all** of the following. The list is the `enable_` value the publisher passes to the release task, and the publisher's `on.push.paths` entries where it carries a `push` trigger. The list continues with the `changes` paths-filter entry + output and the `smoke-build` enable-forward. The list includes `expect_release_assets` where the change adds the first file target or drops the last (D4.3). For a package target, the list also includes the separate `publish-` job. A repo owning its release task also updates the target's build job there, `build-` or `dotnet-publish` for the .NET target. It also updates the target's `github-release` and `build-docker` `needs:` entries. Everything in the `github-release` job **except its `needs:` list** stays verbatim, and so does the version and publish-plan logic. "Verbatim" never reaches the surfaces this item requires editing, that `needs:` list, the release task's job list, and the paths-filter among them. *Prevents: a partial subset that startup-fails on a missing leaf or never smoke-builds a target.* diff --git a/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/test-methodology.md b/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/test-methodology.md index 2e88b46d5..6381fc559 100644 --- a/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/test-methodology.md +++ b/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/test-methodology.md @@ -41,7 +41,7 @@ For each *applicable* scenario, evaluate every job's `if:`/`needs:` against the | S13 | deploy dispatch of a production environment from a non-default ref | **fails fast**, before anything is installed or written | D2.1 | | S14 | publish whose branch head gained different `.github/workflows` content after the build began | every update since a release bot's push or merge: release-create **skipped** and the publisher dispatched on the branch. In that case this run ends **cancelled** with its package publish jobs skipped (a Docker image already pushed). The dispatched run releases the head, queueing behind this run only where the head's publisher evaluates this run's group for a dispatch. A push landing after the branch is confirmed unmoved and before the dispatch is released as if it were such an update. That is an accepted, bounded limit per D4.7. Any other update: the step **fails**, nothing is released or dispatched | D4.1, D4.2, D4.5, D4.7 | | S15 | a smoke or publish run whose `build-nuget` job runs the hub default leaf, for a project declaring `net10.0;net11.0`. The package holds one framework's assembly under both `lib/` folders | the job plans both runtime lines, installs them, and consumes the package once per framework. It **fails** on the `TargetFrameworkAttribute` of the `lib/` folder holding the other framework's assembly, after reporting every other row. A correct package **passes**. The check uploads nothing in either run. A publish run's leaf has uploaded its artifacts already, and a failure leaves them to their retention and the dependent publish job **skipped** | D1.3, D1.7 | -| S16 | a smoke or publish run whose `build-pypi` job runs the hub default leaf, for a project with a `tests/` folder and a `python-versions` of `["3.13", "3.14"]`. Its wheel leaves out a module the tests import | the job builds, then consumes the wheel and the sdist under each line. It **fails** on the tests row of each artifact lacking the module, after reporting every other row. A correct package **passes** under both lines. The check uploads nothing in either run. A publish run's leaf has uploaded its artifact already. A failure leaves it to its retention, and the dependent publish job is **skipped** | D1.3, D1.8 | +| S16 | a smoke or publish run whose `build-pypi` job runs the hub default leaf, for a project with a `tests/` folder and a `python-versions` of `["3.13", "3.14"]`. Its wheel leaves out a module the tests import | the job builds, then consumes the wheel and the sdist under each line. It **fails** on the tests row of each artifact lacking the module, after reporting every other row. A correct package **passes** under both lines. The check uploads nothing in either run. A publish run's leaf has uploaded its artifacts already. A failure leaves them to their retention, and the dependent publish job is **skipped** | D1.3, D1.8 | ### 5C. Live Probe (Where Warranted) diff --git a/.github/actions/pypi-build-default/action.yml b/.github/actions/pypi-build-default/action.yml index 3670d287c..198c75bbb 100644 --- a/.github/actions/pypi-build-default/action.yml +++ b/.github/actions/pypi-build-default/action.yml @@ -1,12 +1,12 @@ name: Build PyPI package default -description: Build a wheel and source distribution for the publish-pypi job. +description: Build a wheel and source distribution for the publish-pypi job and the GitHub release. inputs: branch: description: Logical branch driving the PEP 440 version. develop gives a .dev0 prerelease, else a plain release. required: true smoke: - description: Smoke mode skips the build-artifact upload, since nothing would consume it. + description: Smoke mode skips the build-artifact upload and the release-asset upload, since nothing would consume them. required: false default: 'false' semver2: @@ -134,3 +134,17 @@ runs: if-no-files-found: error # Consumed within the run by the caller stub's publish-pypi job, so minimize artifact storage. retention-days: 1 + + # GitHub-release asset, uploaded under the release-asset-- pattern the github-release job collects. + # The wheel and sdist go up as bare files, so the release attaches them directly. + # That holds because the job downloads with merge-multiple. + - name: Upload release asset step + if: ${{ inputs.smoke != 'true' }} + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: release-asset-${{ inputs.branch }}-pypi + path: ${{ inputs.project-dir }}/dist/* + if-no-files-found: error + # Consumed within the run by the github-release job's download step, which expect_release_assets false skips. + # The short retention bounds what a caller skipping that download leaves behind. + retention-days: 1 diff --git a/.github/skills/branching-and-release-model/references/release-publish-mechanics.md b/.github/skills/branching-and-release-model/references/release-publish-mechanics.md index b3af6488d..0d3fce9f7 100644 --- a/.github/skills/branching-and-release-model/references/release-publish-mechanics.md +++ b/.github/skills/branching-and-release-model/references/release-publish-mechanics.md @@ -45,10 +45,12 @@ project-path inputs among them. Pick by where each artifact *goes*, not by language: - **Files attached to the GitHub Release** (zips, binaries, packaged libraries): a dotnet-publish - hook or a build-nuget hook per output, each uploading `release-asset--`. This is where the - .NET `dotnet publish` or `dotnet build` lives, though a package push does not. The hub default takes an explicit - project path, and a project needing different build behavior replaces the hook. A data-only - repo's own output (e.g. a symbol library) is a file target, which the `build-release-asset` hook + hook or a build-nuget hook per output, each uploading `release-asset--`. + The default PyPI leaf uploads one too. + The .NET `dotnet publish` lives in the dotnet-publish hook and `dotnet build` in the build-nuget hook, though a package push lives in neither. + The hub default takes an explicit project path. + A project needing different build behavior replaces the hook. + A data-only repo's own output (e.g. a symbol library) is a file target, which the `build-release-asset` hook builds when the caller sets `enable_release_asset: true`. The hook has no hub default, so the caller provides `.github/actions/build-release-asset/action.yml` and the task fails without it. - **Package-registry pushes** (NuGet.org, PyPI): each is split, and the push never sits in the @@ -61,11 +63,12 @@ Pick by where each artifact *goes*, not by language: build-nuget hook uploads a `nuget-build-` artifact for a separate `publish-nuget` job in the caller's own `publish-release.yml`. That job authenticates through `NuGet/login` and therefore carries `id-token: write` (plus `actions: write` to delete the artifact it consumed). The hook - *also* uploads a `release-asset-*` (.7z) for the GitHub release. PyPI is the same shape: the build-pypi hook only builds and uploads the - `pypi-build-` artifact. The separate `publish-pypi` job in the caller's own - `publish-release.yml` does the OIDC Trusted-Publishing upload, behind an `environment: pypi` - gate and with `skip-existing: true`. The `id-token: write` permission is granted only at that - one entry point. PyPI contributes **no** `release-asset-*`. + *also* uploads a `release-asset-*` (.7z) for the GitHub release. + PyPI is the same shape. + The hub default leaf uploads the `pypi-build-` artifact and a `release-asset--pypi` carrying the wheel and sdist. + The separate `publish-pypi` job in the caller's own `publish-release.yml` does the OIDC Trusted-Publishing upload. + It runs behind an `environment: pypi` gate and with `skip-existing: true`. + The `id-token: write` permission is granted only at that one entry point. - **Image-registry pushes** (Docker Hub): `build-docker-task.yml`, hub-hosted like `build-release-task.yml`, pushes the default branch multi-arch (amd64+arm64) and any other branch `amd64`-only, and contributes **no** `release-asset-*`. The image set comes from a docker-prepare hook (the hub default emits the diff --git a/.github/skills/workflow-ci-contract/references/architecture.md b/.github/skills/workflow-ci-contract/references/architecture.md index 07d73c83e..d887558d7 100644 --- a/.github/skills/workflow-ci-contract/references/architecture.md +++ b/.github/skills/workflow-ci-contract/references/architecture.md @@ -44,9 +44,10 @@ A target contributes a file to the GitHub release by uploading a workflow artifa flowchart LR dotnet[dotnet-publish] -->|release-asset-BRANCH-dotnet-publish| store[(run artifacts)] nuget[build-nuget] -->|release-asset-BRANCH-nuget| store + pypi[build-pypi] -->|release-asset-BRANCH-pypi| store store -->|pattern + merge-multiple| rel["github-release job (D6)"] nuget -->|nuget-build-BRANCH| pub["publish-TARGET job in the repo's own publisher"] - pypi[build-pypi] -->|pypi-build-BRANCH| pub + pypi -->|pypi-build-BRANCH| pub pub -->|push| registries[(registries)] docker[build-docker] -->|push| registries ``` @@ -102,10 +103,10 @@ flowchart TD Pick each output's path by **where the artifact goes**: - **File on the GitHub release** (zip, binary, packaged library): one leaf per output uploading `release-asset--`. For a repo calling the hub-hosted task, the path is instead the files its `build-release-asset` hook writes, which the task uploads as one such artifact. The repo keeps `expect_release_assets: true` (its default). -- **Package-registry push** (NuGet, PyPI): the leaf builds and uploads a build artifact (`nuget-build-` / `pypi-build-`). A separate `publish-` job in the **publishing repository's own** publisher consumes it and pushes. Each registry publishes through OIDC Trusted Publishing, never a stored API key, and that push sits outside the leaf for the reasons that follow. Trusted publishing validates the OIDC token's `job_workflow_ref` claim, which names the workflow the job actually ran from. So a push made from a reusable workflow a *different* repository hosts is rejected at the token exchange. There NuGet.org answers `HTTP 401` with `does not start with //.github/workflows/`. That alone rules out a leaf another repository hosts. A leaf this repository hosts clears the claim, and the split still applies to it. That is because a called job declaring no `permissions:` runs under the calling job's whole grant. So a push anywhere inside the release task would put `id-token: write` on every job in it, rather than at the one entry point D7.2 requires. The registered trusted-publishing policy therefore names the publisher, `publish-release.yml`. PyPI additionally gates its publish job behind an environment. NuGet.org binds its policy to the workflow file rather than to an environment and needs none. NuGet's leaf also uploads a `release-asset-*` carrying the package, and PyPI contributes none. +- **Package-registry push** (NuGet, PyPI): the leaf builds and uploads a build artifact (`nuget-build-` / `pypi-build-`). A separate `publish-` job in the **publishing repository's own** publisher consumes it and pushes. Each registry publishes through OIDC Trusted Publishing, never a stored API key, and that push sits outside the leaf for the reasons that follow. Trusted publishing validates the OIDC token's `job_workflow_ref` claim, which names the workflow the job actually ran from. So a push made from a reusable workflow a *different* repository hosts is rejected at the token exchange. There NuGet.org answers `HTTP 401` with `does not start with //.github/workflows/`. That alone rules out a leaf another repository hosts. A leaf this repository hosts clears the claim, and the split still applies to it. That is because a called job declaring no `permissions:` runs under the calling job's whole grant. So a push anywhere inside the release task would put `id-token: write` on every job in it, rather than at the one entry point D7.2 requires. The registered trusted-publishing policy therefore names the publisher, `publish-release.yml`. PyPI additionally gates its publish job behind an environment. NuGet.org binds its policy to the workflow file rather than to an environment and needs none. NuGet's and PyPI's default leaves also upload a `release-asset-*` carrying the package files. - **Image-registry push** (Docker): the leaf pushes the default branch multi-arch (amd64+arm64) and any other branch `amd64`-only, and contributes no `release-asset-*`. The arm64 emulation is reserved for the released image. - **Filesystem on a host the project owns** (a static site, a config tree): the leaf builds the tree and ships it to the host. It contributes no `release-asset-*`. The transport is the repo's own. The contract fixes the rest. The deploy is a **separate `workflow_dispatch`** from the release, so a redeploy of an unchanged commit mints no tag. A host rebuild, a rollback, or proving a branch on a non-production environment then costs nothing. Its credentials come from a **per-environment GitHub Environment** rather than the repository secret store. The deploy also ends by asserting **what the host serves** rather than the transport's exit status (D4.6). Retention at the destination is bounded by a declared count, with one side recorded as owning the prune. That side is the deploy where its credential can observe the destination, and the host where that credential is deliberately write-only (D5.6). -- **No file target via the release task** (Docker-only, PyPI-only, source-only): the release is tag + source zip + README + LICENSE. The caller **MUST pass `expect_release_assets: false`** to the release task. A publisher with file targets retains the default `true`. This setting is caller-specific. The default `true` fails on `fail_on_unmatched_files` when no assets exist. A **source-only** repo also passes every `enable_*` input as false because it has no build leaf (see `WORKFLOW.md` section 6). +- **No file target** (Docker-only, source-only, or PyPI-only with a no-asset hook): the release is tag + source zip + README + LICENSE. The caller **MUST pass `expect_release_assets: false`** to the release task. A publisher with file targets retains the default `true`. This setting is caller-specific. The default `true` fails on `fail_on_unmatched_files` when no assets exist. A **source-only** repo also passes every `enable_*` input as false because it has no build leaf (see `WORKFLOW.md` section 6). `WORKFLOW.md` section 3 keeps the architecture. The `workflow-ci-contract` Skill carries this section whole as a generated include, at `.agents/skills/workflow-ci-contract/references/architecture.md` in the hub. That path is not a repo-relative link, since it is hub-local and not carried into every fleet repo. diff --git a/.github/skills/workflow-ci-contract/references/d-guarantees.md b/.github/skills/workflow-ci-contract/references/d-guarantees.md index e4a37f852..327dd5149 100644 --- a/.github/skills/workflow-ci-contract/references/d-guarantees.md +++ b/.github/skills/workflow-ci-contract/references/d-guarantees.md @@ -39,7 +39,7 @@ The required behaviors, organized by domain. Each is a **MUST**, and its `Output - **D4.1 Gated single-branch publish.** Output: PRs smoke-test and publish nothing. A **human merge never auto-publishes**. A `plan` job (`publish-plan-task.yml`) decides once. A job downstream of it either gates on the plan's outputs or inherits the skip through `needs:`. A gate on an output compares it against `'true'` rather than testing it bare, since a job output is always a string. A publish runs on a **code-affecting bot push to `main`**, gated to the codegen App / Dependabot `github.actor`. On that trigger, an Actions-only bump matches no release path and publishes nothing. A publish also runs on a **dispatch** of `main`/`develop`, or on a **main-only weekly schedule** (Docker). A source-only repo publishes on dispatch only. The plan reports every `schedule` as a publish, so a publisher with no `push` trigger whose schedule retests and never publishes gates its release itself. Each of its jobs calling `build-release-task.yml` carries `github.event_name == 'workflow_dispatch'` as an `&&` term of its job-level `if:` holding no `||` or negated group. Each run builds one branch. The D4.7 supersede dispatch has one accepted, bounded window that publishes without the allowlist check. - **D4.2 Tag the built commit.** Output: the release `target_commitish` is the built commit's SHA (NBGV's `GitCommitId`), never a branch name or a separately re-resolved ref. *Prevents: the tag landing on the default branch instead of the built tree.* -- **D4.3 Release contents.** Output: every release contains a tag on the built commit plus the auto source zip, README, and LICENSE. File targets attach `release-asset-*`. The `prerelease` value equals `branch != default`. A no-file-target caller sets `expect_release_assets: false` to reach the no-asset shape. This applies to Docker-only, PyPI-only, and source-only repos. A NuGet target is not among them, since its leaf uploads a `release-asset-*` carrying the package, so a NuGet-only caller keeps the default `true`. The setting relaxes `fail_on_unmatched_files` and skips the asset download. The release-create step fails when no assets exist and the setting retains its default `true`. A source-only caller also sets every `enable_*` input false. +- **D4.3 Release contents.** Output: every release contains a tag on the built commit plus the auto source zip, README, and LICENSE. File targets attach `release-asset-*`. The `prerelease` value equals `branch != default`. A no-file-target caller sets `expect_release_assets: false` to reach the no-asset shape. This applies to Docker-only and source-only repos, and to a PyPI-only caller whose own `build-pypi` hook uploads none. A NuGet or PyPI target on the hub default leaf is not among them. That leaf uploads a `release-asset-*` carrying the package files, so such a caller keeps the default `true`. The setting relaxes `fail_on_unmatched_files` and skips the asset download. The release-create step fails when no assets exist and the setting retains its default `true`. A source-only caller also sets every `enable_*` input false. - **D4.4 No-op republish.** Input: a re-run whose version is unchanged, on a schedule or push trigger. Output: no second release is cut, because the release-create step is skipped when `gh release view` finds a release for the tag. The paired asset-delete is skipped with it. A **dispatch** re-run refreshes the release instead and runs that delete with it. That is why a dispatch-only publisher records this item's skip leg as unreachable rather than failed. Package-registry pushes are no-ops. The NuGet/PyPI publish steps are **not** statically gated on existence. They run and the **server** dedupes (`dotnet nuget push --skip-duplicate` turns a 409 into success, and PyPI does the same under `skip-existing: true`). **Docker always re-pushes** the image (base-image refresh), independently of the release-create skip, within the same run. *Prevents: duplicate releases and wasted pushes.* - **D4.5 A build failure blocks every publish target, within the Docker limit below.** Input: a real publish where one enabled build fails. Output: nothing publishes. The limit applies where a Docker target builds a shared base or more than one image. Its task then pushes the base and each image leg as it builds. So a leg failing after the base or a sibling leg pushed leaves those images in the registry with no release. `github-release` needs every build and carries the same `!failure() && !cancelled()` guard the terminal registry pusher (Docker) does. Without that guard, the implicit `success()` would skip both on every run that disables a target, rather than only on a failed one. A failed build therefore skips the release (no tag, no release). Docker, which needs every other build, skips with it (no image push). By contrast, a **disabled** target, skipped rather than failed, still lets docker push. A package target's separate publish job needs its own gate for the same reason, since it sits outside the `github-release` and Docker `needs:` chains. That gate is that it `needs:` the release-task call, so a failed build skips it with the rest. The push itself is what no gate can cover, because it runs after the whole release task and therefore after `github-release`. It runs there for the trusted-publishing reason `WORKFLOW.md` section 3's "Output Seam by Destination" package-registry bullet gives. So a rejected token exchange, a registry outage, or a trusted-publishing policy naming the wrong workflow file leaves a published release and tag. That release and tag are for a version that never reached the registry. The recovery is a re-dispatch or a full re-run rather than a cleanup. **A full re-run is always available inside its window and is the only route once the branch tip has moved.** The `Re-run failed jobs` shortcut is not a third route here, D5.2's delete having already removed the artifact it would download. `GOVERNANCE.md` "Release Model", and the skill it routes to, carry the mechanics of each route, how to choose, and the window. *Prevents: a partial publish, e.g. a Docker image pushed while .NET publish failed and no release was cut.* - **D4.6 Deploy verification names the release.** Input: a deploy to a filesystem on a host the project owns that completes without error. Output: a check against the running host asserts **which release is answering**, not merely that it answers. The artifact stamps its own version into the configuration it ships, and the check compares that against the version just installed. The check **waits for convergence to a bounded timeout** rather than sampling once. That is because content goes live the instant a pointer moves, while server rules wait on an asynchronous reload. The same check asserts **which environment** answered. That is because several environments serve a byte-identical artifact, and a proxy rule aimed at the wrong one answers healthily under the right hostname. An unreachable host is reported distinctly from an HTTP status. *Prevents: a green deploy over a host still serving the previous release's configuration, and a URL contract checked against the wrong environment. It also prevents a dead config watcher read as a routing fault.* @@ -56,7 +56,7 @@ The required behaviors, organized by domain. Each is a **MUST**, and its `Output ### D6 - Seam / Architecture Conformance -- **D6.1 Pattern handoff.** Output: the release job downloads by `pattern:`/`merge-multiple:`, not `artifact-ids:`. **File** targets upload `release-asset--`. A file target the hub-hosted task builds through the `build-release-asset` hook fills `` with `build-release-asset`. A target contributing no file to the release (Docker, PyPI) uploads no `release-asset-*` of its own, per D4.3, whatever other transfer artifact it uploads. The `pattern:` download is canonical for a single-target repo too, which does not special-case itself to `artifact-ids:`. +- **D6.1 Pattern handoff.** Output: the release job downloads by `pattern:`/`merge-multiple:`, not `artifact-ids:`. **File** targets upload `release-asset--`. A file target the hub-hosted task builds through the `build-release-asset` hook fills `` with `build-release-asset`. A target contributing no file to the release (Docker) uploads no `release-asset-*` of its own, per D4.3, whatever other transfer artifact it uploads. The `pattern:` download is canonical for a single-target repo too, which does not special-case itself to `artifact-ids:`. - **D6.2 Branch drives config.** Output: a called workflow's branch-derived config reads `inputs.branch`, never `github.ref_name`. - **D6.3 Branch-named artifacts.** Output: every artifact name carries the branch, so a branch's artifacts do not collide with another branch's. - **D6.4 Target add/drop is consistent.** Output: adding or dropping a target updates **all** of the following. The list is the `enable_` value the publisher passes to the release task, and the publisher's `on.push.paths` entries where it carries a `push` trigger. The list continues with the `changes` paths-filter entry + output and the `smoke-build` enable-forward. The list includes `expect_release_assets` where the change adds the first file target or drops the last (D4.3). For a package target, the list also includes the separate `publish-` job. A repo owning its release task also updates the target's build job there, `build-` or `dotnet-publish` for the .NET target. It also updates the target's `github-release` and `build-docker` `needs:` entries. Everything in the `github-release` job **except its `needs:` list** stays verbatim, and so does the version and publish-plan logic. "Verbatim" never reaches the surfaces this item requires editing, that `needs:` list, the release task's job list, and the paths-filter among them. *Prevents: a partial subset that startup-fails on a missing leaf or never smoke-builds a target.* diff --git a/.github/skills/workflow-ci-contract/references/test-methodology.md b/.github/skills/workflow-ci-contract/references/test-methodology.md index 2e88b46d5..6381fc559 100644 --- a/.github/skills/workflow-ci-contract/references/test-methodology.md +++ b/.github/skills/workflow-ci-contract/references/test-methodology.md @@ -41,7 +41,7 @@ For each *applicable* scenario, evaluate every job's `if:`/`needs:` against the | S13 | deploy dispatch of a production environment from a non-default ref | **fails fast**, before anything is installed or written | D2.1 | | S14 | publish whose branch head gained different `.github/workflows` content after the build began | every update since a release bot's push or merge: release-create **skipped** and the publisher dispatched on the branch. In that case this run ends **cancelled** with its package publish jobs skipped (a Docker image already pushed). The dispatched run releases the head, queueing behind this run only where the head's publisher evaluates this run's group for a dispatch. A push landing after the branch is confirmed unmoved and before the dispatch is released as if it were such an update. That is an accepted, bounded limit per D4.7. Any other update: the step **fails**, nothing is released or dispatched | D4.1, D4.2, D4.5, D4.7 | | S15 | a smoke or publish run whose `build-nuget` job runs the hub default leaf, for a project declaring `net10.0;net11.0`. The package holds one framework's assembly under both `lib/` folders | the job plans both runtime lines, installs them, and consumes the package once per framework. It **fails** on the `TargetFrameworkAttribute` of the `lib/` folder holding the other framework's assembly, after reporting every other row. A correct package **passes**. The check uploads nothing in either run. A publish run's leaf has uploaded its artifacts already, and a failure leaves them to their retention and the dependent publish job **skipped** | D1.3, D1.7 | -| S16 | a smoke or publish run whose `build-pypi` job runs the hub default leaf, for a project with a `tests/` folder and a `python-versions` of `["3.13", "3.14"]`. Its wheel leaves out a module the tests import | the job builds, then consumes the wheel and the sdist under each line. It **fails** on the tests row of each artifact lacking the module, after reporting every other row. A correct package **passes** under both lines. The check uploads nothing in either run. A publish run's leaf has uploaded its artifact already. A failure leaves it to its retention, and the dependent publish job is **skipped** | D1.3, D1.8 | +| S16 | a smoke or publish run whose `build-pypi` job runs the hub default leaf, for a project with a `tests/` folder and a `python-versions` of `["3.13", "3.14"]`. Its wheel leaves out a module the tests import | the job builds, then consumes the wheel and the sdist under each line. It **fails** on the tests row of each artifact lacking the module, after reporting every other row. A correct package **passes** under both lines. The check uploads nothing in either run. A publish run's leaf has uploaded its artifacts already. A failure leaves them to their retention, and the dependent publish job is **skipped** | D1.3, D1.8 | ### 5C. Live Probe (Where Warranted) diff --git a/.github/workflows/build-release-task.yml b/.github/workflows/build-release-task.yml index e9dd80999..d52597f6a 100644 --- a/.github/workflows/build-release-task.yml +++ b/.github/workflows/build-release-task.yml @@ -4,7 +4,7 @@ name: Build project release task # NBGV runs once in get-version and threads the version to every target. # The validate-release job gates branch<->version consistency once before any build or publish. # The github-release job is verbatim in shape: pattern download, exists gate, target_commitish, consume-then-delete. -# The expect_release_assets input collapses the fleet's three no-asset release shapes (Docker-only, PyPI-only, source-only) into one flag. +# The expect_release_assets input collapses the fleet's no-asset release shapes (Docker-only, source-only, a PyPI-only caller whose own hook uploads no asset) into one flag. # # Each build target uses a caller hook or the hub default for that target. # The one exception is build-release-asset, a file target the hub cannot know, whose caller hook is required. @@ -63,8 +63,9 @@ on: required: false type: boolean default: false - # Set false for a repo that produces no release-asset-* files, such as a Docker-only, PyPI-only, or source-only one. - # A NuGet caller keeps the default, since the nuget-build hook uploads a release-asset--nuget carrying the package. + # Set false for a repo that produces no release-asset-* files, such as a Docker-only or source-only one. + # A NuGet or PyPI caller on the hub default leaf keeps the default, since that leaf uploads a release-asset--nuget or -pypi carrying the package files. + # A PyPI-only caller whose own build-pypi hook uploads no release-asset-* sets it false. # The release is then just the tag + source zip + README + LICENSE. # The artifact download is skipped and the unmatched-files guard relaxes. expect_release_assets: @@ -301,7 +302,7 @@ jobs: feed-dir: ${{ runner.temp }}/publish # PyPI publishing happens in the caller stub's own publish-pypi job, since id-token: write is granted only at that one entry point. - # This job just builds and uploads the artifact for that job to download. + # This job builds and uploads the artifact for that job to download, and the release asset for the github-release job. build-pypi: name: Build PyPI library job if: ${{ inputs.enable_pypi }} @@ -487,7 +488,7 @@ jobs: # A skipped needs job still lets this job run, since it only needs a real, non-smoke publish. # The release step guards fail_on_unmatched_files: true, so at least one release-asset-* must match. # A repo that drops every file-producing target relaxes that guard. - # A Docker-only or PyPI-only repo is the case, its release carrying only the source zip + README + LICENSE. + # A Docker-only or source-only repo is the case, its release carrying only the source zip + README + LICENSE. - name: Download release asset artifacts step if: ${{ inputs.expect_release_assets }} uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 diff --git a/WORKFLOW.md b/WORKFLOW.md index 6bfd15ce0..b43759e9a 100644 --- a/WORKFLOW.md +++ b/WORKFLOW.md @@ -67,9 +67,10 @@ A target contributes a file to the GitHub release by uploading a workflow artifa flowchart LR dotnet[dotnet-publish] -->|release-asset-BRANCH-dotnet-publish| store[(run artifacts)] nuget[build-nuget] -->|release-asset-BRANCH-nuget| store + pypi[build-pypi] -->|release-asset-BRANCH-pypi| store store -->|pattern + merge-multiple| rel["github-release job (D6)"] nuget -->|nuget-build-BRANCH| pub["publish-TARGET job in the repo's own publisher"] - pypi[build-pypi] -->|pypi-build-BRANCH| pub + pypi -->|pypi-build-BRANCH| pub pub -->|push| registries[(registries)] docker[build-docker] -->|push| registries ``` @@ -125,10 +126,10 @@ flowchart TD Pick each output's path by **where the artifact goes**: - **File on the GitHub release** (zip, binary, packaged library): one leaf per output uploading `release-asset--`. For a repo calling the hub-hosted task, the path is instead the files its `build-release-asset` hook writes, which the task uploads as one such artifact. The repo keeps `expect_release_assets: true` (its default). -- **Package-registry push** (NuGet, PyPI): the leaf builds and uploads a build artifact (`nuget-build-` / `pypi-build-`). A separate `publish-` job in the **publishing repository's own** publisher consumes it and pushes. Each registry publishes through OIDC Trusted Publishing, never a stored API key, and that push sits outside the leaf for the reasons that follow. Trusted publishing validates the OIDC token's `job_workflow_ref` claim, which names the workflow the job actually ran from. So a push made from a reusable workflow a *different* repository hosts is rejected at the token exchange. There NuGet.org answers `HTTP 401` with `does not start with //.github/workflows/`. That alone rules out a leaf another repository hosts. A leaf this repository hosts clears the claim, and the split still applies to it. That is because a called job declaring no `permissions:` runs under the calling job's whole grant. So a push anywhere inside the release task would put `id-token: write` on every job in it, rather than at the one entry point D7.2 requires. The registered trusted-publishing policy therefore names the publisher, `publish-release.yml`. PyPI additionally gates its publish job behind an environment. NuGet.org binds its policy to the workflow file rather than to an environment and needs none. NuGet's leaf also uploads a `release-asset-*` carrying the package, and PyPI contributes none. +- **Package-registry push** (NuGet, PyPI): the leaf builds and uploads a build artifact (`nuget-build-` / `pypi-build-`). A separate `publish-` job in the **publishing repository's own** publisher consumes it and pushes. Each registry publishes through OIDC Trusted Publishing, never a stored API key, and that push sits outside the leaf for the reasons that follow. Trusted publishing validates the OIDC token's `job_workflow_ref` claim, which names the workflow the job actually ran from. So a push made from a reusable workflow a *different* repository hosts is rejected at the token exchange. There NuGet.org answers `HTTP 401` with `does not start with //.github/workflows/`. That alone rules out a leaf another repository hosts. A leaf this repository hosts clears the claim, and the split still applies to it. That is because a called job declaring no `permissions:` runs under the calling job's whole grant. So a push anywhere inside the release task would put `id-token: write` on every job in it, rather than at the one entry point D7.2 requires. The registered trusted-publishing policy therefore names the publisher, `publish-release.yml`. PyPI additionally gates its publish job behind an environment. NuGet.org binds its policy to the workflow file rather than to an environment and needs none. NuGet's and PyPI's default leaves also upload a `release-asset-*` carrying the package files. - **Image-registry push** (Docker): the leaf pushes the default branch multi-arch (amd64+arm64) and any other branch `amd64`-only, and contributes no `release-asset-*`. The arm64 emulation is reserved for the released image. - **Filesystem on a host the project owns** (a static site, a config tree): the leaf builds the tree and ships it to the host. It contributes no `release-asset-*`. The transport is the repo's own. The contract fixes the rest. The deploy is a **separate `workflow_dispatch`** from the release, so a redeploy of an unchanged commit mints no tag. A host rebuild, a rollback, or proving a branch on a non-production environment then costs nothing. Its credentials come from a **per-environment GitHub Environment** rather than the repository secret store. The deploy also ends by asserting **what the host serves** rather than the transport's exit status (D4.6). Retention at the destination is bounded by a declared count, with one side recorded as owning the prune. That side is the deploy where its credential can observe the destination, and the host where that credential is deliberately write-only (D5.6). -- **No file target via the release task** (Docker-only, PyPI-only, source-only): the release is tag + source zip + README + LICENSE. The caller **MUST pass `expect_release_assets: false`** to the release task. A publisher with file targets retains the default `true`. This setting is caller-specific. The default `true` fails on `fail_on_unmatched_files` when no assets exist. A **source-only** repo also passes every `enable_*` input as false because it has no build leaf (see `WORKFLOW.md` section 6). +- **No file target** (Docker-only, source-only, or PyPI-only with a no-asset hook): the release is tag + source zip + README + LICENSE. The caller **MUST pass `expect_release_assets: false`** to the release task. A publisher with file targets retains the default `true`. This setting is caller-specific. The default `true` fails on `fail_on_unmatched_files` when no assets exist. A **source-only** repo also passes every `enable_*` input as false because it has no build leaf (see `WORKFLOW.md` section 6). `WORKFLOW.md` section 3 keeps the architecture. The `workflow-ci-contract` Skill carries this section whole as a generated include, at `.agents/skills/workflow-ci-contract/references/architecture.md` in the hub. That path is not a repo-relative link, since it is hub-local and not carried into every fleet repo. @@ -167,7 +168,7 @@ The required behaviors, organized by domain. Each is a **MUST**, and its `Output - **D4.1 Gated single-branch publish.** Output: PRs smoke-test and publish nothing. A **human merge never auto-publishes**. A `plan` job (`publish-plan-task.yml`) decides once. A job downstream of it either gates on the plan's outputs or inherits the skip through `needs:`. A gate on an output compares it against `'true'` rather than testing it bare, since a job output is always a string. A publish runs on a **code-affecting bot push to `main`**, gated to the codegen App / Dependabot `github.actor`. On that trigger, an Actions-only bump matches no release path and publishes nothing. A publish also runs on a **dispatch** of `main`/`develop`, or on a **main-only weekly schedule** (Docker). A source-only repo publishes on dispatch only. The plan reports every `schedule` as a publish, so a publisher with no `push` trigger whose schedule retests and never publishes gates its release itself. Each of its jobs calling `build-release-task.yml` carries `github.event_name == 'workflow_dispatch'` as an `&&` term of its job-level `if:` holding no `||` or negated group. Each run builds one branch. The D4.7 supersede dispatch has one accepted, bounded window that publishes without the allowlist check. - **D4.2 Tag the built commit.** Output: the release `target_commitish` is the built commit's SHA (NBGV's `GitCommitId`), never a branch name or a separately re-resolved ref. *Prevents: the tag landing on the default branch instead of the built tree.* -- **D4.3 Release contents.** Output: every release contains a tag on the built commit plus the auto source zip, README, and LICENSE. File targets attach `release-asset-*`. The `prerelease` value equals `branch != default`. A no-file-target caller sets `expect_release_assets: false` to reach the no-asset shape. This applies to Docker-only, PyPI-only, and source-only repos. A NuGet target is not among them, since its leaf uploads a `release-asset-*` carrying the package, so a NuGet-only caller keeps the default `true`. The setting relaxes `fail_on_unmatched_files` and skips the asset download. The release-create step fails when no assets exist and the setting retains its default `true`. A source-only caller also sets every `enable_*` input false. +- **D4.3 Release contents.** Output: every release contains a tag on the built commit plus the auto source zip, README, and LICENSE. File targets attach `release-asset-*`. The `prerelease` value equals `branch != default`. A no-file-target caller sets `expect_release_assets: false` to reach the no-asset shape. This applies to Docker-only and source-only repos, and to a PyPI-only caller whose own `build-pypi` hook uploads none. A NuGet or PyPI target on the hub default leaf is not among them. That leaf uploads a `release-asset-*` carrying the package files, so such a caller keeps the default `true`. The setting relaxes `fail_on_unmatched_files` and skips the asset download. The release-create step fails when no assets exist and the setting retains its default `true`. A source-only caller also sets every `enable_*` input false. - **D4.4 No-op republish.** Input: a re-run whose version is unchanged, on a schedule or push trigger. Output: no second release is cut, because the release-create step is skipped when `gh release view` finds a release for the tag. The paired asset-delete is skipped with it. A **dispatch** re-run refreshes the release instead and runs that delete with it. That is why a dispatch-only publisher records this item's skip leg as unreachable rather than failed. Package-registry pushes are no-ops. The NuGet/PyPI publish steps are **not** statically gated on existence. They run and the **server** dedupes (`dotnet nuget push --skip-duplicate` turns a 409 into success, and PyPI does the same under `skip-existing: true`). **Docker always re-pushes** the image (base-image refresh), independently of the release-create skip, within the same run. *Prevents: duplicate releases and wasted pushes.* - **D4.5 A build failure blocks every publish target, within the Docker limit below.** Input: a real publish where one enabled build fails. Output: nothing publishes. The limit applies where a Docker target builds a shared base or more than one image. Its task then pushes the base and each image leg as it builds. So a leg failing after the base or a sibling leg pushed leaves those images in the registry with no release. `github-release` needs every build and carries the same `!failure() && !cancelled()` guard the terminal registry pusher (Docker) does. Without that guard, the implicit `success()` would skip both on every run that disables a target, rather than only on a failed one. A failed build therefore skips the release (no tag, no release). Docker, which needs every other build, skips with it (no image push). By contrast, a **disabled** target, skipped rather than failed, still lets docker push. A package target's separate publish job needs its own gate for the same reason, since it sits outside the `github-release` and Docker `needs:` chains. That gate is that it `needs:` the release-task call, so a failed build skips it with the rest. The push itself is what no gate can cover, because it runs after the whole release task and therefore after `github-release`. It runs there for the trusted-publishing reason `WORKFLOW.md` section 3's "Output Seam by Destination" package-registry bullet gives. So a rejected token exchange, a registry outage, or a trusted-publishing policy naming the wrong workflow file leaves a published release and tag. That release and tag are for a version that never reached the registry. The recovery is a re-dispatch or a full re-run rather than a cleanup. **A full re-run is always available inside its window and is the only route once the branch tip has moved.** The `Re-run failed jobs` shortcut is not a third route here, D5.2's delete having already removed the artifact it would download. `GOVERNANCE.md` "Release Model", and the skill it routes to, carry the mechanics of each route, how to choose, and the window. *Prevents: a partial publish, e.g. a Docker image pushed while .NET publish failed and no release was cut.* - **D4.6 Deploy verification names the release.** Input: a deploy to a filesystem on a host the project owns that completes without error. Output: a check against the running host asserts **which release is answering**, not merely that it answers. The artifact stamps its own version into the configuration it ships, and the check compares that against the version just installed. The check **waits for convergence to a bounded timeout** rather than sampling once. That is because content goes live the instant a pointer moves, while server rules wait on an asynchronous reload. The same check asserts **which environment** answered. That is because several environments serve a byte-identical artifact, and a proxy rule aimed at the wrong one answers healthily under the right hostname. An unreachable host is reported distinctly from an HTTP status. *Prevents: a green deploy over a host still serving the previous release's configuration, and a URL contract checked against the wrong environment. It also prevents a dead config watcher read as a routing fault.* @@ -184,7 +185,7 @@ The required behaviors, organized by domain. Each is a **MUST**, and its `Output ### D6 - Seam / Architecture Conformance -- **D6.1 Pattern handoff.** Output: the release job downloads by `pattern:`/`merge-multiple:`, not `artifact-ids:`. **File** targets upload `release-asset--`. A file target the hub-hosted task builds through the `build-release-asset` hook fills `` with `build-release-asset`. A target contributing no file to the release (Docker, PyPI) uploads no `release-asset-*` of its own, per D4.3, whatever other transfer artifact it uploads. The `pattern:` download is canonical for a single-target repo too, which does not special-case itself to `artifact-ids:`. +- **D6.1 Pattern handoff.** Output: the release job downloads by `pattern:`/`merge-multiple:`, not `artifact-ids:`. **File** targets upload `release-asset--`. A file target the hub-hosted task builds through the `build-release-asset` hook fills `` with `build-release-asset`. A target contributing no file to the release (Docker) uploads no `release-asset-*` of its own, per D4.3, whatever other transfer artifact it uploads. The `pattern:` download is canonical for a single-target repo too, which does not special-case itself to `artifact-ids:`. - **D6.2 Branch drives config.** Output: a called workflow's branch-derived config reads `inputs.branch`, never `github.ref_name`. - **D6.3 Branch-named artifacts.** Output: every artifact name carries the branch, so a branch's artifacts do not collide with another branch's. - **D6.4 Target add/drop is consistent.** Output: adding or dropping a target updates **all** of the following. The list is the `enable_` value the publisher passes to the release task, and the publisher's `on.push.paths` entries where it carries a `push` trigger. The list continues with the `changes` paths-filter entry + output and the `smoke-build` enable-forward. The list includes `expect_release_assets` where the change adds the first file target or drops the last (D4.3). For a package target, the list also includes the separate `publish-` job. A repo owning its release task also updates the target's build job there, `build-` or `dotnet-publish` for the .NET target. It also updates the target's `github-release` and `build-docker` `needs:` entries. Everything in the `github-release` job **except its `needs:` list** stays verbatim, and so does the version and publish-plan logic. "Verbatim" never reaches the surfaces this item requires editing, that `needs:` list, the release task's job list, and the paths-filter among them. *Prevents: a partial subset that startup-fails on a missing leaf or never smoke-builds a target.* @@ -252,7 +253,7 @@ For each *applicable* scenario, evaluate every job's `if:`/`needs:` against the | S13 | deploy dispatch of a production environment from a non-default ref | **fails fast**, before anything is installed or written | D2.1 | | S14 | publish whose branch head gained different `.github/workflows` content after the build began | every update since a release bot's push or merge: release-create **skipped** and the publisher dispatched on the branch. In that case this run ends **cancelled** with its package publish jobs skipped (a Docker image already pushed). The dispatched run releases the head, queueing behind this run only where the head's publisher evaluates this run's group for a dispatch. A push landing after the branch is confirmed unmoved and before the dispatch is released as if it were such an update. That is an accepted, bounded limit per D4.7. Any other update: the step **fails**, nothing is released or dispatched | D4.1, D4.2, D4.5, D4.7 | | S15 | a smoke or publish run whose `build-nuget` job runs the hub default leaf, for a project declaring `net10.0;net11.0`. The package holds one framework's assembly under both `lib/` folders | the job plans both runtime lines, installs them, and consumes the package once per framework. It **fails** on the `TargetFrameworkAttribute` of the `lib/` folder holding the other framework's assembly, after reporting every other row. A correct package **passes**. The check uploads nothing in either run. A publish run's leaf has uploaded its artifacts already, and a failure leaves them to their retention and the dependent publish job **skipped** | D1.3, D1.7 | -| S16 | a smoke or publish run whose `build-pypi` job runs the hub default leaf, for a project with a `tests/` folder and a `python-versions` of `["3.13", "3.14"]`. Its wheel leaves out a module the tests import | the job builds, then consumes the wheel and the sdist under each line. It **fails** on the tests row of each artifact lacking the module, after reporting every other row. A correct package **passes** under both lines. The check uploads nothing in either run. A publish run's leaf has uploaded its artifact already. A failure leaves it to its retention, and the dependent publish job is **skipped** | D1.3, D1.8 | +| S16 | a smoke or publish run whose `build-pypi` job runs the hub default leaf, for a project with a `tests/` folder and a `python-versions` of `["3.13", "3.14"]`. Its wheel leaves out a module the tests import | the job builds, then consumes the wheel and the sdist under each line. It **fails** on the tests row of each artifact lacking the module, after reporting every other row. A correct package **passes** under both lines. The check uploads nothing in either run. A publish run's leaf has uploaded its artifacts already. A failure leaves them to their retention, and the dependent publish job is **skipped** | D1.3, D1.8 | ### 5C. Live Probe (Where Warranted) @@ -300,7 +301,7 @@ What each type adds beyond that, and how its leaf behaves, is below. - **`dotnet-publish`.** The target runs a sequential `dotnet publish` runtime loop inside one composite-action job. Configuration is Release on the default branch and Debug otherwise. A non-smoke run builds the full runtime set, archives the combined output as a `.7z`, and uploads it as `release-asset--dotnet-publish`. The archive is named from the project file stem unless `dotnet_publish_asset_name` overrides it. A smoke run builds a **strict, non-empty subset** of that runtime set and skips the archive and upload steps, so it uploads nothing. S1 smoke-builds that subset after a .NET project change. S7 attaches the 7z from a non-smoke run. The non-default leg sets `prerelease=true`, and the default leg sets `prerelease=false`. GitHub marks the stable default release "Latest" automatically. - **`nuget`.** The leaf uploads both `release-asset--nuget` and `nuget-build-` on a non-smoke run and pushes nothing. A separate `publish-nuget` job in the repo's own publisher consumes the second and runs `dotnet nuget push *.nupkg --skip-duplicate`. It then deletes that artifact under the download step's own success (D5.2). Section 3's `Output Seam by Destination` says why the push sits there rather than in the leaf. Configuration is Release on the default branch, Debug otherwise. The default leaf is followed by the D1.7 package consume check in smoke and publish runs alike. A caller's own `build-nuget` hook is outside it. The release-asset `.7z` carries the packages alone, never the loose build output, since each package already holds every target framework's build under its own `lib//`. Where symbols are enabled (`snupkg`), the push auto-carries the paired `.snupkg` to NuGet.org's symbol server and the release-asset `.7z` also contains it, a triple surface. NuGet.org derives `isPrerelease` from the SemVer2 `-g` suffix (the workflow sets no such flag). Test: S15 consumes the package per framework. S7 non-default leg publishes a prerelease package + asset, default a stable. S9 re-run is a server-side `--skip-duplicate` no-op. 5C: query NuGet.org for both versions and the symbol package. -- **`pypi`.** The leaf builds and uploads `pypi-build-`. A **separate** `publish-pypi` job (with `environment: pypi`, `id-token: write`, `actions: write`) does the OIDC Trusted-Publishing upload with `skip-existing: true`. It then **consume-then-deletes** the build artifact under the download step's own success (D5.2). So on S9 the build artifact is deleted even though the `release-asset-*` delete is skipped. The version is the `X.Y.Z` core of `SemVer2` with `.dev0` appended on `develop` only, per D3.4. PyPI contributes no `release-asset-*`. The default leaf is followed by the D1.8 package consume check in smoke and publish runs alike. A caller's own `build-pypi` hook is outside it. A PyPI-only repo sets `expect_release_assets: false` at the caller. Test: S16 consumes the wheel and the sdist per Python line. S7 default leg publishes a release, non-default a `.dev0`. S9 is a `skip-existing` no-op. 5C inspects the `dist/*` filenames and the compute-version log. +- **`pypi`.** The leaf uploads `release-asset--pypi` and `pypi-build-` on a non-smoke run. The first carries the wheel and sdist as bare files, so the release attaches them directly. A **separate** `publish-pypi` job (with `environment: pypi`, `id-token: write`, `actions: write`) does the OIDC Trusted-Publishing upload with `skip-existing: true`. It then **consume-then-deletes** the build artifact under the download step's own success (D5.2). So on S9 the build artifact is deleted even though the `release-asset-*` delete is skipped. The version is the `X.Y.Z` core of `SemVer2` with `.dev0` appended on `develop` only, per D3.4. The default leaf is followed by the D1.8 package consume check in smoke and publish runs alike. A caller's own `build-pypi` hook is outside it. A PyPI-only repo on the default leaf keeps `expect_release_assets` true, and one whose own `build-pypi` hook uploads no `release-asset-*` sets it false. Test: S16 consumes the wheel and the sdist per Python line. S7 default leg publishes a release, non-default a `.dev0`, and the release carries the wheel and the sdist. S9 is a `skip-existing` no-op. 5C inspects the `dist/*` filenames and the compute-version log. - **`docker`.** The leaf pushes the default branch multi-arch (amd64+arm64) and any other branch `amd64`-only, with a per-branch registry buildcache. A single-image repo caches to `:buildcache-`. A multi-image repo varies the cache **repository** rather than the tag, `:buildcache-` for each image, since the tag alone cannot distinguish two images. `cache-to` writes only the built branch and only on push, and `cache-from` reads both branches. It contributes no `release-asset-*`, so a Docker-only repo's caller passes `expect_release_assets: false`. The readme job (`peter-evans/dockerhub-description`, `DOCKER_HUB_ACCESS_TOKEN`) runs **only** when the default branch publishes, whether called directly or reached through the hub-hosted `publish-docker-readme-task.yml`. Where the Docker Hub overview differs from the project README, the repo publishes a `Docker/README.md` through that task, the Hub description being size-limited. The docker-readme task validates its two mutually-exclusive input sources, `repositories` against `manifest`+`manifest-jq`. It defaults to the calling repository where neither is supplied. A multi-image repo derives its publish matrix from the manifest. Docker **always re-pushes** the image, independently of a skipped release-create (S9). The tests that follow assume the default tag matrix, which a caller-supplied `matrix` or `docker-prepare` hook replaces. Test: S7 default leg pushes `latest` + the version tag and updates the readme. Non-default pushes `develop` + the version tag (amd64 only). S9 still re-pushes. 5C Docker probe needs `DOCKER_HUB_*` secrets and same-repo (not fork) runs. - **`library` (a worked example, not a fleet type).** No such leaf ships, so this row walks D6.4's add-a-target procedure rather than an existing shape. The target is a single new leaf that validates, zips, and uploads `release-asset--library` (`retention-days: 1` per D5.4, upload gated on smoke being false per D1.3). Adding it means a new `enable_library` input, and a `build-library` job and its `github-release` and `build-docker` `needs:` entries, in the release task. In the PR workflow it means a `library` paths-filter entry, `changes` output, and `smoke-build` enable-forward. Without that last one, D1.1 never smoke-builds the library. In the publisher, it means the `enable_library` value the publisher passes, and the library's paths in its `on.push.paths` where it carries a `push` trigger. **Only a repo that owns its release task can make the release-task half of that edit.** The hub-hosted release task declares a closed input set, and a call passing an input it does not declare fails. So a repo calling it sets `enable_release_asset` instead and carries the leaf as its `build-release-asset` hook. The hook writes the zip, and the task uploads it under `release-asset--build-release-asset`, skipping the upload on a smoke run. Keep `expect_release_assets: true` (it has a file target, unlike Docker). The caller's own validation job is replaced by a type-appropriate validator only where the reusable one cannot express this repo's validation. The aggregator is then re-pointed to the replacement (D1.2). `smoke-build` keeps `needs: [changes]`, as D1.2 has it. `version.json` and the NBGV `get-version` **job** are retained (they own the tag). Test: S1 smoke runs validate+zip and uploads nothing. S7 attaches the zip, prerelease on the non-default leg. S9 on a push re-run skips release-create and the asset-delete (the existing zip is untouched, no registry push). A `workflow_dispatch` re-run, by contrast, is D4.4's refresh case rather than S9's, re-uploading then re-deleting the asset. - **`upstream-wrapper`.** The repo tracks an upstream project's releases rather than versioning its own code. A scheduled resolver writes a `name -> version` state file and opens a per-branch bump pull request. The merge-bot auto-merges it, or leaves it for the maintainer where the tracker sets `auto-merge: false` (D8.3). The build leaf MUST read that state file for its build or image version instead of `SemVer2`, while NBGV still tags the release (D3.5). That is because the tracker ships without this consumer wiring. Test: S11 traces the bump from resolver to the publish that ships it, which for a merge-bot-merged `main` pin is D8.3's gated publish. Nothing in this row depends on which build-target types the wrapper also declares. diff --git a/docs/reusable-workflows.md b/docs/reusable-workflows.md index 57a98124e..e0b2848f3 100644 --- a/docs/reusable-workflows.md +++ b/docs/reusable-workflows.md @@ -56,7 +56,7 @@ A workflow whose job graph is identical across repos of a type is reached, not c ### The Hook Contract -A hook receives the fixed inputs [WORKFLOW.md "Reusable-Task Parameter Contract"][workflow-reusable-task-parameter-contract] gives a leaf today. Those are `ref`, `branch`, `smoke` where relevant, and the NBGV version outputs where a build needs them. It reports back through step outputs and, for a release target, through the existing artifact seam, `release-asset--`, which the hub's `github-release` job collects by pattern. Each task finds a hook by its `action.yml` alone, so a hook named `action.yaml` is never run. The `install-test-deps` hook is an exception, taking `leg` and `directories` inputs and reporting nothing back. It may also run a check that needs that leg's environment. A failure there fails the leg's `unit-test` job before its Python tests run. The `pre-test` hook is another, taking no inputs and reporting nothing back. Each `unit-test` leg runs it before the .NET SDK setup, where a .NET test project exists and the caller carries the hook. So a system tool a .NET test shells out to is installed before those tests run. The `build-release-asset` hook is another, writing its files into the `output-directory` it receives, on a smoke run too, and leaving the upload to the task. The task accepts only regular files at that directory's top level and refuses a subdirectory, a symlink, or a dot-prefixed name. A package hook also uploads the artifact its publish job consumes: a NuGet hook uploads `nuget-build-` as well as its `release-asset-*`. A PyPI hook uploads `pypi-build-` and no release asset at all. A NuGet or PyPI hook has to carry that exact package-artifact name or its publish job finds nothing. The `package-consume` hook is another, optional and taking `frameworks`, `package-id`, `version`, and `feed-dir` inputs while reporting nothing back. `build-nuget` runs it once after the hub default's own package consume check, in smoke and publish runs alike. So the hook loops over the JSON `frameworks` array itself. A caller carrying its own `build-nuget` hook gets neither check, since that hook's output location is unknown to the hub. The `validate` and `resolve-upstream` hooks can also take one string from their caller. `validate-task.yml` and `check-upstream-version-task.yml` each declare an optional `hook-input` input. Each passes a non-empty value on to its hook's own `hook-input` input. The task passes it from a step of its own, run only when the caller sets it. So a caller passing none runs a hook declaring no such input exactly as before. A caller that sets it needs a hook declaring `hook-input` as an optional input. The caller defines what the value means. It can name which of two callers runs the hook, or carry a change-gate result an expensive check skips on. The hub's no-op `validate-default` never receives it. A hook may use marketplace actions, which is the reason a hook is a composite action rather than a script. A toolchain setup, a Docker build, or a coverage upload is a `uses:` step, and a shell script cannot carry one. Action pins inside a hook follow the SHA-pinning rule like any other workflow content, and Dependabot bumps them in the repo that carries the hook. A hook runs with no persisted git credential, since every checkout ahead of a hook sets `persist-credentials: false`. A hook that runs git against the remote therefore passes its own credential to that call. +A hook receives the fixed inputs [WORKFLOW.md "Reusable-Task Parameter Contract"][workflow-reusable-task-parameter-contract] gives a leaf today. Those are `ref`, `branch`, `smoke` where relevant, and the NBGV version outputs where a build needs them. It reports back through step outputs and, for a release target, through the existing artifact seam, `release-asset--`, which the hub's `github-release` job collects by pattern. Each task finds a hook by its `action.yml` alone, so a hook named `action.yaml` is never run. The `install-test-deps` hook is an exception, taking `leg` and `directories` inputs and reporting nothing back. It may also run a check that needs that leg's environment. A failure there fails the leg's `unit-test` job before its Python tests run. The `pre-test` hook is another, taking no inputs and reporting nothing back. Each `unit-test` leg runs it before the .NET SDK setup, where a .NET test project exists and the caller carries the hook. So a system tool a .NET test shells out to is installed before those tests run. The `build-release-asset` hook is another, writing its files into the `output-directory` it receives, on a smoke run too, and leaving the upload to the task. The task accepts only regular files at that directory's top level and refuses a subdirectory, a symlink, or a dot-prefixed name. A package hook also uploads the artifact its publish job consumes: a NuGet hook uploads `nuget-build-` as well as its `release-asset-*`. A PyPI hook uploads `pypi-build-`, and a PyPI-only caller whose hook uploads no `release-asset-*` sets `expect_release_assets` false. A NuGet or PyPI hook has to carry that exact package-artifact name or its publish job finds nothing. The `package-consume` hook is another, optional and taking `frameworks`, `package-id`, `version`, and `feed-dir` inputs while reporting nothing back. `build-nuget` runs it once after the hub default's own package consume check, in smoke and publish runs alike. So the hook loops over the JSON `frameworks` array itself. A caller carrying its own `build-nuget` hook gets neither check, since that hook's output location is unknown to the hub. The `validate` and `resolve-upstream` hooks can also take one string from their caller. `validate-task.yml` and `check-upstream-version-task.yml` each declare an optional `hook-input` input. Each passes a non-empty value on to its hook's own `hook-input` input. The task passes it from a step of its own, run only when the caller sets it. So a caller passing none runs a hook declaring no such input exactly as before. A caller that sets it needs a hook declaring `hook-input` as an optional input. The caller defines what the value means. It can name which of two callers runs the hook, or carry a change-gate result an expensive check skips on. The hub's no-op `validate-default` never receives it. A hook may use marketplace actions, which is the reason a hook is a composite action rather than a script. A toolchain setup, a Docker build, or a coverage upload is a `uses:` step, and a shell script cannot carry one. Action pins inside a hook follow the SHA-pinning rule like any other workflow content, and Dependabot bumps them in the repo that carries the hook. A hook runs with no persisted git credential, since every checkout ahead of a hook sets `persist-credentials: false`. A hook that runs git against the remote therefore passes its own credential to that call. ### Pinning @@ -704,7 +704,7 @@ jobs: done ``` -A Docker repo's stub removes the `push:` block (its paths filter with it). It adds `schedule: - cron: '0 2 * * MON'` to the trigger block. It sets `enable_docker: true`, `dockerhub: true`, `docker_image: ptr727/widget`, `enable_nuget: false` (dropping `nuget_project` with it) and `expect_release_assets: false`. It maps `DOCKER_HUB_USERNAME`/`DOCKER_HUB_ACCESS_TOKEN` under the `publish` job's `secrets:`. It drops the `publish-nuget` job, since Docker Hub has no OIDC equivalent and the hub task pushes the image itself. A PyPI repo sets `enable_pypi: true` with `pypi_project_dir` and `pypi_version_file`. It also sets `enable_nuget: false` (dropping `nuget_project`) and `expect_release_assets: false`, since PyPI contributes no release asset. It swaps `publish-nuget` for the same shape one registry over, verbatim as today's: +A Docker repo's stub removes the `push:` block (its paths filter with it). It adds `schedule: - cron: '0 2 * * MON'` to the trigger block. It sets `enable_docker: true`, `dockerhub: true`, `docker_image: ptr727/widget`, `enable_nuget: false` (dropping `nuget_project` with it) and `expect_release_assets: false`. It maps `DOCKER_HUB_USERNAME`/`DOCKER_HUB_ACCESS_TOKEN` under the `publish` job's `secrets:`. It drops the `publish-nuget` job, since Docker Hub has no OIDC equivalent and the hub task pushes the image itself. A PyPI repo sets `enable_pypi: true` with `pypi_project_dir` and `pypi_version_file`. It also sets `enable_nuget: false` (dropping `nuget_project`) and keeps `expect_release_assets` at its default, since the default PyPI leaf uploads a release asset. It swaps `publish-nuget` for the same shape one registry over, verbatim as today's: ```yaml publish-pypi: diff --git a/tests/test_release_guards.py b/tests/test_release_guards.py index 285798d66..cb1ae33a6 100755 --- a/tests/test_release_guards.py +++ b/tests/test_release_guards.py @@ -628,6 +628,39 @@ def names_a_ref(line: str) -> bool: with self.subTest(form=form): self.assertFalse(names_a_ref(form)) + def test_default_leaves_upload_a_smoke_gated_release_asset(self) -> None: + # A typo in the name leaves the release without the files, and a missing gate lets a smoke run upload. + for leaf in ("nuget", "pypi"): + with self.subTest(leaf=leaf): + step = yaml_step( + (REPO / f".github/actions/{leaf}-build-default/action.yml").read_text( + encoding="utf-8" + ), + "Upload release asset step", + ) + self.assertEqual("${{ inputs.smoke != 'true' }}", yaml_value(step, "if")) + self.assertEqual( + f"release-asset-${{{{ inputs.branch }}}}-{leaf}", + yaml_value(step, "with", "name"), + ) + self.assertEqual("1", yaml_value(step, "with", "retention-days")) + + # The wheel and sdist are attached as they are, so the upload takes the files rather than an archive. + pypi = yaml_step( + (REPO / ".github/actions/pypi-build-default/action.yml").read_text(encoding="utf-8"), + "Upload release asset step", + ) + self.assertEqual("${{ inputs.project-dir }}/dist/*", yaml_value(pypi, "with", "path")) + self.assertEqual("error", yaml_value(pypi, "with", "if-no-files-found")) + + # Without merge-multiple the files land in a per-artifact subdirectory that ./Publish/* never attaches as files. + task = (REPO / ".github/workflows/build-release-task.yml").read_text(encoding="utf-8") + download = yaml_step(task, "Download release asset artifacts step") + self.assertEqual( + "release-asset-${{ inputs.branch }}-*", yaml_value(download, "with", "pattern") + ) + self.assertEqual("true", yaml_value(download, "with", "merge-multiple")) + def test_nuget_artifact_name_matches_contracts_and_consumers(self) -> None: canonical_name = "nuget-build-" legacy_name = "nuget-push" + "-default" From d7300a72ced78514237e31394a043f06636efbb2 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Thu, 3 Dec 2026 08:18:08 -0800 Subject: [PATCH 4/7] Run Each .NET Line as Its Own Unit Test Leg (#4617) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #4609 Splits the .NET tests out of the Python `unit-test` job of `validate-task.yml` into a new `unit-test-dotnet` job. Each declared .NET line is its own `Unit test job (.NET X.Y)` leg running `dotnet test --framework netX.Y`, with a per-line Codecov flag beside `dotnet`. The `test-matrix` job now builds the .NET matrix, reports whether a `*Tests*.csproj` exists, and resolves the Python directories, so each job skips cleanly when its kind is absent. The `dotnet-sdk` action gains a `lines` output so the selection is not duplicated. `WORKFLOW.md` gains D1.9, and the stale docs, spec assert, and skill source are updated. ## Open local-review findings (edit budget spent) - `.github/workflows/validate-task.yml:84`, the comment above `Select Python version step` says the test-matrix job cannot tell whether the caller holds Python, which this change made false. Class `introduced`, fixed in the last commit. - The two stale single-job doc sentences earlier passes raised are fixed in the last commit. ## Dropped findings - Forcing `--framework` on every project, the net10.0 fallback line, a solution-level `--framework`, and skipping the install-test-deps hook check where no Python directory resolves are the decided design of #4609. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Sonnet 5.5 --- .agents/skills/dotnet-codestyle/SKILL.md | 6 +- .../references/d-guarantees.md | 3 +- .../references/test-methodology.md | 2 + .../.source-digests/dotnet-codestyle | 2 +- .../.source-digests/workflow-ci-contract | 2 +- .../skills/dotnet-codestyle/SKILL.md | 6 +- .../references/d-guarantees.md | 3 +- .../references/test-methodology.md | 2 + .github/actions/dotnet-sdk/action.yml | 16 ++ .github/actions/validate-default/action.yml | 2 +- .github/skills/dotnet-codestyle/SKILL.md | 6 +- .../references/d-guarantees.md | 3 +- .../references/test-methodology.md | 2 + .github/workflows/validate-task.yml | 194 ++++++++++-------- WORKFLOW.md | 5 +- docs/reusable-workflows.md | 14 +- spec/project-types.json | 2 +- tests/test_release_guards.py | 186 +++++++++++++---- 18 files changed, 314 insertions(+), 142 deletions(-) diff --git a/.agents/skills/dotnet-codestyle/SKILL.md b/.agents/skills/dotnet-codestyle/SKILL.md index 873b071fe..a26a19ae0 100644 --- a/.agents/skills/dotnet-codestyle/SKILL.md +++ b/.agents/skills/dotnet-codestyle/SKILL.md @@ -127,9 +127,9 @@ Shared MSBuild configuration is centralized at the repository root, never duplic sets a singular `TargetFramework`, the multi-targeted `.csproj` clears it, since a singular value wins and builds one framework only. Its test projects run each framework under that framework's own runtime. So the repository passes the hub's `validate-task.yml` a `dotnet-versions` input - naming every line, the `global.json` line first, such as `'["11.0", "10.0"]'`. That installs - each line beside the selected one in the one unit-test job. An entry leading with another line - fails the run. + naming every line, the `global.json` line first, such as `'["11.0", "10.0"]'`. Each line then + runs as its own unit-test leg, with every line installed beside the selected one. An entry + leading with another line fails the run. A developer host now needs a release SDK on the repository's line, 10.0.x for the fleet default today. A host holding only another major, or only a 10.0 preview, fails with a clear error. It diff --git a/.agents/skills/workflow-ci-contract/references/d-guarantees.md b/.agents/skills/workflow-ci-contract/references/d-guarantees.md index 327dd5149..f7e3097b7 100644 --- a/.agents/skills/workflow-ci-contract/references/d-guarantees.md +++ b/.agents/skills/workflow-ci-contract/references/d-guarantees.md @@ -11,13 +11,14 @@ The required behaviors, organized by domain. Each is a **MUST**, and its `Output ### D1 - PR Fast-Feedback (Smoke) - **D1.1 Only changed targets build.** Input: a PR touching some targets. Output: the paths-filter marks exactly those targets and only their smoke builds run. Unchanged targets skip. A repo's own targets MUST each have a filter entry, so a touched target is never silently skipped. That entry lists paths rather than negating them, so a change matching no entry marks nothing and every smoke build skips. *Prevents: rebuilding everything, and a changed target slipping through unbuilt.* -- **D1.2 A validation job always runs.** Input: any PR. Output: a validation job runs unconditionally and the aggregator `needs:` it. That job is the caller's own job reaching the reusable validator, named `validate` in every shipped stub. That name is what the aggregator's `needs:` carries. The validator's internal jobs (`test-matrix`, `lint`, `unit-test` and `validate` in the hub's `validate-task.yml`) are not addressable from a caller. So a `validate` in a caller's `needs:` list always names the caller's own job, never the validator's internal one. The validator detects the tree rather than the repo's language, so a non-.NET repo calls the same one rather than replacing it. It runs the doc and repo gates everywhere, and the `dotnet test` path only where a `*Tests*.csproj` project exists. It runs the Python path in each directory the caller declares in its `python-directories` input. Where the caller declares none and a root `pyproject.toml` is tracked, it runs that path at the root instead. At that undeclared root the test leg runs only where a `tests/` suite sits beside a `uv.lock` or `requirements*.txt`. A declared directory without `tests/`, by contrast, fails (D1.6). The declaration rather than discovery decides what is gated, since a stray or vendored `.py` file would otherwise change the gate silently. The validator warns about a tracked `.py` file no declared directory covers. It checks out the triggering commit, `github.sha`, with no `ref` input. It needs none, because a reusable workflow reads its caller's `github` context, so a publisher's call validates the same commit its publish job pins. A repo whose tests take another shape can run them from its own `.github/actions/validate/action.yml` hook, which the validator runs where that file exists. That hook receives no secret, so a repo whose other-shape tests owe D1.6's coverage upload is one whose validation the validator cannot express. A repo whose validation it cannot express **replaces** the call (not deletes it) with its own validator and re-points the aggregator's `needs:` to the replacement. `smoke-build` `needs:` the `changes` job rather than the validation job, so no second `needs:` moves with it. *Prevents: a PR merging with no validation, or a dangling `needs:` that stops the whole workflow from loading.* +- **D1.2 A validation job always runs.** Input: any PR. Output: a validation job runs unconditionally and the aggregator `needs:` it. That job is the caller's own job reaching the reusable validator, named `validate` in every shipped stub. That name is what the aggregator's `needs:` carries. The validator's internal jobs (`test-matrix`, `lint`, `unit-test`, `unit-test-dotnet` and `validate` in the hub's `validate-task.yml`) are not addressable from a caller. So a `validate` in a caller's `needs:` list always names the caller's own job, never the validator's internal one. The validator detects the tree rather than the repo's language, so a non-.NET repo calls the same one rather than replacing it. It runs the doc and repo gates everywhere, and the `dotnet test` path only where a `*Tests*.csproj` project exists. It runs the Python path in each directory the caller declares in its `python-directories` input. Where the caller declares none and a root `pyproject.toml` is tracked, it runs that path at the root instead. At that undeclared root the test leg runs only where a `tests/` suite sits beside a `uv.lock` or `requirements*.txt`. A declared directory without `tests/`, by contrast, fails (D1.6). The declaration rather than discovery decides what is gated, since a stray or vendored `.py` file would otherwise change the gate silently. The validator warns about a tracked `.py` file no declared directory covers. It checks out the triggering commit, `github.sha`, with no `ref` input. It needs none, because a reusable workflow reads its caller's `github` context, so a publisher's call validates the same commit its publish job pins. A repo whose tests take another shape can run them from its own `.github/actions/validate/action.yml` hook, which the validator runs where that file exists. That hook receives no secret, so a repo whose other-shape tests owe D1.6's coverage upload is one whose validation the validator cannot express. A repo whose validation it cannot express **replaces** the call (not deletes it) with its own validator and re-points the aggregator's `needs:` to the replacement. `smoke-build` `needs:` the `changes` job rather than the validation job, so no second `needs:` moves with it. *Prevents: a PR merging with no validation, or a dangling `needs:` that stops the whole workflow from loading.* - **D1.3 Smoke never publishes and never uploads.** Input: `smoke: true`. Output: full compile/lint/test, but no registry/image push, no release, and **no** artifact uploads. Every `upload-artifact`, including any aggregation job, is gated on smoke being false. That gate is written `!inputs.smoke` at the workflow layer and `inputs.smoke != 'true'` in a composite action, whose inputs are strings. *Prevents: a PR publishing, and orphaned artifacts churning the storage quota.* - **D1.4 Workflow-file changes are not smoke-built.** Input: a PR changing only `.github/workflows/**`. Output: the paths-filter marks no target, so smoke-build skips. An inclusion list satisfying D1.1 reaches this by leaving workflow paths out of every target's entry. *Implication: a workflow-only change is not smoke-built, but actionlint still validates it in CI.* - **D1.5 One required aggregator gates merge.** Input: any PR. Output: a single aggregator job must **succeed**. It must run under `if: always()`, so a failed or skipped dependency cannot skip the gate itself. It must also `needs:` the validation job, and the `changes` and `smoke-build` jobs too wherever the repo has a smoke build. It must treat a **skipped** smoke build as pass, and **block** on `failure`/`cancelled`. Its name is ruleset-bound: the job `name:` and the ruleset `context:` are the same string and MUST be renamed together, never independently. The workflow holding it MUST trigger on `pull_request`. A gate without a `pull_request` trigger never runs the validator's pull-request-only steps, the prose gate among them. A workflow any other event also triggers yields that name only when `github.event_name == 'pull_request'`, through an expression `name:`. Otherwise a dispatch or push run on a PR's head posts the required context without the PR run's gates. *Prevents: a paths-filter error letting a target-changing PR merge unbuilt.* - **D1.6 Coverage is reported to Codecov (C# and Python).** Input: a C# or Python repo that has tests for that type. Output: the validation job runs those tests under coverage collection, and a `codecov/codecov-action` step uploads the report. The collection is `dotnet test --coverage --coverage-output-format cobertura --results-directory ./coverage`, leaving `--coverage-output` unset so each test project writes its own report rather than overwriting a shared one. A bare call resolves one workspace from the working directory, so it fails at a root holding none or more than one. Unless the repository root holds exactly one solution or project, the hub's validator therefore runs the collection once per tracked `*Tests*.csproj` with `--project`. It names no solution in that case, since a solution holding no test project fails the run. Or it is `pytest --cov-report=xml` in a Python directory with its own `uv.lock` or `requirements*.txt`, whose own `pyproject.toml` selects what to measure. Or it is `coverage run -m unittest discover -s tests` then `coverage xml` in a `lint-only` one. The upload is **best-effort** (`continue-on-error` and/or `fail_ci_if_error: false`), so a Codecov outage or an absent token never reds the gate. Each leg **fails its test step when the run wrote no report**. The reason is that the best-effort upload reads a missing report exactly as it reads a healthy run. A second reason is that, on the Python leg, `--cov-report=xml` alone selects nothing to measure. The C# leg renames each report to `coverage-.cobertura.xml` before the upload step reads the directory, since `codecov-cli`'s own finder does not match the default name. A repo owning its validator rather than calling the hub's owes that rename itself. `CODECOV_TOKEN` lives in the repo's **actions** and **dependabot** secret stores. The token is in the second because a run triggered by a Dependabot pull request reads the Dependabot store. Without the token there, the upload would otherwise skip silently on every bot pull request. A caller reaching the reusable validator across repositories names the secret it passes (`secrets:` with `CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}`). It does so on its pull request path and its publisher path alike. That is because `secrets: inherit` is documented for a caller in the same organization or enterprise, which a personal account is not. A call by local path stays inside one repository, where the caller's own store is the one the callee reads. So `secrets: inherit` is available there instead of naming each secret. The repo ships a **`.codecov.yml`** at the repository root. It sets the project and patch statuses to **`informational: true`**, so a coverage delta never gates a pull request. A repo whose quality bar requires a threshold may turn that off. The same file excludes intentionally-untested, non-shipped code (an example or benchmark project) from the denominator via `ignore`. Codecov reads its configuration under several names, but `.codecov.yml` is the only one the fleet accepts. So a copy under any other name is drift to rename. Coverage output is a build artifact, so `.gitignore` excludes it. The C# invocation runs under **Microsoft.Testing.Platform**, and the runner declaration, package references, and version floor an MTP-based test project needs are `CODESTYLE.md`'s .NET side. The Python invocation needs **`pytest-cov`** and a coverage selector, which are `CODESTYLE.md`'s Python side. A Python directory declared in the validator's `python-directories` input owes a `tests/` suite whatever its profile, so the validator fails one that has none. N/A for a repo carrying no tests for that type. *Prevents: coverage silently going unreported, and a coverage regression blocking an unrelated pull request.* - **D1.7 A built NuGet package is consumed before it publishes.** Input: a repo whose `build-nuget` job runs the hub's default leaf, in a smoke run or a publish run alike. Output: after the leaf packs, the job restores, builds, and runs a throwaway console project against that exact `.nupkg`. It does so once per target framework the project declares. Each consumer lives outside the checkout, so the caller's `global.json` and `Directory.Build.props` do not apply. Its `nuget.config` resolves the package ID, and the ID of each sibling package in the folder holding the build output, only from that folder. Every other ID resolves from nuget.org. Its package cache is its own, so neither a cached nor a published copy can stand in for the artifact under test. The consumer loads the package assembly and calls `GetExportedTypes()`. The check asserts from `obj/project.assets.json` that the package resolved from the `lib//` folder of the consumer's own framework. It also asserts that the loaded assembly's `TargetFrameworkAttribute` matches that folder. A `netstandard` framework is consumed under the SDK line `global.json` selects, or the newest declared line where there is none. It is asserted against the folder it resolved. A framework the check does not consume is reported skipped. Examples are .NET Framework, `netcoreapp3.1`, and a platform-specific `netX.Y-windows`. The attribute row of a `netstandard` consumer resolving such a folder is skipped too. Four static assertions join them. The package's `lib//` folders equal the declared frameworks. The nuspec `` equals the build version. The nuspec holds a dependency group per framework. A symbol package exists where the project enables symbols. Every declared `netX.Y` and `netstandard` framework is consumed and reported with one summary row per assertion. A failed step ends that framework's rows rather than the run. The job fails at the end if any failed. The check covers a library package, whose assemblies sit under `lib//`. The check uploads nothing, so it honors D1.3. It runs inside the build job, so a failure blocks the publish job that `needs:` that build. A caller's own `build-nuget` hook replaces the whole leaf and is outside the check. A caller's own `.github/actions/package-consume/action.yml` runs once after the default check. It receives the declared frameworks as JSON beside the package ID, version, and package folder. *Prevents: a defect that exists only in the packed form shipping. One example is one target framework's assembly packed under every `lib//` folder while the tests, which reach the library through a project reference, stay green.* - **D1.8 A built PyPI package is consumed before it publishes.** Input: a repo whose `build-pypi` job runs the hub's default leaf, in a smoke run or a publish run alike. Output: after the leaf builds, the job installs the wheel and, separately, the sdist into a fresh `uv venv`. It does so for each line of the `python-versions` input of `build-release-task.yml`. Empty runs the one line the root `.python-version` selects. Where there is none it runs the hub's fallback line. A caller that sets `python-versions` for both `validate-task.yml` and `build-release-task.yml` passes the same value to each. So the lines its tests run under are the lines its artifact is consumed under. Each environment lives outside the checkout. It installs the artifact, then the project's locked dependency groups from `uv.lock` without the project itself. The check asserts that `importlib.metadata` reports the version the leaf computed. It also asserts that every top-level name the installed distribution provides imports from the environment's site-packages, not the source tree. A distribution providing none, such as one of scripts only, reports that row skipped. It then runs the caller's `tests/` folder against the installed copy with pytest in `importlib` import mode. That run has the source tree off `sys.path` and the project's `pythonpath` setting cleared. Its working directory is outside the project. So the caller's suite must not read a path relative to the project root, or a tool setting read from the working directory. It must import a sibling helper as part of a package. The project directory holds its own `uv.lock`. A project with no `tests/` folder, or a run collecting no tests, is reported skipped rather than passed. Every line and artifact reports one summary row per assertion. A failed environment, install, or metadata read ends that artifact's rows rather than the run. The job fails at the end if any failed. The check uploads nothing, so it honors D1.3. It runs inside the build job, so a failure blocks the publish job that `needs:` that build. A caller's own `build-pypi` hook replaces the whole leaf and is outside the check. *Prevents: a defect that exists only in the built form shipping. One example is a module left out of the wheel while the tests, which import it from the source tree, stay green.* +- **D1.9 Each declared test line runs as its own named unit-test leg.** Input: a repo declaring .NET lines in `dotnet-versions` of `validate-task.yml`, Python lines in `python-versions`, or both. Output: each declared .NET line runs as a `Unit test job (.NET X.Y)` leg running `dotnet test --framework netX.Y` under that line's runtime. Each declared Python line runs as a `Unit test job (Python X.Y)` leg, or as the caller's named `test-matrix` legs where it sets one. A caller declaring neither runs the one line each of `global.json` and `.python-version` selects. The hub's fallback line stands in where a file is absent. The .NET legs run only where a `*Tests*.csproj` exists. The Python legs run only where a Python directory resolves. So a repo holding one kind reports no leg of the other. Each leg uploads its own coverage report, and the .NET upload carries a per-line flag beside `dotnet`. A failing leg does not cancel its siblings. *Prevents: a failing target framework or interpreter hiding inside a combined run naming none of them. A .NET-only repo reporting a Python line it never ran is the other.* ### D2 - Input/State Validation at Entry diff --git a/.agents/skills/workflow-ci-contract/references/test-methodology.md b/.agents/skills/workflow-ci-contract/references/test-methodology.md index 6381fc559..4136c0f86 100644 --- a/.agents/skills/workflow-ci-contract/references/test-methodology.md +++ b/.agents/skills/workflow-ci-contract/references/test-methodology.md @@ -18,6 +18,8 @@ D1.7 is read in the build job. A step after the default leaf plans the declared D1.8 is read in the build job. A step after the default leaf runs the consume check. It receives the build's computed version and the `python-versions` list. Empty becomes the one line the root `.python-version` selects, or the hub's fallback line where there is none. It uploads nothing. +D1.9 is read in the validate task's job list. The `Build test matrix job` outputs one matrix per kind, and each unit-test job's `matrix` reads its output. The .NET job's `dotnet test` carries `--framework` for its matrix line, and the Python job holds no .NET step. Each job's `if:` reads the output that says its kind exists. + Cite what each verdict rests on. That is `file:line` for a file in the audited repo. It is the evidence's own name where a setting, a ruleset, or a secret name rather than a file is the evidence. Where the guarantee binds a workflow or composite action the audited repo only reaches, it is `/@` plus the `file:line` in that repo. The callee is read at the SHA the caller pins. An **N/A** verdict names the absent construct instead, there being no line to cite. ### 5B. End-to-End Trace Scenarios (No Execution, Deterministic from the YAML) diff --git a/.claude-plugin/fleet-skills/.source-digests/dotnet-codestyle b/.claude-plugin/fleet-skills/.source-digests/dotnet-codestyle index 808eb791a..0e2bb1f4c 100644 --- a/.claude-plugin/fleet-skills/.source-digests/dotnet-codestyle +++ b/.claude-plugin/fleet-skills/.source-digests/dotnet-codestyle @@ -1 +1 @@ -4220137c3ae914a3 +f3639b6ba86a32a6 diff --git a/.claude-plugin/fleet-skills/.source-digests/workflow-ci-contract b/.claude-plugin/fleet-skills/.source-digests/workflow-ci-contract index 4553344d0..11468940c 100644 --- a/.claude-plugin/fleet-skills/.source-digests/workflow-ci-contract +++ b/.claude-plugin/fleet-skills/.source-digests/workflow-ci-contract @@ -1 +1 @@ -750bae5d66dc9c1d +48bde8411845cb66 diff --git a/.claude-plugin/fleet-skills/skills/dotnet-codestyle/SKILL.md b/.claude-plugin/fleet-skills/skills/dotnet-codestyle/SKILL.md index 873b071fe..a26a19ae0 100644 --- a/.claude-plugin/fleet-skills/skills/dotnet-codestyle/SKILL.md +++ b/.claude-plugin/fleet-skills/skills/dotnet-codestyle/SKILL.md @@ -127,9 +127,9 @@ Shared MSBuild configuration is centralized at the repository root, never duplic sets a singular `TargetFramework`, the multi-targeted `.csproj` clears it, since a singular value wins and builds one framework only. Its test projects run each framework under that framework's own runtime. So the repository passes the hub's `validate-task.yml` a `dotnet-versions` input - naming every line, the `global.json` line first, such as `'["11.0", "10.0"]'`. That installs - each line beside the selected one in the one unit-test job. An entry leading with another line - fails the run. + naming every line, the `global.json` line first, such as `'["11.0", "10.0"]'`. Each line then + runs as its own unit-test leg, with every line installed beside the selected one. An entry + leading with another line fails the run. A developer host now needs a release SDK on the repository's line, 10.0.x for the fleet default today. A host holding only another major, or only a 10.0 preview, fails with a clear error. It diff --git a/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/d-guarantees.md b/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/d-guarantees.md index 327dd5149..f7e3097b7 100644 --- a/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/d-guarantees.md +++ b/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/d-guarantees.md @@ -11,13 +11,14 @@ The required behaviors, organized by domain. Each is a **MUST**, and its `Output ### D1 - PR Fast-Feedback (Smoke) - **D1.1 Only changed targets build.** Input: a PR touching some targets. Output: the paths-filter marks exactly those targets and only their smoke builds run. Unchanged targets skip. A repo's own targets MUST each have a filter entry, so a touched target is never silently skipped. That entry lists paths rather than negating them, so a change matching no entry marks nothing and every smoke build skips. *Prevents: rebuilding everything, and a changed target slipping through unbuilt.* -- **D1.2 A validation job always runs.** Input: any PR. Output: a validation job runs unconditionally and the aggregator `needs:` it. That job is the caller's own job reaching the reusable validator, named `validate` in every shipped stub. That name is what the aggregator's `needs:` carries. The validator's internal jobs (`test-matrix`, `lint`, `unit-test` and `validate` in the hub's `validate-task.yml`) are not addressable from a caller. So a `validate` in a caller's `needs:` list always names the caller's own job, never the validator's internal one. The validator detects the tree rather than the repo's language, so a non-.NET repo calls the same one rather than replacing it. It runs the doc and repo gates everywhere, and the `dotnet test` path only where a `*Tests*.csproj` project exists. It runs the Python path in each directory the caller declares in its `python-directories` input. Where the caller declares none and a root `pyproject.toml` is tracked, it runs that path at the root instead. At that undeclared root the test leg runs only where a `tests/` suite sits beside a `uv.lock` or `requirements*.txt`. A declared directory without `tests/`, by contrast, fails (D1.6). The declaration rather than discovery decides what is gated, since a stray or vendored `.py` file would otherwise change the gate silently. The validator warns about a tracked `.py` file no declared directory covers. It checks out the triggering commit, `github.sha`, with no `ref` input. It needs none, because a reusable workflow reads its caller's `github` context, so a publisher's call validates the same commit its publish job pins. A repo whose tests take another shape can run them from its own `.github/actions/validate/action.yml` hook, which the validator runs where that file exists. That hook receives no secret, so a repo whose other-shape tests owe D1.6's coverage upload is one whose validation the validator cannot express. A repo whose validation it cannot express **replaces** the call (not deletes it) with its own validator and re-points the aggregator's `needs:` to the replacement. `smoke-build` `needs:` the `changes` job rather than the validation job, so no second `needs:` moves with it. *Prevents: a PR merging with no validation, or a dangling `needs:` that stops the whole workflow from loading.* +- **D1.2 A validation job always runs.** Input: any PR. Output: a validation job runs unconditionally and the aggregator `needs:` it. That job is the caller's own job reaching the reusable validator, named `validate` in every shipped stub. That name is what the aggregator's `needs:` carries. The validator's internal jobs (`test-matrix`, `lint`, `unit-test`, `unit-test-dotnet` and `validate` in the hub's `validate-task.yml`) are not addressable from a caller. So a `validate` in a caller's `needs:` list always names the caller's own job, never the validator's internal one. The validator detects the tree rather than the repo's language, so a non-.NET repo calls the same one rather than replacing it. It runs the doc and repo gates everywhere, and the `dotnet test` path only where a `*Tests*.csproj` project exists. It runs the Python path in each directory the caller declares in its `python-directories` input. Where the caller declares none and a root `pyproject.toml` is tracked, it runs that path at the root instead. At that undeclared root the test leg runs only where a `tests/` suite sits beside a `uv.lock` or `requirements*.txt`. A declared directory without `tests/`, by contrast, fails (D1.6). The declaration rather than discovery decides what is gated, since a stray or vendored `.py` file would otherwise change the gate silently. The validator warns about a tracked `.py` file no declared directory covers. It checks out the triggering commit, `github.sha`, with no `ref` input. It needs none, because a reusable workflow reads its caller's `github` context, so a publisher's call validates the same commit its publish job pins. A repo whose tests take another shape can run them from its own `.github/actions/validate/action.yml` hook, which the validator runs where that file exists. That hook receives no secret, so a repo whose other-shape tests owe D1.6's coverage upload is one whose validation the validator cannot express. A repo whose validation it cannot express **replaces** the call (not deletes it) with its own validator and re-points the aggregator's `needs:` to the replacement. `smoke-build` `needs:` the `changes` job rather than the validation job, so no second `needs:` moves with it. *Prevents: a PR merging with no validation, or a dangling `needs:` that stops the whole workflow from loading.* - **D1.3 Smoke never publishes and never uploads.** Input: `smoke: true`. Output: full compile/lint/test, but no registry/image push, no release, and **no** artifact uploads. Every `upload-artifact`, including any aggregation job, is gated on smoke being false. That gate is written `!inputs.smoke` at the workflow layer and `inputs.smoke != 'true'` in a composite action, whose inputs are strings. *Prevents: a PR publishing, and orphaned artifacts churning the storage quota.* - **D1.4 Workflow-file changes are not smoke-built.** Input: a PR changing only `.github/workflows/**`. Output: the paths-filter marks no target, so smoke-build skips. An inclusion list satisfying D1.1 reaches this by leaving workflow paths out of every target's entry. *Implication: a workflow-only change is not smoke-built, but actionlint still validates it in CI.* - **D1.5 One required aggregator gates merge.** Input: any PR. Output: a single aggregator job must **succeed**. It must run under `if: always()`, so a failed or skipped dependency cannot skip the gate itself. It must also `needs:` the validation job, and the `changes` and `smoke-build` jobs too wherever the repo has a smoke build. It must treat a **skipped** smoke build as pass, and **block** on `failure`/`cancelled`. Its name is ruleset-bound: the job `name:` and the ruleset `context:` are the same string and MUST be renamed together, never independently. The workflow holding it MUST trigger on `pull_request`. A gate without a `pull_request` trigger never runs the validator's pull-request-only steps, the prose gate among them. A workflow any other event also triggers yields that name only when `github.event_name == 'pull_request'`, through an expression `name:`. Otherwise a dispatch or push run on a PR's head posts the required context without the PR run's gates. *Prevents: a paths-filter error letting a target-changing PR merge unbuilt.* - **D1.6 Coverage is reported to Codecov (C# and Python).** Input: a C# or Python repo that has tests for that type. Output: the validation job runs those tests under coverage collection, and a `codecov/codecov-action` step uploads the report. The collection is `dotnet test --coverage --coverage-output-format cobertura --results-directory ./coverage`, leaving `--coverage-output` unset so each test project writes its own report rather than overwriting a shared one. A bare call resolves one workspace from the working directory, so it fails at a root holding none or more than one. Unless the repository root holds exactly one solution or project, the hub's validator therefore runs the collection once per tracked `*Tests*.csproj` with `--project`. It names no solution in that case, since a solution holding no test project fails the run. Or it is `pytest --cov-report=xml` in a Python directory with its own `uv.lock` or `requirements*.txt`, whose own `pyproject.toml` selects what to measure. Or it is `coverage run -m unittest discover -s tests` then `coverage xml` in a `lint-only` one. The upload is **best-effort** (`continue-on-error` and/or `fail_ci_if_error: false`), so a Codecov outage or an absent token never reds the gate. Each leg **fails its test step when the run wrote no report**. The reason is that the best-effort upload reads a missing report exactly as it reads a healthy run. A second reason is that, on the Python leg, `--cov-report=xml` alone selects nothing to measure. The C# leg renames each report to `coverage-.cobertura.xml` before the upload step reads the directory, since `codecov-cli`'s own finder does not match the default name. A repo owning its validator rather than calling the hub's owes that rename itself. `CODECOV_TOKEN` lives in the repo's **actions** and **dependabot** secret stores. The token is in the second because a run triggered by a Dependabot pull request reads the Dependabot store. Without the token there, the upload would otherwise skip silently on every bot pull request. A caller reaching the reusable validator across repositories names the secret it passes (`secrets:` with `CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}`). It does so on its pull request path and its publisher path alike. That is because `secrets: inherit` is documented for a caller in the same organization or enterprise, which a personal account is not. A call by local path stays inside one repository, where the caller's own store is the one the callee reads. So `secrets: inherit` is available there instead of naming each secret. The repo ships a **`.codecov.yml`** at the repository root. It sets the project and patch statuses to **`informational: true`**, so a coverage delta never gates a pull request. A repo whose quality bar requires a threshold may turn that off. The same file excludes intentionally-untested, non-shipped code (an example or benchmark project) from the denominator via `ignore`. Codecov reads its configuration under several names, but `.codecov.yml` is the only one the fleet accepts. So a copy under any other name is drift to rename. Coverage output is a build artifact, so `.gitignore` excludes it. The C# invocation runs under **Microsoft.Testing.Platform**, and the runner declaration, package references, and version floor an MTP-based test project needs are `CODESTYLE.md`'s .NET side. The Python invocation needs **`pytest-cov`** and a coverage selector, which are `CODESTYLE.md`'s Python side. A Python directory declared in the validator's `python-directories` input owes a `tests/` suite whatever its profile, so the validator fails one that has none. N/A for a repo carrying no tests for that type. *Prevents: coverage silently going unreported, and a coverage regression blocking an unrelated pull request.* - **D1.7 A built NuGet package is consumed before it publishes.** Input: a repo whose `build-nuget` job runs the hub's default leaf, in a smoke run or a publish run alike. Output: after the leaf packs, the job restores, builds, and runs a throwaway console project against that exact `.nupkg`. It does so once per target framework the project declares. Each consumer lives outside the checkout, so the caller's `global.json` and `Directory.Build.props` do not apply. Its `nuget.config` resolves the package ID, and the ID of each sibling package in the folder holding the build output, only from that folder. Every other ID resolves from nuget.org. Its package cache is its own, so neither a cached nor a published copy can stand in for the artifact under test. The consumer loads the package assembly and calls `GetExportedTypes()`. The check asserts from `obj/project.assets.json` that the package resolved from the `lib//` folder of the consumer's own framework. It also asserts that the loaded assembly's `TargetFrameworkAttribute` matches that folder. A `netstandard` framework is consumed under the SDK line `global.json` selects, or the newest declared line where there is none. It is asserted against the folder it resolved. A framework the check does not consume is reported skipped. Examples are .NET Framework, `netcoreapp3.1`, and a platform-specific `netX.Y-windows`. The attribute row of a `netstandard` consumer resolving such a folder is skipped too. Four static assertions join them. The package's `lib//` folders equal the declared frameworks. The nuspec `` equals the build version. The nuspec holds a dependency group per framework. A symbol package exists where the project enables symbols. Every declared `netX.Y` and `netstandard` framework is consumed and reported with one summary row per assertion. A failed step ends that framework's rows rather than the run. The job fails at the end if any failed. The check covers a library package, whose assemblies sit under `lib//`. The check uploads nothing, so it honors D1.3. It runs inside the build job, so a failure blocks the publish job that `needs:` that build. A caller's own `build-nuget` hook replaces the whole leaf and is outside the check. A caller's own `.github/actions/package-consume/action.yml` runs once after the default check. It receives the declared frameworks as JSON beside the package ID, version, and package folder. *Prevents: a defect that exists only in the packed form shipping. One example is one target framework's assembly packed under every `lib//` folder while the tests, which reach the library through a project reference, stay green.* - **D1.8 A built PyPI package is consumed before it publishes.** Input: a repo whose `build-pypi` job runs the hub's default leaf, in a smoke run or a publish run alike. Output: after the leaf builds, the job installs the wheel and, separately, the sdist into a fresh `uv venv`. It does so for each line of the `python-versions` input of `build-release-task.yml`. Empty runs the one line the root `.python-version` selects. Where there is none it runs the hub's fallback line. A caller that sets `python-versions` for both `validate-task.yml` and `build-release-task.yml` passes the same value to each. So the lines its tests run under are the lines its artifact is consumed under. Each environment lives outside the checkout. It installs the artifact, then the project's locked dependency groups from `uv.lock` without the project itself. The check asserts that `importlib.metadata` reports the version the leaf computed. It also asserts that every top-level name the installed distribution provides imports from the environment's site-packages, not the source tree. A distribution providing none, such as one of scripts only, reports that row skipped. It then runs the caller's `tests/` folder against the installed copy with pytest in `importlib` import mode. That run has the source tree off `sys.path` and the project's `pythonpath` setting cleared. Its working directory is outside the project. So the caller's suite must not read a path relative to the project root, or a tool setting read from the working directory. It must import a sibling helper as part of a package. The project directory holds its own `uv.lock`. A project with no `tests/` folder, or a run collecting no tests, is reported skipped rather than passed. Every line and artifact reports one summary row per assertion. A failed environment, install, or metadata read ends that artifact's rows rather than the run. The job fails at the end if any failed. The check uploads nothing, so it honors D1.3. It runs inside the build job, so a failure blocks the publish job that `needs:` that build. A caller's own `build-pypi` hook replaces the whole leaf and is outside the check. *Prevents: a defect that exists only in the built form shipping. One example is a module left out of the wheel while the tests, which import it from the source tree, stay green.* +- **D1.9 Each declared test line runs as its own named unit-test leg.** Input: a repo declaring .NET lines in `dotnet-versions` of `validate-task.yml`, Python lines in `python-versions`, or both. Output: each declared .NET line runs as a `Unit test job (.NET X.Y)` leg running `dotnet test --framework netX.Y` under that line's runtime. Each declared Python line runs as a `Unit test job (Python X.Y)` leg, or as the caller's named `test-matrix` legs where it sets one. A caller declaring neither runs the one line each of `global.json` and `.python-version` selects. The hub's fallback line stands in where a file is absent. The .NET legs run only where a `*Tests*.csproj` exists. The Python legs run only where a Python directory resolves. So a repo holding one kind reports no leg of the other. Each leg uploads its own coverage report, and the .NET upload carries a per-line flag beside `dotnet`. A failing leg does not cancel its siblings. *Prevents: a failing target framework or interpreter hiding inside a combined run naming none of them. A .NET-only repo reporting a Python line it never ran is the other.* ### D2 - Input/State Validation at Entry diff --git a/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/test-methodology.md b/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/test-methodology.md index 6381fc559..4136c0f86 100644 --- a/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/test-methodology.md +++ b/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/test-methodology.md @@ -18,6 +18,8 @@ D1.7 is read in the build job. A step after the default leaf plans the declared D1.8 is read in the build job. A step after the default leaf runs the consume check. It receives the build's computed version and the `python-versions` list. Empty becomes the one line the root `.python-version` selects, or the hub's fallback line where there is none. It uploads nothing. +D1.9 is read in the validate task's job list. The `Build test matrix job` outputs one matrix per kind, and each unit-test job's `matrix` reads its output. The .NET job's `dotnet test` carries `--framework` for its matrix line, and the Python job holds no .NET step. Each job's `if:` reads the output that says its kind exists. + Cite what each verdict rests on. That is `file:line` for a file in the audited repo. It is the evidence's own name where a setting, a ruleset, or a secret name rather than a file is the evidence. Where the guarantee binds a workflow or composite action the audited repo only reaches, it is `/@` plus the `file:line` in that repo. The callee is read at the SHA the caller pins. An **N/A** verdict names the absent construct instead, there being no line to cite. ### 5B. End-to-End Trace Scenarios (No Execution, Deterministic from the YAML) diff --git a/.github/actions/dotnet-sdk/action.yml b/.github/actions/dotnet-sdk/action.yml index 5237f573c..4e00d8554 100644 --- a/.github/actions/dotnet-sdk/action.yml +++ b/.github/actions/dotnet-sdk/action.yml @@ -16,6 +16,11 @@ inputs: required: false default: 'true' +outputs: + lines: + description: JSON array of the X.Y lines the caller's tests run under, the versions input where set, else the one line global.json selects, else the fallback line as X.0. + value: ${{ steps.sdk-line.outputs.lines }} + runs: using: composite steps: @@ -68,6 +73,16 @@ runs: sdk = document.get("sdk") selected = isinstance(sdk, dict) and isinstance(sdk.get("version"), str) extra = lines + # The lines a caller tests under, one dotnet test leg each, are the entries it names, else the one line global.json selects, else the fallback. + reported = lines + if not lines and selected: + line = re.match(r"[0-9]+\.[0-9]+", sdk["version"]) + if line is None: + print("::error::The global.json sdk.version must start with an X.Y line, such as 10.0.100.") + sys.exit(1) + reported = [line.group(0)] + elif not lines: + reported = [fallback.replace(".x", ".0")] if selected and lines: line = re.match(r"[0-9]+\.[0-9]+", sdk["version"]) if line is None or lines[0] != line.group(0): @@ -75,6 +90,7 @@ runs: sys.exit(1) extra = lines[1:] with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as output: + output.write("lines=" + json.dumps(reported) + "\n") if selected: output.write("global-json-file=global.json\n") if extra: diff --git a/.github/actions/validate-default/action.yml b/.github/actions/validate-default/action.yml index 7727711c4..ff3b20bc9 100644 --- a/.github/actions/validate-default/action.yml +++ b/.github/actions/validate-default/action.yml @@ -1,7 +1,7 @@ # The hub default for the validate hook, used when a caller carries no .github/actions/validate/action.yml of its own. # A repo with no domain checks of its own has nothing for this hook to run. # These domain checks include an ESPHome compile, a Hugo build, a KiCad ERC, codegen drift, and PowerShell tests. -# The fleet doc-lint block plus the generic unit-test job already cover everything else validate-task.yml checks. +# The fleet doc-lint block plus the generic unit-test jobs already cover everything else validate-task.yml checks. name: Validate repository (default) description: No-op default for the validate hook. diff --git a/.github/skills/dotnet-codestyle/SKILL.md b/.github/skills/dotnet-codestyle/SKILL.md index 873b071fe..a26a19ae0 100644 --- a/.github/skills/dotnet-codestyle/SKILL.md +++ b/.github/skills/dotnet-codestyle/SKILL.md @@ -127,9 +127,9 @@ Shared MSBuild configuration is centralized at the repository root, never duplic sets a singular `TargetFramework`, the multi-targeted `.csproj` clears it, since a singular value wins and builds one framework only. Its test projects run each framework under that framework's own runtime. So the repository passes the hub's `validate-task.yml` a `dotnet-versions` input - naming every line, the `global.json` line first, such as `'["11.0", "10.0"]'`. That installs - each line beside the selected one in the one unit-test job. An entry leading with another line - fails the run. + naming every line, the `global.json` line first, such as `'["11.0", "10.0"]'`. Each line then + runs as its own unit-test leg, with every line installed beside the selected one. An entry + leading with another line fails the run. A developer host now needs a release SDK on the repository's line, 10.0.x for the fleet default today. A host holding only another major, or only a 10.0 preview, fails with a clear error. It diff --git a/.github/skills/workflow-ci-contract/references/d-guarantees.md b/.github/skills/workflow-ci-contract/references/d-guarantees.md index 327dd5149..f7e3097b7 100644 --- a/.github/skills/workflow-ci-contract/references/d-guarantees.md +++ b/.github/skills/workflow-ci-contract/references/d-guarantees.md @@ -11,13 +11,14 @@ The required behaviors, organized by domain. Each is a **MUST**, and its `Output ### D1 - PR Fast-Feedback (Smoke) - **D1.1 Only changed targets build.** Input: a PR touching some targets. Output: the paths-filter marks exactly those targets and only their smoke builds run. Unchanged targets skip. A repo's own targets MUST each have a filter entry, so a touched target is never silently skipped. That entry lists paths rather than negating them, so a change matching no entry marks nothing and every smoke build skips. *Prevents: rebuilding everything, and a changed target slipping through unbuilt.* -- **D1.2 A validation job always runs.** Input: any PR. Output: a validation job runs unconditionally and the aggregator `needs:` it. That job is the caller's own job reaching the reusable validator, named `validate` in every shipped stub. That name is what the aggregator's `needs:` carries. The validator's internal jobs (`test-matrix`, `lint`, `unit-test` and `validate` in the hub's `validate-task.yml`) are not addressable from a caller. So a `validate` in a caller's `needs:` list always names the caller's own job, never the validator's internal one. The validator detects the tree rather than the repo's language, so a non-.NET repo calls the same one rather than replacing it. It runs the doc and repo gates everywhere, and the `dotnet test` path only where a `*Tests*.csproj` project exists. It runs the Python path in each directory the caller declares in its `python-directories` input. Where the caller declares none and a root `pyproject.toml` is tracked, it runs that path at the root instead. At that undeclared root the test leg runs only where a `tests/` suite sits beside a `uv.lock` or `requirements*.txt`. A declared directory without `tests/`, by contrast, fails (D1.6). The declaration rather than discovery decides what is gated, since a stray or vendored `.py` file would otherwise change the gate silently. The validator warns about a tracked `.py` file no declared directory covers. It checks out the triggering commit, `github.sha`, with no `ref` input. It needs none, because a reusable workflow reads its caller's `github` context, so a publisher's call validates the same commit its publish job pins. A repo whose tests take another shape can run them from its own `.github/actions/validate/action.yml` hook, which the validator runs where that file exists. That hook receives no secret, so a repo whose other-shape tests owe D1.6's coverage upload is one whose validation the validator cannot express. A repo whose validation it cannot express **replaces** the call (not deletes it) with its own validator and re-points the aggregator's `needs:` to the replacement. `smoke-build` `needs:` the `changes` job rather than the validation job, so no second `needs:` moves with it. *Prevents: a PR merging with no validation, or a dangling `needs:` that stops the whole workflow from loading.* +- **D1.2 A validation job always runs.** Input: any PR. Output: a validation job runs unconditionally and the aggregator `needs:` it. That job is the caller's own job reaching the reusable validator, named `validate` in every shipped stub. That name is what the aggregator's `needs:` carries. The validator's internal jobs (`test-matrix`, `lint`, `unit-test`, `unit-test-dotnet` and `validate` in the hub's `validate-task.yml`) are not addressable from a caller. So a `validate` in a caller's `needs:` list always names the caller's own job, never the validator's internal one. The validator detects the tree rather than the repo's language, so a non-.NET repo calls the same one rather than replacing it. It runs the doc and repo gates everywhere, and the `dotnet test` path only where a `*Tests*.csproj` project exists. It runs the Python path in each directory the caller declares in its `python-directories` input. Where the caller declares none and a root `pyproject.toml` is tracked, it runs that path at the root instead. At that undeclared root the test leg runs only where a `tests/` suite sits beside a `uv.lock` or `requirements*.txt`. A declared directory without `tests/`, by contrast, fails (D1.6). The declaration rather than discovery decides what is gated, since a stray or vendored `.py` file would otherwise change the gate silently. The validator warns about a tracked `.py` file no declared directory covers. It checks out the triggering commit, `github.sha`, with no `ref` input. It needs none, because a reusable workflow reads its caller's `github` context, so a publisher's call validates the same commit its publish job pins. A repo whose tests take another shape can run them from its own `.github/actions/validate/action.yml` hook, which the validator runs where that file exists. That hook receives no secret, so a repo whose other-shape tests owe D1.6's coverage upload is one whose validation the validator cannot express. A repo whose validation it cannot express **replaces** the call (not deletes it) with its own validator and re-points the aggregator's `needs:` to the replacement. `smoke-build` `needs:` the `changes` job rather than the validation job, so no second `needs:` moves with it. *Prevents: a PR merging with no validation, or a dangling `needs:` that stops the whole workflow from loading.* - **D1.3 Smoke never publishes and never uploads.** Input: `smoke: true`. Output: full compile/lint/test, but no registry/image push, no release, and **no** artifact uploads. Every `upload-artifact`, including any aggregation job, is gated on smoke being false. That gate is written `!inputs.smoke` at the workflow layer and `inputs.smoke != 'true'` in a composite action, whose inputs are strings. *Prevents: a PR publishing, and orphaned artifacts churning the storage quota.* - **D1.4 Workflow-file changes are not smoke-built.** Input: a PR changing only `.github/workflows/**`. Output: the paths-filter marks no target, so smoke-build skips. An inclusion list satisfying D1.1 reaches this by leaving workflow paths out of every target's entry. *Implication: a workflow-only change is not smoke-built, but actionlint still validates it in CI.* - **D1.5 One required aggregator gates merge.** Input: any PR. Output: a single aggregator job must **succeed**. It must run under `if: always()`, so a failed or skipped dependency cannot skip the gate itself. It must also `needs:` the validation job, and the `changes` and `smoke-build` jobs too wherever the repo has a smoke build. It must treat a **skipped** smoke build as pass, and **block** on `failure`/`cancelled`. Its name is ruleset-bound: the job `name:` and the ruleset `context:` are the same string and MUST be renamed together, never independently. The workflow holding it MUST trigger on `pull_request`. A gate without a `pull_request` trigger never runs the validator's pull-request-only steps, the prose gate among them. A workflow any other event also triggers yields that name only when `github.event_name == 'pull_request'`, through an expression `name:`. Otherwise a dispatch or push run on a PR's head posts the required context without the PR run's gates. *Prevents: a paths-filter error letting a target-changing PR merge unbuilt.* - **D1.6 Coverage is reported to Codecov (C# and Python).** Input: a C# or Python repo that has tests for that type. Output: the validation job runs those tests under coverage collection, and a `codecov/codecov-action` step uploads the report. The collection is `dotnet test --coverage --coverage-output-format cobertura --results-directory ./coverage`, leaving `--coverage-output` unset so each test project writes its own report rather than overwriting a shared one. A bare call resolves one workspace from the working directory, so it fails at a root holding none or more than one. Unless the repository root holds exactly one solution or project, the hub's validator therefore runs the collection once per tracked `*Tests*.csproj` with `--project`. It names no solution in that case, since a solution holding no test project fails the run. Or it is `pytest --cov-report=xml` in a Python directory with its own `uv.lock` or `requirements*.txt`, whose own `pyproject.toml` selects what to measure. Or it is `coverage run -m unittest discover -s tests` then `coverage xml` in a `lint-only` one. The upload is **best-effort** (`continue-on-error` and/or `fail_ci_if_error: false`), so a Codecov outage or an absent token never reds the gate. Each leg **fails its test step when the run wrote no report**. The reason is that the best-effort upload reads a missing report exactly as it reads a healthy run. A second reason is that, on the Python leg, `--cov-report=xml` alone selects nothing to measure. The C# leg renames each report to `coverage-.cobertura.xml` before the upload step reads the directory, since `codecov-cli`'s own finder does not match the default name. A repo owning its validator rather than calling the hub's owes that rename itself. `CODECOV_TOKEN` lives in the repo's **actions** and **dependabot** secret stores. The token is in the second because a run triggered by a Dependabot pull request reads the Dependabot store. Without the token there, the upload would otherwise skip silently on every bot pull request. A caller reaching the reusable validator across repositories names the secret it passes (`secrets:` with `CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}`). It does so on its pull request path and its publisher path alike. That is because `secrets: inherit` is documented for a caller in the same organization or enterprise, which a personal account is not. A call by local path stays inside one repository, where the caller's own store is the one the callee reads. So `secrets: inherit` is available there instead of naming each secret. The repo ships a **`.codecov.yml`** at the repository root. It sets the project and patch statuses to **`informational: true`**, so a coverage delta never gates a pull request. A repo whose quality bar requires a threshold may turn that off. The same file excludes intentionally-untested, non-shipped code (an example or benchmark project) from the denominator via `ignore`. Codecov reads its configuration under several names, but `.codecov.yml` is the only one the fleet accepts. So a copy under any other name is drift to rename. Coverage output is a build artifact, so `.gitignore` excludes it. The C# invocation runs under **Microsoft.Testing.Platform**, and the runner declaration, package references, and version floor an MTP-based test project needs are `CODESTYLE.md`'s .NET side. The Python invocation needs **`pytest-cov`** and a coverage selector, which are `CODESTYLE.md`'s Python side. A Python directory declared in the validator's `python-directories` input owes a `tests/` suite whatever its profile, so the validator fails one that has none. N/A for a repo carrying no tests for that type. *Prevents: coverage silently going unreported, and a coverage regression blocking an unrelated pull request.* - **D1.7 A built NuGet package is consumed before it publishes.** Input: a repo whose `build-nuget` job runs the hub's default leaf, in a smoke run or a publish run alike. Output: after the leaf packs, the job restores, builds, and runs a throwaway console project against that exact `.nupkg`. It does so once per target framework the project declares. Each consumer lives outside the checkout, so the caller's `global.json` and `Directory.Build.props` do not apply. Its `nuget.config` resolves the package ID, and the ID of each sibling package in the folder holding the build output, only from that folder. Every other ID resolves from nuget.org. Its package cache is its own, so neither a cached nor a published copy can stand in for the artifact under test. The consumer loads the package assembly and calls `GetExportedTypes()`. The check asserts from `obj/project.assets.json` that the package resolved from the `lib//` folder of the consumer's own framework. It also asserts that the loaded assembly's `TargetFrameworkAttribute` matches that folder. A `netstandard` framework is consumed under the SDK line `global.json` selects, or the newest declared line where there is none. It is asserted against the folder it resolved. A framework the check does not consume is reported skipped. Examples are .NET Framework, `netcoreapp3.1`, and a platform-specific `netX.Y-windows`. The attribute row of a `netstandard` consumer resolving such a folder is skipped too. Four static assertions join them. The package's `lib//` folders equal the declared frameworks. The nuspec `` equals the build version. The nuspec holds a dependency group per framework. A symbol package exists where the project enables symbols. Every declared `netX.Y` and `netstandard` framework is consumed and reported with one summary row per assertion. A failed step ends that framework's rows rather than the run. The job fails at the end if any failed. The check covers a library package, whose assemblies sit under `lib//`. The check uploads nothing, so it honors D1.3. It runs inside the build job, so a failure blocks the publish job that `needs:` that build. A caller's own `build-nuget` hook replaces the whole leaf and is outside the check. A caller's own `.github/actions/package-consume/action.yml` runs once after the default check. It receives the declared frameworks as JSON beside the package ID, version, and package folder. *Prevents: a defect that exists only in the packed form shipping. One example is one target framework's assembly packed under every `lib//` folder while the tests, which reach the library through a project reference, stay green.* - **D1.8 A built PyPI package is consumed before it publishes.** Input: a repo whose `build-pypi` job runs the hub's default leaf, in a smoke run or a publish run alike. Output: after the leaf builds, the job installs the wheel and, separately, the sdist into a fresh `uv venv`. It does so for each line of the `python-versions` input of `build-release-task.yml`. Empty runs the one line the root `.python-version` selects. Where there is none it runs the hub's fallback line. A caller that sets `python-versions` for both `validate-task.yml` and `build-release-task.yml` passes the same value to each. So the lines its tests run under are the lines its artifact is consumed under. Each environment lives outside the checkout. It installs the artifact, then the project's locked dependency groups from `uv.lock` without the project itself. The check asserts that `importlib.metadata` reports the version the leaf computed. It also asserts that every top-level name the installed distribution provides imports from the environment's site-packages, not the source tree. A distribution providing none, such as one of scripts only, reports that row skipped. It then runs the caller's `tests/` folder against the installed copy with pytest in `importlib` import mode. That run has the source tree off `sys.path` and the project's `pythonpath` setting cleared. Its working directory is outside the project. So the caller's suite must not read a path relative to the project root, or a tool setting read from the working directory. It must import a sibling helper as part of a package. The project directory holds its own `uv.lock`. A project with no `tests/` folder, or a run collecting no tests, is reported skipped rather than passed. Every line and artifact reports one summary row per assertion. A failed environment, install, or metadata read ends that artifact's rows rather than the run. The job fails at the end if any failed. The check uploads nothing, so it honors D1.3. It runs inside the build job, so a failure blocks the publish job that `needs:` that build. A caller's own `build-pypi` hook replaces the whole leaf and is outside the check. *Prevents: a defect that exists only in the built form shipping. One example is a module left out of the wheel while the tests, which import it from the source tree, stay green.* +- **D1.9 Each declared test line runs as its own named unit-test leg.** Input: a repo declaring .NET lines in `dotnet-versions` of `validate-task.yml`, Python lines in `python-versions`, or both. Output: each declared .NET line runs as a `Unit test job (.NET X.Y)` leg running `dotnet test --framework netX.Y` under that line's runtime. Each declared Python line runs as a `Unit test job (Python X.Y)` leg, or as the caller's named `test-matrix` legs where it sets one. A caller declaring neither runs the one line each of `global.json` and `.python-version` selects. The hub's fallback line stands in where a file is absent. The .NET legs run only where a `*Tests*.csproj` exists. The Python legs run only where a Python directory resolves. So a repo holding one kind reports no leg of the other. Each leg uploads its own coverage report, and the .NET upload carries a per-line flag beside `dotnet`. A failing leg does not cancel its siblings. *Prevents: a failing target framework or interpreter hiding inside a combined run naming none of them. A .NET-only repo reporting a Python line it never ran is the other.* ### D2 - Input/State Validation at Entry diff --git a/.github/skills/workflow-ci-contract/references/test-methodology.md b/.github/skills/workflow-ci-contract/references/test-methodology.md index 6381fc559..4136c0f86 100644 --- a/.github/skills/workflow-ci-contract/references/test-methodology.md +++ b/.github/skills/workflow-ci-contract/references/test-methodology.md @@ -18,6 +18,8 @@ D1.7 is read in the build job. A step after the default leaf plans the declared D1.8 is read in the build job. A step after the default leaf runs the consume check. It receives the build's computed version and the `python-versions` list. Empty becomes the one line the root `.python-version` selects, or the hub's fallback line where there is none. It uploads nothing. +D1.9 is read in the validate task's job list. The `Build test matrix job` outputs one matrix per kind, and each unit-test job's `matrix` reads its output. The .NET job's `dotnet test` carries `--framework` for its matrix line, and the Python job holds no .NET step. Each job's `if:` reads the output that says its kind exists. + Cite what each verdict rests on. That is `file:line` for a file in the audited repo. It is the evidence's own name where a setting, a ruleset, or a secret name rather than a file is the evidence. Where the guarantee binds a workflow or composite action the audited repo only reaches, it is `/@` plus the `file:line` in that repo. The callee is read at the SHA the caller pins. An **N/A** verdict names the absent construct instead, there being no line to cite. ### 5B. End-to-End Trace Scenarios (No Execution, Deterministic from the YAML) diff --git a/.github/workflows/validate-task.yml b/.github/workflows/validate-task.yml index 54985abb4..4ffcfcb0d 100644 --- a/.github/workflows/validate-task.yml +++ b/.github/workflows/validate-task.yml @@ -28,7 +28,7 @@ on: type: string default: '' dotnet-versions: - description: JSON array of the X.Y .NET lines a multi-targeted caller's projects build, one per target framework, for example ["11.0", "10.0"]. The first entry is the line the root global.json selects, which builds every target framework, and a first entry differing from it fails the run. Every listed line is installed in the one unit-test job, whose dotnet test runs each target framework under its own runtime, so it adds no matrix leg. Quote each entry, since an unquoted one is a JSON number rather than a line. Empty installs the one line global.json selects, or the hub's fallback line where it carries none. + description: JSON array of the X.Y .NET lines a multi-targeted caller's projects build, one per target framework, for example ["11.0", "10.0"]. The first entry is the line the root global.json selects, which builds every target framework, and a first entry differing from it fails the run. Every listed line is installed in each .NET leg, and each entry is its own Unit test job (.NET X.Y) leg running dotnet test --framework netX.Y under that line's runtime. Quote each entry, since an unquoted one is a JSON number rather than a line. Empty installs the one line global.json selects, or the hub's fallback line where it carries none. required: false type: string default: '' @@ -70,17 +70,18 @@ jobs: matrix: ${{ steps.build.outputs.matrix }} legs: ${{ steps.check.outputs.legs }} versions: ${{ steps.build.outputs.versions }} + dotnet-matrix: ${{ steps.build.outputs.dotnet-matrix }} + dotnet-tests: ${{ steps.build.outputs.dotnet-tests }} + python-any: ${{ steps.python-directories.outputs.any }} steps: + # The whole tree is read, since the job reports whether a test project and a Python directory exist at all. - name: Checkout code step - if: ${{ inputs.test-matrix-file != '' || inputs.python-versions == '' || inputs.dotnet-versions != '' }} uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - sparse-checkout: ${{ inputs.test-matrix-file == '' && fromJSON('"/.python-version\n/global.json"') || '' }} - sparse-checkout-cone-mode: false - # This job cannot tell whether the caller holds Python, so the lint job, which can, warns of a fallback instead. + # The lint job warns of a fallback line, so this job selects it without repeating the warning. - name: Select Python version step id: python-version if: ${{ inputs.python-versions == '' }} @@ -88,13 +89,21 @@ jobs: with: warn: 'false' + # The action validates the input and reports the lines the .NET legs run, installing nothing here. - name: Validate dotnet-versions input step - if: ${{ inputs.dotnet-versions != '' }} + id: dotnet-sdk uses: $/.github/actions/dotnet-sdk with: versions: ${{ inputs.dotnet-versions }} install: 'false' + # The job-level condition of the Python job cannot read the tree, so the resolved answer travels as an output. + - name: Resolve Python directories step + id: python-directories + uses: $/.github/actions/python-directories + with: + directories: ${{ inputs.python-directories }} + # Either input lands in one file here, so the check below and the build step read the same bytes whichever input the caller set. - name: Validate test-matrix input step id: check @@ -172,6 +181,8 @@ jobs: env: LEGS: ${{ steps.check.outputs.legs }} PYTHON_VERSIONS: ${{ inputs.python-versions || format('["{0}"]', steps.python-version.outputs.version) }} + DOTNET_LINES: ${{ steps.dotnet-sdk.outputs.lines }} + DOTNET_TESTS: ${{ hashFiles('**/*Tests*.csproj') != '' }} run: | set -Eeuo pipefail if [[ "$LEGS" == "true" ]]; then @@ -179,8 +190,12 @@ jobs: else matrix=$(jq -c --argjson versions "$PYTHON_VERSIONS" -n '{"python-version": $versions}') fi - echo "matrix=$matrix" >> "$GITHUB_OUTPUT" - echo "versions=$(jq -c . <<< "$PYTHON_VERSIONS")" >> "$GITHUB_OUTPUT" + { + echo "matrix=$matrix" + echo "versions=$(jq -c . <<< "$PYTHON_VERSIONS")" + echo "dotnet-matrix=$(jq -c -n --argjson lines "$DOTNET_LINES" '{"dotnet-version": $lines}')" + echo "dotnet-tests=$DOTNET_TESTS" + } >> "$GITHUB_OUTPUT" lint: name: Lint sources job @@ -832,23 +847,16 @@ jobs: echo "The branching-and-release-model skill's references/branch-protection-and-promotion.md states the cut." exit 1 - # No job-level if: here, since GitHub Actions does not evaluate hashFiles in a job condition, only a step one. - # Every step below carries its own guard instead, a tree-detection one on the .NET half and the resolved Python directories on the Python half. - # A caller with no *Tests*.csproj and no Python directory runs every guard false. - # The job reports success having done nothing, which is the clean skip this job promises. - # See D1.6 for a declared Python directory with no tests/. - # See D1.2 for the undeclared root. + # A job-level if: cannot read the tree, so the Python directories are resolved in the test-matrix job and read here as an output. + # A .NET-only caller therefore reports no Python leg at all. # The matrix dimension is the interpreter, or the test-matrix leg when either matrix input is set. # A caller naming neither runs the single leg this job ran before the input existed. - # A python-versions leg names an interpreter whether or not one ran. - # So a .NET-only caller reports a Python version its Python steps never used. - # A caller naming several also repeats this job's .NET half once per leg. - # That spends runner minutes and re-uploads an identical report rather than measuring anything new. - # Splitting the two halves into jobs of their own is what that costs. - # The first repo to carry both a .NET test project and more than one interpreter owes it. + # See D1.6 for a declared Python directory with no tests/. + # See D1.2 for the undeclared root. unit-test: name: Unit test job (${{ matrix.label || format('Python {0}', matrix.python-version) }}) needs: test-matrix + if: ${{ needs.test-matrix.outputs.python-any == 'true' }} runs-on: ubuntu-latest permissions: contents: read @@ -875,68 +883,6 @@ jobs: exit 1 fi - # A system tool a .NET test shells out to must reach the runner before the tests, which no later hook can do. - - name: Run caller pre-test hook step - if: hashFiles('**/*Tests*.csproj') != '' && hashFiles('.github/actions/pre-test/action.yml') != '' - uses: ./.github/actions/pre-test - - # The caller's global.json selects the SDK line, or the dotnet-sdk action's fallback line where it carries none yet. - - name: Setup .NET SDK step - if: hashFiles('**/*Tests*.csproj') != '' - uses: $/.github/actions/dotnet-sdk - with: - versions: ${{ inputs.dotnet-versions }} - - - name: Resolve .NET workspaces step - id: dotnet - if: hashFiles('**/*Tests*.csproj') != '' - uses: $/.github/actions/dotnet-workspaces - with: - projects: ':(glob)**/*Tests*.csproj' - - # --coverage-output stays unset because pinning one filename gives every test project in the solution the same path, and the last to finish overwrites the rest. - # The default .cobertura.xml written instead is a name codecov-cli's finder does not match. - # Each report is therefore prefixed rather than renamed, keeping the guid that makes it unique. - - name: Run unit tests step - if: hashFiles('**/*Tests*.csproj') != '' - env: - WORKSPACES: ${{ steps.dotnet.outputs.workspaces }} - run: | - set -Eeuo pipefail - rm -rf ./coverage - # A solution holding no test project fails dotnet test with no test projects found, so the tests are named one project at a time. - if [ -z "$WORKSPACES" ]; then - dotnet test --coverage --coverage-output-format cobertura --results-directory ./coverage - fi - while IFS= read -r workspace; do - [ -n "$workspace" ] || continue - dotnet test --project "$workspace" --coverage --coverage-output-format cobertura --results-directory ./coverage < /dev/null - done <<< "$WORKSPACES" - written=0 - for report in ./coverage/*.cobertura.xml; do - [ -e "$report" ] || continue - renamed="./coverage/coverage-$(basename "$report")" - mv "$report" "$renamed" - if [ -s "$renamed" ]; then - written=1 - fi - done - if [ "$written" -eq 0 ]; then - echo "::error::This run wrote no non-empty Cobertura report under ./coverage. Reference Microsoft.Testing.Extensions.CodeCoverage from each test project, per CODESTYLE.md's .NET side." - exit 1 - fi - - # Report-only: fail_ci_if_error is false so a Codecov hiccup or an absent token never fails the gate. - - name: Upload coverage to Codecov step - if: hashFiles('**/*Tests*.csproj') != '' - uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1 - with: - directory: ./coverage - flags: dotnet - fail_ci_if_error: false - env: - CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} - - name: Resolve Python directories step id: python uses: $/.github/actions/python-directories @@ -1095,6 +1041,90 @@ jobs: flags: python-${{ matrix.label || matrix.python-version }} fail_ci_if_error: false + # One leg per .NET line, so a failing target framework names itself rather than hiding in a combined run. + # The job-level if: reads the test-matrix job's tree detection, since a job condition cannot call hashFiles. + unit-test-dotnet: + name: Unit test job (.NET ${{ matrix.dotnet-version }}) + needs: test-matrix + if: ${{ needs.test-matrix.outputs.dotnet-tests == 'true' }} + runs-on: ubuntu-latest + permissions: + contents: read + strategy: + # A failing framework must not cancel its siblings, since which of them fail is the whole point of running more than one. + fail-fast: false + matrix: ${{ fromJSON(needs.test-matrix.outputs.dotnet-matrix) }} + + steps: + + - name: Checkout code step + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + # A system tool a .NET test shells out to must reach the runner before the tests, which no later hook can do. + - name: Run caller pre-test hook step + if: hashFiles('**/*Tests*.csproj') != '' && hashFiles('.github/actions/pre-test/action.yml') != '' + uses: ./.github/actions/pre-test + + # The caller's global.json selects the SDK line, or the dotnet-sdk action's fallback line where it carries none yet. + - name: Setup .NET SDK step + if: hashFiles('**/*Tests*.csproj') != '' + uses: $/.github/actions/dotnet-sdk + with: + versions: ${{ inputs.dotnet-versions }} + + - name: Resolve .NET workspaces step + id: dotnet + if: hashFiles('**/*Tests*.csproj') != '' + uses: $/.github/actions/dotnet-workspaces + with: + projects: ':(glob)**/*Tests*.csproj' + + # --coverage-output stays unset because pinning one filename gives every test project in the solution the same path, and the last to finish overwrites the rest. + # The default .cobertura.xml written instead is a name codecov-cli's finder does not match. + # Each report is therefore prefixed rather than renamed, keeping the guid that makes it unique. + - name: Run unit tests step + if: hashFiles('**/*Tests*.csproj') != '' + env: + WORKSPACES: ${{ steps.dotnet.outputs.workspaces }} + DOTNET_VERSION: ${{ matrix.dotnet-version }} + run: | + set -Eeuo pipefail + rm -rf ./coverage + # A solution holding no test project fails dotnet test with no test projects found, so the tests are named one project at a time. + if [ -z "$WORKSPACES" ]; then + dotnet test --framework "net$DOTNET_VERSION" --coverage --coverage-output-format cobertura --results-directory ./coverage + fi + while IFS= read -r workspace; do + [ -n "$workspace" ] || continue + dotnet test --framework "net$DOTNET_VERSION" --project "$workspace" --coverage --coverage-output-format cobertura --results-directory ./coverage < /dev/null + done <<< "$WORKSPACES" + written=0 + for report in ./coverage/*.cobertura.xml; do + [ -e "$report" ] || continue + renamed="./coverage/coverage-$(basename "$report")" + mv "$report" "$renamed" + if [ -s "$renamed" ]; then + written=1 + fi + done + if [ "$written" -eq 0 ]; then + echo "::error::This run wrote no non-empty Cobertura report under ./coverage. Reference Microsoft.Testing.Extensions.CodeCoverage from each test project, per CODESTYLE.md's .NET side." + exit 1 + fi + + # Report-only: fail_ci_if_error is false so a Codecov hiccup or an absent token never fails the gate. + - name: Upload coverage to Codecov step + if: hashFiles('**/*Tests*.csproj') != '' + uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1 + with: + directory: ./coverage + flags: dotnet,dotnet-${{ matrix.dotnet-version }} + fail_ci_if_error: false + env: + CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} + validate: name: Validate repository job runs-on: ubuntu-latest diff --git a/WORKFLOW.md b/WORKFLOW.md index b43759e9a..4eadedb23 100644 --- a/WORKFLOW.md +++ b/WORKFLOW.md @@ -140,13 +140,14 @@ The required behaviors, organized by domain. Each is a **MUST**, and its `Output ### D1 - PR Fast-Feedback (Smoke) - **D1.1 Only changed targets build.** Input: a PR touching some targets. Output: the paths-filter marks exactly those targets and only their smoke builds run. Unchanged targets skip. A repo's own targets MUST each have a filter entry, so a touched target is never silently skipped. That entry lists paths rather than negating them, so a change matching no entry marks nothing and every smoke build skips. *Prevents: rebuilding everything, and a changed target slipping through unbuilt.* -- **D1.2 A validation job always runs.** Input: any PR. Output: a validation job runs unconditionally and the aggregator `needs:` it. That job is the caller's own job reaching the reusable validator, named `validate` in every shipped stub. That name is what the aggregator's `needs:` carries. The validator's internal jobs (`test-matrix`, `lint`, `unit-test` and `validate` in the hub's `validate-task.yml`) are not addressable from a caller. So a `validate` in a caller's `needs:` list always names the caller's own job, never the validator's internal one. The validator detects the tree rather than the repo's language, so a non-.NET repo calls the same one rather than replacing it. It runs the doc and repo gates everywhere, and the `dotnet test` path only where a `*Tests*.csproj` project exists. It runs the Python path in each directory the caller declares in its `python-directories` input. Where the caller declares none and a root `pyproject.toml` is tracked, it runs that path at the root instead. At that undeclared root the test leg runs only where a `tests/` suite sits beside a `uv.lock` or `requirements*.txt`. A declared directory without `tests/`, by contrast, fails (D1.6). The declaration rather than discovery decides what is gated, since a stray or vendored `.py` file would otherwise change the gate silently. The validator warns about a tracked `.py` file no declared directory covers. It checks out the triggering commit, `github.sha`, with no `ref` input. It needs none, because a reusable workflow reads its caller's `github` context, so a publisher's call validates the same commit its publish job pins. A repo whose tests take another shape can run them from its own `.github/actions/validate/action.yml` hook, which the validator runs where that file exists. That hook receives no secret, so a repo whose other-shape tests owe D1.6's coverage upload is one whose validation the validator cannot express. A repo whose validation it cannot express **replaces** the call (not deletes it) with its own validator and re-points the aggregator's `needs:` to the replacement. `smoke-build` `needs:` the `changes` job rather than the validation job, so no second `needs:` moves with it. *Prevents: a PR merging with no validation, or a dangling `needs:` that stops the whole workflow from loading.* +- **D1.2 A validation job always runs.** Input: any PR. Output: a validation job runs unconditionally and the aggregator `needs:` it. That job is the caller's own job reaching the reusable validator, named `validate` in every shipped stub. That name is what the aggregator's `needs:` carries. The validator's internal jobs (`test-matrix`, `lint`, `unit-test`, `unit-test-dotnet` and `validate` in the hub's `validate-task.yml`) are not addressable from a caller. So a `validate` in a caller's `needs:` list always names the caller's own job, never the validator's internal one. The validator detects the tree rather than the repo's language, so a non-.NET repo calls the same one rather than replacing it. It runs the doc and repo gates everywhere, and the `dotnet test` path only where a `*Tests*.csproj` project exists. It runs the Python path in each directory the caller declares in its `python-directories` input. Where the caller declares none and a root `pyproject.toml` is tracked, it runs that path at the root instead. At that undeclared root the test leg runs only where a `tests/` suite sits beside a `uv.lock` or `requirements*.txt`. A declared directory without `tests/`, by contrast, fails (D1.6). The declaration rather than discovery decides what is gated, since a stray or vendored `.py` file would otherwise change the gate silently. The validator warns about a tracked `.py` file no declared directory covers. It checks out the triggering commit, `github.sha`, with no `ref` input. It needs none, because a reusable workflow reads its caller's `github` context, so a publisher's call validates the same commit its publish job pins. A repo whose tests take another shape can run them from its own `.github/actions/validate/action.yml` hook, which the validator runs where that file exists. That hook receives no secret, so a repo whose other-shape tests owe D1.6's coverage upload is one whose validation the validator cannot express. A repo whose validation it cannot express **replaces** the call (not deletes it) with its own validator and re-points the aggregator's `needs:` to the replacement. `smoke-build` `needs:` the `changes` job rather than the validation job, so no second `needs:` moves with it. *Prevents: a PR merging with no validation, or a dangling `needs:` that stops the whole workflow from loading.* - **D1.3 Smoke never publishes and never uploads.** Input: `smoke: true`. Output: full compile/lint/test, but no registry/image push, no release, and **no** artifact uploads. Every `upload-artifact`, including any aggregation job, is gated on smoke being false. That gate is written `!inputs.smoke` at the workflow layer and `inputs.smoke != 'true'` in a composite action, whose inputs are strings. *Prevents: a PR publishing, and orphaned artifacts churning the storage quota.* - **D1.4 Workflow-file changes are not smoke-built.** Input: a PR changing only `.github/workflows/**`. Output: the paths-filter marks no target, so smoke-build skips. An inclusion list satisfying D1.1 reaches this by leaving workflow paths out of every target's entry. *Implication: a workflow-only change is not smoke-built, but actionlint still validates it in CI.* - **D1.5 One required aggregator gates merge.** Input: any PR. Output: a single aggregator job must **succeed**. It must run under `if: always()`, so a failed or skipped dependency cannot skip the gate itself. It must also `needs:` the validation job, and the `changes` and `smoke-build` jobs too wherever the repo has a smoke build. It must treat a **skipped** smoke build as pass, and **block** on `failure`/`cancelled`. Its name is ruleset-bound: the job `name:` and the ruleset `context:` are the same string and MUST be renamed together, never independently. The workflow holding it MUST trigger on `pull_request`. A gate without a `pull_request` trigger never runs the validator's pull-request-only steps, the prose gate among them. A workflow any other event also triggers yields that name only when `github.event_name == 'pull_request'`, through an expression `name:`. Otherwise a dispatch or push run on a PR's head posts the required context without the PR run's gates. *Prevents: a paths-filter error letting a target-changing PR merge unbuilt.* - **D1.6 Coverage is reported to Codecov (C# and Python).** Input: a C# or Python repo that has tests for that type. Output: the validation job runs those tests under coverage collection, and a `codecov/codecov-action` step uploads the report. The collection is `dotnet test --coverage --coverage-output-format cobertura --results-directory ./coverage`, leaving `--coverage-output` unset so each test project writes its own report rather than overwriting a shared one. A bare call resolves one workspace from the working directory, so it fails at a root holding none or more than one. Unless the repository root holds exactly one solution or project, the hub's validator therefore runs the collection once per tracked `*Tests*.csproj` with `--project`. It names no solution in that case, since a solution holding no test project fails the run. Or it is `pytest --cov-report=xml` in a Python directory with its own `uv.lock` or `requirements*.txt`, whose own `pyproject.toml` selects what to measure. Or it is `coverage run -m unittest discover -s tests` then `coverage xml` in a `lint-only` one. The upload is **best-effort** (`continue-on-error` and/or `fail_ci_if_error: false`), so a Codecov outage or an absent token never reds the gate. Each leg **fails its test step when the run wrote no report**. The reason is that the best-effort upload reads a missing report exactly as it reads a healthy run. A second reason is that, on the Python leg, `--cov-report=xml` alone selects nothing to measure. The C# leg renames each report to `coverage-.cobertura.xml` before the upload step reads the directory, since `codecov-cli`'s own finder does not match the default name. A repo owning its validator rather than calling the hub's owes that rename itself. `CODECOV_TOKEN` lives in the repo's **actions** and **dependabot** secret stores. The token is in the second because a run triggered by a Dependabot pull request reads the Dependabot store. Without the token there, the upload would otherwise skip silently on every bot pull request. A caller reaching the reusable validator across repositories names the secret it passes (`secrets:` with `CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}`). It does so on its pull request path and its publisher path alike. That is because `secrets: inherit` is documented for a caller in the same organization or enterprise, which a personal account is not. A call by local path stays inside one repository, where the caller's own store is the one the callee reads. So `secrets: inherit` is available there instead of naming each secret. The repo ships a **`.codecov.yml`** at the repository root. It sets the project and patch statuses to **`informational: true`**, so a coverage delta never gates a pull request. A repo whose quality bar requires a threshold may turn that off. The same file excludes intentionally-untested, non-shipped code (an example or benchmark project) from the denominator via `ignore`. Codecov reads its configuration under several names, but `.codecov.yml` is the only one the fleet accepts. So a copy under any other name is drift to rename. Coverage output is a build artifact, so `.gitignore` excludes it. The C# invocation runs under **Microsoft.Testing.Platform**, and the runner declaration, package references, and version floor an MTP-based test project needs are `CODESTYLE.md`'s .NET side. The Python invocation needs **`pytest-cov`** and a coverage selector, which are `CODESTYLE.md`'s Python side. A Python directory declared in the validator's `python-directories` input owes a `tests/` suite whatever its profile, so the validator fails one that has none. N/A for a repo carrying no tests for that type. *Prevents: coverage silently going unreported, and a coverage regression blocking an unrelated pull request.* - **D1.7 A built NuGet package is consumed before it publishes.** Input: a repo whose `build-nuget` job runs the hub's default leaf, in a smoke run or a publish run alike. Output: after the leaf packs, the job restores, builds, and runs a throwaway console project against that exact `.nupkg`. It does so once per target framework the project declares. Each consumer lives outside the checkout, so the caller's `global.json` and `Directory.Build.props` do not apply. Its `nuget.config` resolves the package ID, and the ID of each sibling package in the folder holding the build output, only from that folder. Every other ID resolves from nuget.org. Its package cache is its own, so neither a cached nor a published copy can stand in for the artifact under test. The consumer loads the package assembly and calls `GetExportedTypes()`. The check asserts from `obj/project.assets.json` that the package resolved from the `lib//` folder of the consumer's own framework. It also asserts that the loaded assembly's `TargetFrameworkAttribute` matches that folder. A `netstandard` framework is consumed under the SDK line `global.json` selects, or the newest declared line where there is none. It is asserted against the folder it resolved. A framework the check does not consume is reported skipped. Examples are .NET Framework, `netcoreapp3.1`, and a platform-specific `netX.Y-windows`. The attribute row of a `netstandard` consumer resolving such a folder is skipped too. Four static assertions join them. The package's `lib//` folders equal the declared frameworks. The nuspec `` equals the build version. The nuspec holds a dependency group per framework. A symbol package exists where the project enables symbols. Every declared `netX.Y` and `netstandard` framework is consumed and reported with one summary row per assertion. A failed step ends that framework's rows rather than the run. The job fails at the end if any failed. The check covers a library package, whose assemblies sit under `lib//`. The check uploads nothing, so it honors D1.3. It runs inside the build job, so a failure blocks the publish job that `needs:` that build. A caller's own `build-nuget` hook replaces the whole leaf and is outside the check. A caller's own `.github/actions/package-consume/action.yml` runs once after the default check. It receives the declared frameworks as JSON beside the package ID, version, and package folder. *Prevents: a defect that exists only in the packed form shipping. One example is one target framework's assembly packed under every `lib//` folder while the tests, which reach the library through a project reference, stay green.* - **D1.8 A built PyPI package is consumed before it publishes.** Input: a repo whose `build-pypi` job runs the hub's default leaf, in a smoke run or a publish run alike. Output: after the leaf builds, the job installs the wheel and, separately, the sdist into a fresh `uv venv`. It does so for each line of the `python-versions` input of `build-release-task.yml`. Empty runs the one line the root `.python-version` selects. Where there is none it runs the hub's fallback line. A caller that sets `python-versions` for both `validate-task.yml` and `build-release-task.yml` passes the same value to each. So the lines its tests run under are the lines its artifact is consumed under. Each environment lives outside the checkout. It installs the artifact, then the project's locked dependency groups from `uv.lock` without the project itself. The check asserts that `importlib.metadata` reports the version the leaf computed. It also asserts that every top-level name the installed distribution provides imports from the environment's site-packages, not the source tree. A distribution providing none, such as one of scripts only, reports that row skipped. It then runs the caller's `tests/` folder against the installed copy with pytest in `importlib` import mode. That run has the source tree off `sys.path` and the project's `pythonpath` setting cleared. Its working directory is outside the project. So the caller's suite must not read a path relative to the project root, or a tool setting read from the working directory. It must import a sibling helper as part of a package. The project directory holds its own `uv.lock`. A project with no `tests/` folder, or a run collecting no tests, is reported skipped rather than passed. Every line and artifact reports one summary row per assertion. A failed environment, install, or metadata read ends that artifact's rows rather than the run. The job fails at the end if any failed. The check uploads nothing, so it honors D1.3. It runs inside the build job, so a failure blocks the publish job that `needs:` that build. A caller's own `build-pypi` hook replaces the whole leaf and is outside the check. *Prevents: a defect that exists only in the built form shipping. One example is a module left out of the wheel while the tests, which import it from the source tree, stay green.* +- **D1.9 Each declared test line runs as its own named unit-test leg.** Input: a repo declaring .NET lines in `dotnet-versions` of `validate-task.yml`, Python lines in `python-versions`, or both. Output: each declared .NET line runs as a `Unit test job (.NET X.Y)` leg running `dotnet test --framework netX.Y` under that line's runtime. Each declared Python line runs as a `Unit test job (Python X.Y)` leg, or as the caller's named `test-matrix` legs where it sets one. A caller declaring neither runs the one line each of `global.json` and `.python-version` selects. The hub's fallback line stands in where a file is absent. The .NET legs run only where a `*Tests*.csproj` exists. The Python legs run only where a Python directory resolves. So a repo holding one kind reports no leg of the other. Each leg uploads its own coverage report, and the .NET upload carries a per-line flag beside `dotnet`. A failing leg does not cancel its siblings. *Prevents: a failing target framework or interpreter hiding inside a combined run naming none of them. A .NET-only repo reporting a Python line it never ran is the other.* ### D2 - Input/State Validation at Entry @@ -230,6 +231,8 @@ D1.7 is read in the build job. A step after the default leaf plans the declared D1.8 is read in the build job. A step after the default leaf runs the consume check. It receives the build's computed version and the `python-versions` list. Empty becomes the one line the root `.python-version` selects, or the hub's fallback line where there is none. It uploads nothing. +D1.9 is read in the validate task's job list. The `Build test matrix job` outputs one matrix per kind, and each unit-test job's `matrix` reads its output. The .NET job's `dotnet test` carries `--framework` for its matrix line, and the Python job holds no .NET step. Each job's `if:` reads the output that says its kind exists. + Cite what each verdict rests on. That is `file:line` for a file in the audited repo. It is the evidence's own name where a setting, a ruleset, or a secret name rather than a file is the evidence. Where the guarantee binds a workflow or composite action the audited repo only reaches, it is `/@` plus the `file:line` in that repo. The callee is read at the SHA the caller pins. An **N/A** verdict names the absent construct instead, there being no line to cite. ### 5B. End-to-End Trace Scenarios (No Execution, Deterministic from the YAML) diff --git a/docs/reusable-workflows.md b/docs/reusable-workflows.md index e0b2848f3..eab0e6971 100644 --- a/docs/reusable-workflows.md +++ b/docs/reusable-workflows.md @@ -56,7 +56,7 @@ A workflow whose job graph is identical across repos of a type is reached, not c ### The Hook Contract -A hook receives the fixed inputs [WORKFLOW.md "Reusable-Task Parameter Contract"][workflow-reusable-task-parameter-contract] gives a leaf today. Those are `ref`, `branch`, `smoke` where relevant, and the NBGV version outputs where a build needs them. It reports back through step outputs and, for a release target, through the existing artifact seam, `release-asset--`, which the hub's `github-release` job collects by pattern. Each task finds a hook by its `action.yml` alone, so a hook named `action.yaml` is never run. The `install-test-deps` hook is an exception, taking `leg` and `directories` inputs and reporting nothing back. It may also run a check that needs that leg's environment. A failure there fails the leg's `unit-test` job before its Python tests run. The `pre-test` hook is another, taking no inputs and reporting nothing back. Each `unit-test` leg runs it before the .NET SDK setup, where a .NET test project exists and the caller carries the hook. So a system tool a .NET test shells out to is installed before those tests run. The `build-release-asset` hook is another, writing its files into the `output-directory` it receives, on a smoke run too, and leaving the upload to the task. The task accepts only regular files at that directory's top level and refuses a subdirectory, a symlink, or a dot-prefixed name. A package hook also uploads the artifact its publish job consumes: a NuGet hook uploads `nuget-build-` as well as its `release-asset-*`. A PyPI hook uploads `pypi-build-`, and a PyPI-only caller whose hook uploads no `release-asset-*` sets `expect_release_assets` false. A NuGet or PyPI hook has to carry that exact package-artifact name or its publish job finds nothing. The `package-consume` hook is another, optional and taking `frameworks`, `package-id`, `version`, and `feed-dir` inputs while reporting nothing back. `build-nuget` runs it once after the hub default's own package consume check, in smoke and publish runs alike. So the hook loops over the JSON `frameworks` array itself. A caller carrying its own `build-nuget` hook gets neither check, since that hook's output location is unknown to the hub. The `validate` and `resolve-upstream` hooks can also take one string from their caller. `validate-task.yml` and `check-upstream-version-task.yml` each declare an optional `hook-input` input. Each passes a non-empty value on to its hook's own `hook-input` input. The task passes it from a step of its own, run only when the caller sets it. So a caller passing none runs a hook declaring no such input exactly as before. A caller that sets it needs a hook declaring `hook-input` as an optional input. The caller defines what the value means. It can name which of two callers runs the hook, or carry a change-gate result an expensive check skips on. The hub's no-op `validate-default` never receives it. A hook may use marketplace actions, which is the reason a hook is a composite action rather than a script. A toolchain setup, a Docker build, or a coverage upload is a `uses:` step, and a shell script cannot carry one. Action pins inside a hook follow the SHA-pinning rule like any other workflow content, and Dependabot bumps them in the repo that carries the hook. A hook runs with no persisted git credential, since every checkout ahead of a hook sets `persist-credentials: false`. A hook that runs git against the remote therefore passes its own credential to that call. +A hook receives the fixed inputs [WORKFLOW.md "Reusable-Task Parameter Contract"][workflow-reusable-task-parameter-contract] gives a leaf today. Those are `ref`, `branch`, `smoke` where relevant, and the NBGV version outputs where a build needs them. It reports back through step outputs and, for a release target, through the existing artifact seam, `release-asset--`, which the hub's `github-release` job collects by pattern. Each task finds a hook by its `action.yml` alone, so a hook named `action.yaml` is never run. The `install-test-deps` hook is an exception, taking `leg` and `directories` inputs and reporting nothing back. It may also run a check that needs that leg's environment. A failure there fails the leg's `unit-test` job before its Python tests run. The `pre-test` hook is another, taking no inputs and reporting nothing back. Each `unit-test-dotnet` leg runs it before the .NET SDK setup, where a .NET test project exists and the caller carries the hook. So a system tool a .NET test shells out to is installed before those tests run. The `build-release-asset` hook is another, writing its files into the `output-directory` it receives, on a smoke run too, and leaving the upload to the task. The task accepts only regular files at that directory's top level and refuses a subdirectory, a symlink, or a dot-prefixed name. A package hook also uploads the artifact its publish job consumes: a NuGet hook uploads `nuget-build-` as well as its `release-asset-*`. A PyPI hook uploads `pypi-build-`, and a PyPI-only caller whose hook uploads no `release-asset-*` sets `expect_release_assets` false. A NuGet or PyPI hook has to carry that exact package-artifact name or its publish job finds nothing. The `package-consume` hook is another, optional and taking `frameworks`, `package-id`, `version`, and `feed-dir` inputs while reporting nothing back. `build-nuget` runs it once after the hub default's own package consume check, in smoke and publish runs alike. So the hook loops over the JSON `frameworks` array itself. A caller carrying its own `build-nuget` hook gets neither check, since that hook's output location is unknown to the hub. The `validate` and `resolve-upstream` hooks can also take one string from their caller. `validate-task.yml` and `check-upstream-version-task.yml` each declare an optional `hook-input` input. Each passes a non-empty value on to its hook's own `hook-input` input. The task passes it from a step of its own, run only when the caller sets it. So a caller passing none runs a hook declaring no such input exactly as before. A caller that sets it needs a hook declaring `hook-input` as an optional input. The caller defines what the value means. It can name which of two callers runs the hook, or carry a change-gate result an expensive check skips on. The hub's no-op `validate-default` never receives it. A hook may use marketplace actions, which is the reason a hook is a composite action rather than a script. A toolchain setup, a Docker build, or a coverage upload is a `uses:` step, and a shell script cannot carry one. Action pins inside a hook follow the SHA-pinning rule like any other workflow content, and Dependabot bumps them in the repo that carries the hook. A hook runs with no persisted git credential, since every checkout ahead of a hook sets `persist-credentials: false`. A hook that runs git against the remote therefore passes its own credential to that call. ### Pinning @@ -87,7 +87,7 @@ The target set. A row exists once its hub task ships, and until then the row is | Hub task | Hooks, at `.github/actions//action.yml` in the caller | Hub default | | --- | --- | --- | | `merge-bot-task.yml` | none, extra bot rules are a `with:` input | not applicable | -| `validate-task.yml` | `validate` (a repo's own domain checks, beyond the fleet doc-lint block and the generic unit-test job), `install-test-deps` (a `test-matrix` leg's dependency install and per-leg checks). Also `pre-test`, for system tools the .NET tests need | no-op for `validate`, none for `install-test-deps`, which is required where `test-matrix` or `test-matrix-file` is set. None for `pre-test` | +| `validate-task.yml` | `validate` (a repo's own domain checks, beyond the fleet doc-lint block and the generic unit-test jobs), `install-test-deps` (a `test-matrix` leg's dependency install and per-leg checks). Also `pre-test`, for system tools the .NET tests need | no-op for `validate`, none for `install-test-deps`, which is required where `test-matrix` or `test-matrix-file` is set. None for `pre-test` | | `get-version-task.yml`, `publish-plan-task.yml` | none | not applicable | | `build-release-task.yml` | `dotnet-publish`, `build-nuget`, `build-pypi`, `build-release-asset` | `dotnet-publish-default`, `nuget-build-default` followed by `package-consume-nuget`, `pypi-build-default` followed by `package-consume-pypi`, none for `build-release-asset`, which is required where `enable_release_asset` is set | | `build-docker-task.yml` | `docker-prepare` (extra tags, build-args, matrix), `docker-build-base` | vanilla single-target from `image`, base build required when `build-base` | @@ -155,7 +155,7 @@ Adoptable since `2.0.338`. Each repo replaces the whole of its `.github/workflow ### Stage 2: The Gates -Hub: `validate-task.yml` hosts a `lint` job (the fleet doc-lint block, language lint by tree detection, the prose gate, and the repo gate). It also hosts a generic `unit-test` job. That job runs a `dotnet test`, and a `pytest` or `unittest` suite under coverage in each Python directory. The job skips cleanly where the caller carries no test project. It fails a declared Python directory that has none. The task also hosts a `validate` job resolving the `validate` hook for a repo's own domain checks. The `lint` and `unit-test` jobs decide #729 in their `uvx` tool steps. There is no `test-pull-request-task.yml`: the ruleset-bound aggregator stays in the caller stub by design. A task wrapping one line that calls `validate-task.yml` hosts nothing generic, so the stub shapes live in [Adopting the Gates][adopting-the-gates] instead. The trigger shape, operational or release, settles #585 in that same section. This stage is where the hook fallback is first proven live. The hub carries its own `validate` hook. So a hub pull request exercises the override path. That hook is the hub's registry and spec check, script self-tests, fleet-skills check, and unclassified-character report. A repo with no hook of its own exercises the default. The repo gate also shellchecks and schema-checks every composite action under `.github/actions/`, so a downstream repo gets that check at its next pin bump. +Hub: `validate-task.yml` hosts a `lint` job (the fleet doc-lint block, language lint by tree detection, the prose gate, and the repo gate). It also hosts a `unit-test` job per kind. The `unit-test-dotnet` job runs a `dotnet test` per .NET line, and the `unit-test` job runs a `pytest` or `unittest` suite under coverage in each Python directory. Each skips cleanly where the caller carries no project of its kind. The Python job fails a declared Python directory that has no tests. The task also hosts a `validate` job resolving the `validate` hook for a repo's own domain checks. The `lint` and `unit-test` jobs decide #729 in their `uvx` tool steps. There is no `test-pull-request-task.yml`: the ruleset-bound aggregator stays in the caller stub by design. A task wrapping one line that calls `validate-task.yml` hosts nothing generic, so the stub shapes live in [Adopting the Gates][adopting-the-gates] instead. The trigger shape, operational or release, settles #585 in that same section. This stage is where the hook fallback is first proven live. The hub carries its own `validate` hook. So a hub pull request exercises the override path. That hook is the hub's registry and spec check, script self-tests, fleet-skills check, and unclassified-character report. A repo with no hook of its own exercises the default. The repo gate also shellchecks and schema-checks every composite action under `.github/actions/`, so a downstream repo gets that check at its next pin bump. - [x] Hub pull request on `develop` with the task, the hub's own hook and default, and the manifest contracts, [#760][pr-760]. The catalog snippets are left for the release that follows. - [x] Promoted to `main` in #774 (`0b07a59d`) and released as `2.0.352`, the first tag carrying `validate-task.yml`. @@ -499,15 +499,15 @@ A repo whose package claims more than one interpreter names them all in `python- python-versions: '["3.13", "3.14"]' ``` -The default is empty, so a caller naming nothing runs one leg, on the line its root `.python-version` selects. A caller carrying no such file runs the hub's fallback line, 3.14, and its `lint` job warns that it did. So a caller whose `requires-python` or locked dependencies exclude 3.14 adds a `.python-version` before it moves its hub pin. A caller moving onto the fallback also moves its nested check name and its Codecov flag to 3.14. So a `.codecov.yml` naming the old flag stops matching it. Each leg uploads under a `python-` Codecov flag of its own. That keeps the legs apart in the dashboard rather than merging them into one number. And `fail-fast: false` reports a failing interpreter beside a passing one rather than cancelling the run at the first. Two things move on adoption. The nested check reads `Unit test job (Python )` rather than `Unit test job`, which binds no ruleset, only the caller's own aggregator being bound. The nested check reads that way whether or not a Python step ran, so a .NET-only caller reports a version it never used. And a repo that already uploaded Python coverage here uploaded it unflagged. So its series stops there and a `python-` one starts beside it. +The default is empty, so a caller naming nothing runs one leg, on the line its root `.python-version` selects. A caller carrying no such file runs the hub's fallback line, 3.14, and its `lint` job warns that it did. So a caller whose `requires-python` or locked dependencies exclude 3.14 adds a `.python-version` before it moves its hub pin. A caller moving onto the fallback also moves its nested check name and its Codecov flag to 3.14. So a `.codecov.yml` naming the old flag stops matching it. Each leg uploads under a `python-` Codecov flag of its own. That keeps the legs apart in the dashboard rather than merging them into one number. And `fail-fast: false` reports a failing interpreter beside a passing one rather than cancelling the run at the first. Two things move on adoption. The nested check reads `Unit test job (Python )` rather than `Unit test job`, which binds no ruleset, only the caller's own aggregator being bound. A .NET-only caller reports no Python leg, since the job skips where no Python directory resolves. And a repo that already uploaded Python coverage here uploaded it unflagged. So its series stops there and a `python-` one starts beside it. Quote each entry, and give each one a version. The `Build test matrix job` runs first on every call and refuses an array holding an entry with no non-whitespace character. Such a value would otherwise run green on an interpreter nobody chose. That is because `setup-uv` trims what it reads and then reads an empty input as an absent one. A caller reaches that by interpolating an unset value of its own, or by leaving a stray space beside it. The job also refuses an unquoted entry, since `fromJSON` admits a JSON array of numbers. Some of those numbers `uv` resolves to a real interpreter, `'[3]'` among them, so an unquoted entry is a second silent pass. The job refuses an empty array, a non-array, and concatenated JSON values, each with a named cause. The `unit-test` job and its `Run Python tests step` never see a bad `python-versions`. -A caller carrying a .NET test project as well repeats that half of the job once per leg. The matrix is on the job rather than on its Python steps. So naming a second version there buys runner minutes rather than a second measurement. The `lint` job runs once, and its Python steps run under the first interpreter `python-versions` names, or the selected line where it names none. So a `uv.lock` whose `requires-python` floor is above the fallback line still syncs there. A caller carrying a `.python-version` names that line first, since the release builds on it, and the `lint` job refuses one that does not. The prose and repo gates beside them stay on 3.13, the floor the hub's own scripts declare. Its type check is performed at that interpreter alone. `mypy` and `pyright` each default their target to the one they run under. That holds where the repo's own `[tool.mypy]` or `[tool.pyright]` section does not name a version. Meanwhile `ruff` takes its target from `requires-python` where the `pyproject.toml` declares a `[project]` table and from its own default where it does not. A repo testing several interpreters and carrying no `.python-version` settles the type-check target in its own configuration. The `lint` job refuses a `python-versions` value whose first entry is not a quoted version string, with a named cause. +A caller carrying a .NET test project as well runs it in the separate `unit-test-dotnet` job, so the Python legs hold no .NET step. A repo holding no Python directory reports no Python leg. The `lint` job runs once, and its Python steps run under the first interpreter `python-versions` names, or the selected line where it names none. So a `uv.lock` whose `requires-python` floor is above the fallback line still syncs there. A caller carrying a `.python-version` names that line first, since the release builds on it, and the `lint` job refuses one that does not. The prose and repo gates beside them stay on 3.13, the floor the hub's own scripts declare. Its type check is performed at that interpreter alone. `mypy` and `pyright` each default their target to the one they run under. That holds where the repo's own `[tool.mypy]` or `[tool.pyright]` section does not name a version. Meanwhile `ruff` takes its target from `requires-python` where the `pyproject.toml` declares a `[project]` table and from its own default where it does not. A repo testing several interpreters and carrying no `.python-version` settles the type-check target in its own configuration. The `lint` job refuses a `python-versions` value whose first entry is not a quoted version string, with a named cause. -The .NET upload carries one fixed `dotnet` flag, the same in every leg. A caller whose `.codecov.yml` configures flags names `dotnet` for the .NET unit-test share, beside the Python legs' own flags. A .NET caller's coverage reads as a `dotnet` series from its first pin bump onto a release carrying the flag, rather than unflagged. +Each .NET upload carries the fixed `dotnet` flag and a `dotnet-X.Y` flag naming its line. A caller whose `.codecov.yml` configures flags names `dotnet` for the .NET unit-test share, beside the Python legs' own flags. It may also name a line's flag to read that line apart. A .NET caller's coverage reads as a `dotnet` series from its first pin bump onto a release carrying the flag, rather than unflagged. -A repo whose .NET projects multi-target names every line they build in `dotnet-versions`, such as `'["11.0", "10.0"]'` for `net10.0;net11.0`. It is the .NET counterpart of `python-versions`, and it adds no matrix leg. One SDK builds every target framework, and one `dotnet test` runs each framework's tests under that framework's own runtime. So the one `unit-test` job installs every listed line beside the selected one. The first entry is the `X.Y` line the root `global.json` selects, the highest target framework's, since the release builds on it. The `dotnet-sdk` action refuses a first entry naming another line, with a named cause. It also refuses an entry that is not a quoted `X.Y` line. The `Build test matrix job` runs that check first, before any job builds, as it does for `python-versions`. The `lint` job repeats it, since it does not wait on that job. A caller carrying no `global.json` `sdk.version` installs every entry instead of the fallback line. Without the input, a lower framework's tests run only where the runner image happens to carry its runtime. +A repo whose .NET projects multi-target names every line they build in `dotnet-versions`, such as `'["11.0", "10.0"]'` for `net10.0;net11.0`. It is the .NET counterpart of `python-versions`, and each entry is its own `Unit test job (.NET X.Y)` leg running `dotnet test --framework netX.Y`. One SDK builds every target framework, and each framework's tests run under that framework's own runtime. So every leg installs every listed line beside the selected one. A caller naming none runs the one leg for the line `global.json` selects, or the fallback line. The first entry is the `X.Y` line the root `global.json` selects, the highest target framework's, since the release builds on it. The `dotnet-sdk` action refuses a first entry naming another line, with a named cause. It also refuses an entry that is not a quoted `X.Y` line. The `Build test matrix job` runs that check first, before any job builds, as it does for `python-versions`. The `lint` job repeats it, since it does not wait on that job. A caller carrying no `global.json` `sdk.version` installs every entry instead of the fallback line. Without the input, the one leg runs `--framework` for the selected line alone, so a lower framework's tests never run. A PyPI repo names the lines its built package must work under in the `python-versions` input of `build-release-task.yml`, as it does for `validate-task.yml`. The two inputs hold the same value, so the lines its tests run under are the lines its wheel and sdist are consumed under. The input is validated like the unit-test one. Empty consumes under the one line the root `.python-version` selects. Where there is none it consumes under the hub's fallback line. After the hub default builds, the `build-pypi` job installs the wheel and, separately, the sdist into a fresh environment per line, outside the checkout. It then installs the project's locked dependency groups without the project. It asserts the installed version and that the package imports from site-packages. It runs the caller's `tests/` folder against the installed copy, from outside the project. The suite must read no path relative to the project root, and no tool setting from the working directory. It must import a sibling helper as part of a package. The project directory must hold its own `uv.lock`. A smoke run runs it unchanged and uploads nothing, and a caller's own `build-pypi` hook is outside it. WORKFLOW.md D1.8 states the guarantee. diff --git a/spec/project-types.json b/spec/project-types.json index 57fb41922..d90bf27c8 100644 --- a/spec/project-types.json +++ b/spec/project-types.json @@ -12,7 +12,7 @@ { "id": "csharp.analyzers.zerowarnings", "verdict": "intent", "assert": "Analyzer severities are enforced; warnings are not relaxed or suppressed wholesale.", "intentRef": "CODESTYLE.md" }, { "id": "csharp.centralconfig.props", "verdict": "letter", "assert": "Shared MSBuild configuration is centralized at the repo root: Directory.Build.props carries the common analyzer and warning properties (the Zero Warnings set), and Directory.Packages.props enables ManagePackageVersionsCentrally with every dependency version declared once - a csproj carries only project-specific properties and versionless PackageReference items.", "intentRef": "CODESTYLE.md" }, { "id": "csharp.sdk.globaljson", "verdict": "letter", "assert": "A root global.json exists and carries an sdk block. Its version is exactly .0.100 for the repo's highest .NET TFM major, never a netstandard target's (10.0.100 alongside net10.0, and 11.0.100 alongside net10.0;net11.0). It sets rollForward latestFeature and allowPrerelease false, so the local dotnet host selects the SDK line CI installs. The line is the repository's own and need not be the hub baseline's. A carried .NET devcontainer's image tag names the same major. So does the first entry of any dotnet-versions value a caller passes the hub's validate-task.yml. No .props or .targets file the repository holds sets LangVersion, the SDK's own targets aside. Nor does any .csproj targeting a .NET TFM. A netstandard analyzer or source-generator .csproj may set a fixed number, the .NET TFM's C# version. No repository file sets LangVersion to latest, latestMajor, or preview, or sets EnablePreviewFeatures. Required for every C# repo.", "intentRef": "CODESTYLE.md" }, - { "id": "csharp.coverage.codecov", "verdict": "letter", "assert": "The unit-test job collects coverage (dotnet test --coverage --coverage-output-format cobertura --results-directory ./coverage, with the output filename left unset so each test project writes its own report rather than overwriting a shared one) and uploads it to Codecov via codecov/codecov-action, best-effort (fail_ci_if_error: false so a Codecov outage or an absent token never reds the gate). CODECOV_TOKEN is stored in both the repo actions and dependabot secrets stores, the second so the upload does not skip on a Dependabot PR, and the caller maps it to the reusable validator by name. The validator prefixes each report to coverage-.cobertura.xml before uploading, since codecov-cli does not match the default name. Where the repo's test project is MTP-based (xunit.v3 4.0.0 or later), it also carries a root global.json declaring test.runner as Microsoft.Testing.Platform, references Microsoft.Testing.Extensions.CodeCoverage at 18.9.0 or later rather than coverlet.collector, and drops xunit.runner.visualstudio. A test project not yet MTP-based keeps the VSTest collector and its existing pin, which is a migration owed rather than drift. Required for every C# repo with tests.", "intentRef": "WORKFLOW.md", "minProfile": "build" } + { "id": "csharp.coverage.codecov", "verdict": "letter", "assert": "The .NET unit-test job collects coverage (dotnet test --coverage --coverage-output-format cobertura --results-directory ./coverage, run once per declared .NET line, with the output filename left unset so each test project writes its own report rather than overwriting a shared one) and uploads it to Codecov via codecov/codecov-action, best-effort (fail_ci_if_error: false so a Codecov outage or an absent token never reds the gate). CODECOV_TOKEN is stored in both the repo actions and dependabot secrets stores, the second so the upload does not skip on a Dependabot PR, and the caller maps it to the reusable validator by name. The validator prefixes each report to coverage-.cobertura.xml before uploading, since codecov-cli does not match the default name. Where the repo's test project is MTP-based (xunit.v3 4.0.0 or later), it also carries a root global.json declaring test.runner as Microsoft.Testing.Platform, references Microsoft.Testing.Extensions.CodeCoverage at 18.9.0 or later rather than coverlet.collector, and drops xunit.runner.visualstudio. A test project not yet MTP-based keeps the VSTest collector and its existing pin, which is a migration owed rather than drift. Required for every C# repo with tests.", "intentRef": "WORKFLOW.md", "minProfile": "build" } ] }, "nuget": { diff --git a/tests/test_release_guards.py b/tests/test_release_guards.py index cb1ae33a6..e1c3727f2 100755 --- a/tests/test_release_guards.py +++ b/tests/test_release_guards.py @@ -1957,7 +1957,7 @@ def test_validator_python_leg_reaches_a_pip_dependency_repo(self) -> None: collected no coverage and never reached the missing-report failure either. """ workflow = (REPO / ".github/workflows/validate-task.yml").read_text(encoding="utf-8") - job = workflow.split("\n unit-test:\n", 1)[1].split("\n validate:\n", 1)[0] + job = workflow.split("\n unit-test:\n", 1)[1].split("\n unit-test-dotnet:\n", 1)[0] # Every Python step keys on the resolved directories rather than on a root file, or a nested project is skipped. self.assertNotIn("hashFiles('pyproject.toml')", job) @@ -2000,7 +2000,7 @@ def test_validator_python_leg_reaches_a_pip_dependency_repo(self) -> None: def test_validator_pre_test_hook_runs_before_the_dotnet_tests(self) -> None: """A caller's system tools reach the runner before the .NET tests, and only where it carries the hook.""" workflow = (REPO / ".github/workflows/validate-task.yml").read_text(encoding="utf-8") - job = workflow.split("\n unit-test:\n", 1)[1].split("\n validate:\n", 1)[0] + job = workflow.split("\n unit-test-dotnet:\n", 1)[1].split("\n validate:\n", 1)[0] order = [ job.index("name: Checkout code step"), job.index("name: Run caller pre-test hook step"), @@ -2019,7 +2019,7 @@ def test_validator_pre_test_hook_runs_before_the_dotnet_tests(self) -> None: def test_validator_test_matrix_hook_runs_between_install_and_pytest(self) -> None: """A dependency-version leg overrides installed versions after the base install and before pytest.""" workflow = (REPO / ".github/workflows/validate-task.yml").read_text(encoding="utf-8") - job = workflow.split("\n unit-test:\n", 1)[1].split("\n validate:\n", 1)[0] + job = workflow.split("\n unit-test:\n", 1)[1].split("\n unit-test-dotnet:\n", 1)[0] order = [ job.index("name: Check caller install-test-deps hook step"), @@ -2129,12 +2129,10 @@ def test_validator_test_matrix_file_takes_the_inline_input_checks(self) -> None: job = workflow.split("\n test-matrix:\n", 1)[1].split("\n lint:\n", 1)[0] # A file needs the whole tree, and it has to be there before the check reads it. + # The job also reads the tree for its test projects and Python directories, so the checkout is whole and unconditional. checkout = yaml_step(job, "Checkout code step") - self.assertIn(" if: ${{ inputs.test-matrix-file != '' || ", checkout) - self.assertEqual( - "${{ inputs.test-matrix-file == '' && fromJSON('\"/.python-version\\n/global.json\"') || '' }}", - yaml_value(checkout, "with", "sparse-checkout"), - ) + self.assertIsNone(yaml_value(checkout, "if")) + self.assertIsNone(yaml_value(checkout, "with", "sparse-checkout")) self.assertEqual(yaml_value(checkout, "with", "persist-credentials"), "false") steps = re.findall(r"(?m)^ - name: (.*)$", job) self.assertLess( @@ -2168,6 +2166,8 @@ def step(script: str, **env: str) -> tuple[int, str, str]: "TEST_MATRIX": "", "TEST_MATRIX_FILE": "", "PYTHON_VERSIONS": '["3.13"]', + "DOTNET_LINES": '["10.0", "9.0"]', + "DOTNET_TESTS": "true", **env, }, ) @@ -2179,8 +2179,10 @@ def built(**env: str) -> object: self.assertEqual(0, status, log) status, log, lines = step(build, LEGS=output.removeprefix("legs=").strip()) self.assertEqual(0, status, log) - matrix, versions = lines.splitlines() + matrix, versions, dotnet_matrix, dotnet_tests = lines.splitlines() self.assertEqual('versions=["3.13"]', versions) + self.assertEqual('dotnet-matrix={"dotnet-version":["10.0","9.0"]}', dotnet_matrix) + self.assertEqual("dotnet-tests=true", dotnet_tests) return json.loads(matrix.removeprefix("matrix=")) # Each input builds the legs it holds, the inline one differing so a stale resolved file cannot pass for it. @@ -2223,7 +2225,7 @@ def test_validator_pytest_leg_fans_out_over_every_named_interpreter(self) -> Non claiming the rest. The fan-out is therefore asserted here rather than left to be read by eye. """ workflow = (REPO / ".github/workflows/validate-task.yml").read_text(encoding="utf-8") - job = workflow.split("\n unit-test:\n", 1)[1].split("\n validate:\n", 1)[0] + job = workflow.split("\n unit-test:\n", 1)[1].split("\n unit-test-dotnet:\n", 1)[0] # Empty is the default, so a caller naming nothing runs the line its own .python-version selects. declaration = workflow.split(" python-versions:\n", 1)[1].split("\n secrets:", 1)[0] @@ -2261,12 +2263,14 @@ def test_validator_pytest_leg_fans_out_over_every_named_interpreter(self) -> Non def test_validator_dotnet_upload_carries_a_fixed_flag(self) -> None: """A path filter cannot tell the .NET upload from a Python leg's upload where their paths overlap. - The .NET upload therefore carries one fixed flag, the same in every leg, so a caller can name it. + The .NET upload therefore carries the fixed dotnet flag in every leg, so a caller can name it, and a per-line flag beside it. """ workflow = (REPO / ".github/workflows/validate-task.yml").read_text(encoding="utf-8") - job = workflow.split("\n unit-test:\n", 1)[1].split("\n validate:\n", 1)[0] + job = workflow.split("\n unit-test-dotnet:\n", 1)[1].split("\n validate:\n", 1)[0] upload = yaml_step(job, "Upload coverage to Codecov step") - self.assertEqual(yaml_value(upload, "with", "flags"), "dotnet") + self.assertEqual( + yaml_value(upload, "with", "flags"), "dotnet,dotnet-${{ matrix.dotnet-version }}" + ) def test_validator_checks_out_the_triggering_commit(self) -> None: """A ref: on any checkout moves the gate off the commit a publisher releases. @@ -2280,6 +2284,80 @@ def test_validator_checks_out_the_triggering_commit(self) -> None: self.assertIn("actions/checkout@", workflow) self.assertNotRegex(workflow, r"(?m)(^[ \t-]*|[{,][ \t]*)[\"']?ref[\"']?[ \t]*:") + def test_validator_runs_each_dotnet_line_and_python_line_as_its_own_leg(self) -> None: + """WORKFLOW.md D1.9: a .NET line is a leg of its own, and the Python job carries no .NET step.""" + workflow = (REPO / ".github/workflows/validate-task.yml").read_text(encoding="utf-8") + python_job = workflow.split("\n unit-test:\n", 1)[1].split("\n unit-test-dotnet:\n", 1)[0] + dotnet_job = workflow.split("\n unit-test-dotnet:\n", 1)[1].split("\n validate:\n", 1)[0] + builder = workflow.split("\n test-matrix:\n", 1)[1].split("\n lint:\n", 1)[0] + + # The name carries the line, so a failing framework reads from the check list. + self.assertIn(" name: Unit test job (.NET ${{ matrix.dotnet-version }})\n", dotnet_job) + self.assertIn(" needs: test-matrix\n", dotnet_job) + self.assertIn(" fail-fast: false\n", dotnet_job) + self.assertIn( + " matrix: ${{ fromJSON(needs.test-matrix.outputs.dotnet-matrix) }}\n", dotnet_job + ) + self.assertIn( + " if: ${{ needs.test-matrix.outputs.dotnet-tests == 'true' }}\n", dotnet_job + ) + self.assertIn(" contents: read\n", dotnet_job) + + # Each invocation names its framework, and the value reaches the script through env. + script = step_script_text(dotnet_job, "Run unit tests step") + invocations = [ + line + for line in script.splitlines() + if re.match(r"\s*(?:\S.*\s)?dotnet test ", line) and not line.lstrip().startswith("#") + ] + self.assertEqual(2, len(invocations)) + self.assertEqual(2, script.count('dotnet test --framework "net$DOTNET_VERSION" ')) + run_step = yaml_step(dotnet_job, "Run unit tests step") + self.assertEqual( + "${{ matrix.dotnet-version }}", yaml_value(run_step, "env", "DOTNET_VERSION") + ) + self.assertNotIn("matrix.dotnet-version", script) + self.assertIn("wrote no non-empty Cobertura report", script) + + # The SDK still installs every listed line, and the upload names the line beside the fixed flag. + setup = yaml_step(dotnet_job, "Setup .NET SDK step") + self.assertEqual("${{ inputs.dotnet-versions }}", yaml_value(setup, "with", "versions")) + self.assertEqual( + "dotnet,dotnet-${{ matrix.dotnet-version }}", + yaml_value(yaml_step(dotnet_job, "Upload coverage to Codecov step"), "with", "flags"), + ) + self.assertIn("name: Checkout code step", dotnet_job) + + # The Python job holds no .NET step and skips when no Python directory resolves. + for needle in ( + "Setup .NET SDK step", + "Resolve .NET workspaces step", + "Run unit tests step", + "Run caller pre-test hook step", + "Tests*.csproj", + "dotnet test", + "actions/dotnet-sdk", + ): + self.assertNotIn(needle, python_job) + self.assertIn(" if: ${{ needs.test-matrix.outputs.python-any == 'true' }}\n", python_job) + self.assertIn("python-any: ${{ steps.python-directories.outputs.any }}", builder) + self.assertIn("dotnet-matrix: ${{ steps.build.outputs.dotnet-matrix }}", builder) + self.assertIn("dotnet-tests: ${{ steps.build.outputs.dotnet-tests }}", builder) + build = yaml_step(builder, "Build unit-test matrix step") + self.assertEqual( + "${{ steps.dotnet-sdk.outputs.lines }}", yaml_value(build, "env", "DOTNET_LINES") + ) + self.assertEqual( + "${{ hashFiles('**/*Tests*.csproj') != '' }}", yaml_value(build, "env", "DOTNET_TESTS") + ) + sdk = yaml_step(builder, "Validate dotnet-versions input step") + self.assertEqual("dotnet-sdk", yaml_value(sdk, "id")) + resolve = yaml_step(builder, "Resolve Python directories step") + self.assertEqual("$/.github/actions/python-directories", yaml_value(resolve, "uses")) + self.assertEqual( + "${{ inputs.python-directories }}", yaml_value(resolve, "with", "directories") + ) + @unittest.skipUnless( shutil.which("bash") and os.name == "posix", "the step runs under bash against a stand-in dotnet that only a POSIX host can execute", @@ -2293,7 +2371,7 @@ def test_validator_dotnet_leg_fails_when_no_report_was_written(self) -> None: counted it would therefore pass a run that measured nothing. """ workflow = (REPO / ".github/workflows/validate-task.yml").read_text(encoding="utf-8") - job = workflow.split("\n unit-test:\n", 1)[1].split("\n validate:\n", 1)[0] + job = workflow.split("\n unit-test-dotnet:\n", 1)[1].split("\n validate:\n", 1)[0] marker = " - name: Run unit tests step\n" self.assertIn(marker, job) script = step_script_text(job, "Run unit tests step") @@ -2324,6 +2402,7 @@ def test_validator_dotnet_leg_fails_when_no_report_was_written(self) -> None: **without_git_location(), "PATH": f"{bin_dir}{os.pathsep}{os.environ.get('PATH', os.defpath)}", "WORKSPACES": "", + "DOTNET_VERSION": "10.0", }, capture_output=True, text=True, @@ -2355,7 +2434,7 @@ def test_validator_dotnet_steps_run_once_per_workspace(self) -> None: """ workflow = (REPO / ".github/workflows/validate-task.yml").read_text(encoding="utf-8") lint = workflow.split("\n lint:\n", 1)[1].split("\n unit-test:\n", 1)[0] - unit = workflow.split("\n unit-test:\n", 1)[1].split("\n validate:\n", 1)[0] + unit = workflow.split("\n unit-test-dotnet:\n", 1)[1].split("\n validate:\n", 1)[0] action = (REPO / ".github/actions/dotnet-workspaces/action.yml").read_text(encoding="utf-8") resolver = step_script_text(action, "Resolve .NET workspaces step") self.assertNotIn("dotnet_workspaces", workflow) @@ -2401,12 +2480,12 @@ def named_style(*workspaces: str) -> list[str]: "a root solution": ( ["App.sln", "src/Lib/Lib.csproj", "tests/LibTests/LibTests.csproj"], bare_style, - [f"test {flags}"], + [f"test --framework net10.0 {flags}"], ), "a root project": ( ["App.csproj", "tests/AppTests/AppTests.csproj"], bare_style, - [f"test {flags}"], + [f"test --framework net10.0 {flags}"], ), "solutions below the root": ( [ @@ -2416,39 +2495,41 @@ def named_style(*workspaces: str) -> list[str]: "src/LibTests/LibTests.csproj", ], named_style("src/App.sln", "tools/Tool.slnx"), - [f"test --project src/LibTests/LibTests.csproj {flags}"], + [f"test --framework net10.0 --project src/LibTests/LibTests.csproj {flags}"], ), "projects and no solution": ( ["FindInFile/FindInFile.csproj", "FindInFileTests/FindInFileTests.csproj"], named_style( "FindInFile/FindInFile.csproj", "FindInFileTests/FindInFileTests.csproj" ), - [f"test --project FindInFileTests/FindInFileTests.csproj {flags}"], + [ + f"test --framework net10.0 --project FindInFileTests/FindInFileTests.csproj {flags}" + ], ), "a root .sln beside the .slnx dotnet sln migrate writes": ( ["App.sln", "App.slnx", "src/Lib/Lib.csproj", "tests/LibTests/LibTests.csproj"], named_style("App.sln", "App.slnx"), - [f"test --project tests/LibTests/LibTests.csproj {flags}"], + [f"test --framework net10.0 --project tests/LibTests/LibTests.csproj {flags}"], ), "a root solution beside a root project": ( ["App.slnx", "Tool.csproj", "tests/AppTests/AppTests.csproj"], named_style("App.slnx"), - [f"test --project tests/AppTests/AppTests.csproj {flags}"], + [f"test --framework net10.0 --project tests/AppTests/AppTests.csproj {flags}"], ), "two root projects": ( ["App.csproj", "AppTests.csproj"], named_style("App.csproj", "AppTests.csproj"), - [f"test --project AppTests.csproj {flags}"], + [f"test --framework net10.0 --project AppTests.csproj {flags}"], ), "two root projects beside a nested solution": ( ["App.csproj", "AppTests.csproj", "sub/Tool.sln", "sub/Tool.csproj"], named_style("App.csproj", "AppTests.csproj", "sub/Tool.csproj"), - [f"test --project AppTests.csproj {flags}"], + [f"test --framework net10.0 --project AppTests.csproj {flags}"], ), "two root solutions beside a nested solution": ( ["App.sln", "App.slnx", "sub/Tool.sln", "tests/AppTests/AppTests.csproj"], named_style("App.sln", "App.slnx"), - [f"test --project tests/AppTests/AppTests.csproj {flags}"], + [f"test --framework net10.0 --project tests/AppTests/AppTests.csproj {flags}"], ), } steps = ((style, style_inputs, 1), (tests, test_inputs, 2)) @@ -2503,6 +2584,7 @@ def named_style(*workspaces: str) -> list[str]: "PATH": f"{bin_dir}{os.pathsep}{os.environ.get('PATH', os.defpath)}", "STUB_LOG": str(log), "WORKSPACES": match.group(2).removesuffix("\n"), + "DOTNET_VERSION": "10.0", }, capture_output=True, text=True, @@ -2527,7 +2609,7 @@ def test_validator_refuses_a_python_versions_value_fromjson_would_admit(self) -> """ workflow = (REPO / ".github/workflows/validate-task.yml").read_text(encoding="utf-8") job = workflow.split("\n test-matrix:\n", 1)[1].split("\n lint:\n", 1)[0] - unit_test = workflow.split("\n unit-test:\n", 1)[1].split("\n validate:\n", 1)[0] + unit_test = workflow.split("\n unit-test:\n", 1)[1].split("\n unit-test-dotnet:\n", 1)[0] # The guard has to precede the build it guards, and the unit-test job runs only after this job. # Matched on the dash rather than on a name: key, or a step leading with uses: would slip in ahead unseen. @@ -2838,6 +2920,7 @@ class DotnetSdkLineCase(unittest.TestCase): ACTION = REPO / ".github/actions/dotnet-sdk/action.yml" SELECT = "Select .NET SDK line step" last_stdout = "" + last_lines: tuple[str, ...] = () def select(self, global_json: str | bytes | None, versions: str = "") -> list[str]: """The outputs the selection step writes in a workspace holding `global_json`, or none. @@ -2862,7 +2945,9 @@ def run_select(self, global_json: str | bytes | None, versions: str) -> tuple[in code, self.last_stdout, _, outputs = run_selection_step( self.ACTION, self.SELECT, "global.json", global_json, {"VERSIONS": versions} ) - return code, outputs + # The reported lines are asserted by their own test, so the install outputs read as they did. + self.last_lines = tuple(line for line in outputs if line.startswith("lines=")) + return code, [line for line in outputs if not line.startswith("lines=")] def test_versions_install_every_line_beside_the_selected_one(self) -> None: """A multi-targeted test project runs each framework under its own runtime, so each line installs.""" @@ -2919,8 +3004,8 @@ def test_validate_task_hands_dotnet_versions_to_every_sdk_step(self) -> None: users = sorted( job for job, body in jobs.items() if "uses: $/.github/actions/dotnet-sdk" in body ) - self.assertEqual(users, ["lint", "test-matrix", "unit-test"]) - for job in ("lint", "unit-test"): + self.assertEqual(users, ["lint", "test-matrix", "unit-test-dotnet"]) + for job in ("lint", "unit-test-dotnet"): with self.subTest(job=job): setup = yaml_step(jobs[job], "Setup .NET SDK step") self.assertEqual( @@ -2929,7 +3014,7 @@ def test_validate_task_hands_dotnet_versions_to_every_sdk_step(self) -> None: self.assertIsNone(yaml_value(setup, "with", "install")) def test_the_entry_job_validates_dotnet_versions_before_any_build(self) -> None: - """WORKFLOW.md D2.1: the cross-input check runs once in the job unit-test waits on, installing nothing.""" + """WORKFLOW.md D2.1: the cross-input check runs once in the job the unit-test jobs wait on, installing nothing.""" workflow = (REPO / ".github/workflows/validate-task.yml").read_text(encoding="utf-8") jobs = job_texts(workflow) entry = jobs["test-matrix"] @@ -2937,10 +3022,12 @@ def test_the_entry_job_validates_dotnet_versions_before_any_build(self) -> None: self.assertEqual(yaml_value(check, "uses"), "$/.github/actions/dotnet-sdk") self.assertEqual(yaml_value(check, "with", "versions"), "${{ inputs.dotnet-versions }}") self.assertEqual(yaml_value(check, "with", "install"), "'false'") + # The step runs whether or not the input is set, since it also reports the line a caller naming none tests under. + self.assertIsNone(yaml_value(check, "if")) checkout = yaml_step(entry, "Checkout code step") - self.assertIn("inputs.dotnet-versions != ''", yaml_value(checkout, "if") or "") - self.assertIn("/global.json", yaml_value(checkout, "with", "sparse-checkout") or "") + self.assertIsNone(yaml_value(checkout, "if")) self.assertIn("needs: test-matrix", jobs["unit-test"]) + self.assertIn("needs: test-matrix", jobs["unit-test-dotnet"]) action = self.ACTION.read_text(encoding="utf-8") setup = yaml_step(action, "Setup .NET SDK step") self.assertEqual(yaml_value(setup, "if"), "${{ inputs.install != 'false' }}") @@ -2956,6 +3043,37 @@ def test_a_caller_without_an_sdk_version_gets_10x(self) -> None: self.assertEqual(self.select(None), [fallback]) self.assertEqual(self.select(json.dumps({"sdk": None})), [fallback]) + def test_the_reported_lines_are_the_versions_else_the_selected_line_else_the_fallback( + self, + ) -> None: + """Each reported line becomes one dotnet test leg, so the selection and the legs cannot disagree.""" + selects = json.dumps({"sdk": {"version": "11.0.100", "rollForward": "latestFeature"}}) + runner_only = json.dumps({"test": {"runner": "Microsoft.Testing.Platform"}}) + fallback = baseline_line()[0] + for name, global_json, versions, want in ( + ("versions", selects, '["11.0", "10.0"]', ["11.0", "10.0"]), + ( + "versions without a selecting file", + runner_only, + '["11.0", "10.0"]', + ["11.0", "10.0"], + ), + ("the selected line", selects, "", ["11.0"]), + ("the fallback", runner_only, "", [f"{fallback}.0"]), + ("no file", None, "", [f"{fallback}.0"]), + ): + with self.subTest(case=name): + self.select(global_json, versions) + self.assertEqual(self.last_lines, ("lines=" + json.dumps(want),)) + + def test_a_selected_version_with_no_line_fails(self) -> None: + code, outputs = self.run_select(json.dumps({"sdk": {"version": "latest"}}), "") + self.assertNotEqual(code, 0) + self.assertEqual(outputs, []) + self.assertIn( + "::error::The global.json sdk.version must start with an X.Y line", self.last_stdout + ) + def test_comments_are_read_as_the_dotnet_host_reads_them(self) -> None: """The dotnet host accepts comments, so a file holding them still selects its line or the fallback.""" fallback = [f"dotnet-version={baseline_line()[0]}.x"] @@ -3239,11 +3357,7 @@ def test_each_python_job_reaches_the_selection(self) -> None: jobs = job_texts(validate) builder = jobs["test-matrix"] checkout = yaml_step(builder, "Checkout code step") - self.assertEqual( - "${{ inputs.test-matrix-file != '' || inputs.python-versions == '' || inputs.dotnet-versions != '' }}", - yaml_value(checkout, "if"), - ) - self.assertIn('"/.python-version\\n', yaml_value(checkout, "with", "sparse-checkout") or "") + self.assertIsNone(yaml_value(checkout, "if")) resolved = "${{ inputs.python-versions || format('[\"{0}\"]', steps.python-version.outputs.version) }}" for job, steps, condition in ( ( From d6e2b605c9d40b0b374702750f5373a705902d3b Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Thu, 3 Dec 2026 08:53:32 -0800 Subject: [PATCH 5/7] Name the Package Consume Hook in the Hook Table (#4619) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Names the optional `package-consume` hook in the `build-release-task.yml` row of the hook table in `docs/reusable-workflows.md`, with its default (none) and the condition that skips it (a caller carrying its own `build-nuget` hook). The row had omitted it since #4612, found by the local strict review of the develop -> main promotion. Two recorded local passes ran. The first found the "after build-nuget's own check" wording ambiguous, fixed in the second commit. The second found nothing. 🤖 Generated with [Claude Code](https://claude.com/claude-code) ## Summary by CodeRabbit * **Documentation** * Updated the reusable workflow guide to list `package-consume` as an optional release-task hook. It runs after the default package-consume check and is skipped when a caller provides a custom `build-nuget` hook. The guide now reflects these conditions for configuring the hook, including its relationship to the default check and the custom-hook behavior. --------- Co-authored-by: Claude Sonnet 5.5 --- docs/reusable-workflows.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/reusable-workflows.md b/docs/reusable-workflows.md index eab0e6971..6545bd982 100644 --- a/docs/reusable-workflows.md +++ b/docs/reusable-workflows.md @@ -89,7 +89,7 @@ The target set. A row exists once its hub task ships, and until then the row is | `merge-bot-task.yml` | none, extra bot rules are a `with:` input | not applicable | | `validate-task.yml` | `validate` (a repo's own domain checks, beyond the fleet doc-lint block and the generic unit-test jobs), `install-test-deps` (a `test-matrix` leg's dependency install and per-leg checks). Also `pre-test`, for system tools the .NET tests need | no-op for `validate`, none for `install-test-deps`, which is required where `test-matrix` or `test-matrix-file` is set. None for `pre-test` | | `get-version-task.yml`, `publish-plan-task.yml` | none | not applicable | -| `build-release-task.yml` | `dotnet-publish`, `build-nuget`, `build-pypi`, `build-release-asset` | `dotnet-publish-default`, `nuget-build-default` followed by `package-consume-nuget`, `pypi-build-default` followed by `package-consume-pypi`, none for `build-release-asset`, which is required where `enable_release_asset` is set | +| `build-release-task.yml` | `dotnet-publish`, `build-nuget`, `build-pypi`, `build-release-asset`, `package-consume` (optional, run once after the hub default's package consume check, and skipped where the caller carries its own `build-nuget` hook) | `dotnet-publish-default`, `nuget-build-default` followed by `package-consume-nuget`, `pypi-build-default` followed by `package-consume-pypi`, none for `build-release-asset`, which is required where `enable_release_asset` is set, and none for `package-consume` | | `build-docker-task.yml` | `docker-prepare` (extra tags, build-args, matrix), `docker-build-base` | vanilla single-target from `image`, base build required when `build-base` | | `publish-docker-readme-task.yml` | `docker-readme-transform` | publish `Docker/README.md` or `README.md` as-is | | `check-upstream-version-task.yml` | `resolve-upstream` | none, required | From c79fb1a847585563511f55b771293893620305b6 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Thu, 3 Dec 2026 09:35:43 -0800 Subject: [PATCH 6/7] Neutralize Workflow Commands in NuGet Consume Output (#4620) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Breaks a line-leading workflow command in the child output the NuGet consume check prints, as the PyPI check already does with the byte-identical `neutralize()`. Without it a restore, build target, or loaded assembly could emit a line the runner parses as a command. A hosted review of the develop -> main promotion (#4618) raised the parity gap. The unit test mirrors the PyPI twin's. Two recorded local passes ran. The first found the test weaker than its twin, fixed in the last commit. The second found nothing. Declined as parity with the PyPI twin and outside this change: the regex's whitespace class against the runner's trim, the legacy `##[` command form, and `project_properties` printing raw msbuild output (all shared or not covered by the twin). 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Sonnet 5.5 --- .../package-consume-nuget/package_consume_nuget.py | 7 ++++++- tests/test_package_consume_nuget.py | 11 +++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/.github/actions/package-consume-nuget/package_consume_nuget.py b/.github/actions/package-consume-nuget/package_consume_nuget.py index ed4b22938..6a66f0107 100755 --- a/.github/actions/package-consume-nuget/package_consume_nuget.py +++ b/.github/actions/package-consume-nuget/package_consume_nuget.py @@ -83,6 +83,11 @@ def escape_command(value: str) -> str: return value.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A") +def neutralize(text: str) -> str: + """Break a workflow command that leads a line, indented or not, since the runner trims leading whitespace before it parses one.""" + return re.sub(r"(?m)^([ \t]*)::", r"\1: :", text) + + def normalize_tfm(value: str) -> str: """The short folder-style name of a target framework, however a project or nuspec spells it.""" text = value.strip().lower() @@ -354,7 +359,7 @@ def run( check=False, timeout=COMMAND_TIMEOUT_SECONDS, ) - print(result.stdout + result.stderr, end="") + print(neutralize(result.stdout + result.stderr), end="") return result diff --git a/tests/test_package_consume_nuget.py b/tests/test_package_consume_nuget.py index 8a59909fe..896d3468c 100755 --- a/tests/test_package_consume_nuget.py +++ b/tests/test_package_consume_nuget.py @@ -242,6 +242,17 @@ def test_a_failure_is_an_escaped_annotation_and_a_table_row(self) -> None: self.assertEqual(len(report.table().splitlines()), 3) +class OutputTests(unittest.TestCase): + def test_a_line_leading_workflow_command_in_child_output_is_broken(self) -> None: + out = pcn.neutralize( + "ok\n::error::forged\n ::notice::indented\nmid ::x\n::stop-commands::t" + ) + self.assertFalse(any(line.lstrip().startswith("::") for line in out.splitlines())) + self.assertIn(" : :notice::indented", out) + self.assertIn("mid ::x", out) + self.assertIn(": :error::forged", out) + + class PackageSelectionTests(unittest.TestCase): def test_a_referenced_project_package_does_not_hide_the_projects_own(self) -> None: with tempfile.TemporaryDirectory() as name: From 901c575c8538d9a12f2e37237663176eb52b83c2 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Thu, 3 Dec 2026 10:59:09 -0800 Subject: [PATCH 7/7] Run Each .NET Leg over Only the Test Projects Declaring Its Line (#4621) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Part of #4609 ## Summary - A timed-out `uv export` in the PyPI consume check now records a failed `test dependencies` row naming the timeout. The install, version and import checks still run, the tests row for each target fails naming the missing dependencies, the summary is written, and the step fails. - The NuGet twin had no per-leg gap, since its per-framework loop already catches `TimeoutExpired`. Its one uncaught shape was the `dotnet msbuild` property read, which now prints an `::error::` annotation and exits 1. - Each `.NET X.Y` leg runs `dotnet test --framework netX.Y --project P` only for tracked `*Tests*.csproj` projects whose `TargetFramework` or `TargetFrameworks` declares `netX.Y`. Entries are trimmed and compared without case. Other projects are skipped with a log line naming them, and a leg where none declares its line fails with an `::error::`. - Decision to note: the `dotnet-workspaces` hop is dropped from the unit-test job, because with `solutions` false it listed the same `*Tests*.csproj` set the step now enumerates itself. A root holding one solution therefore now runs every tracked `*Tests*.csproj`, not only the projects inside that solution. - Documented in the `dotnet-versions` input description, WORKFLOW.md D1.6 and D1.9, and docs/reusable-workflows.md. ## Local filter evidence Real `dotnet msbuild` property reads, `dotnet test` stubbed, three constructed projects: ATests declares `net10.0`, BTests declares `net10.0;net11.0`, CTests declares `net10.0-windows; NET11.0`. ```text === leg 11.0 Skipping ATests/ATests.csproj, which does not declare net11.0. STUB dotnet test --framework net11.0 --project BTests/BTests.csproj STUB dotnet test --framework net11.0 --project CTests/CTests.csproj exit 0 === leg 10.0 Skipping CTests/CTests.csproj, which does not declare net10.0. STUB dotnet test --framework net10.0 --project ATests/ATests.csproj STUB dotnet test --framework net10.0 --project BTests/BTests.csproj exit 0 === leg 9.0 Skipping ATests/ATests.csproj, which does not declare net9.0. Skipping BTests/BTests.csproj, which does not declare net9.0. Skipping CTests/CTests.csproj, which does not declare net9.0. ::error::No test project declares net9.0 in its TargetFramework or TargetFrameworks, so the .NET 9.0 leg would run no tests. exit 1 ``` ## Local review Three recorded local strict passes. The first found eight issues and the second one, all fixed in this branch. The third found none. Deferred, not blocking: `jq -e` reads unparseable `dotnet msbuild` output the same as no match, so a project could be skipped with a misleading reason. No real source of non-JSON output was found. The `comments` label is applied because the change adds why-comments. Closes nothing: the parent issue stays open for the promotion. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Sonnet 5.5 --- .../references/d-guarantees.md | 4 +- .../.source-digests/workflow-ci-contract | 2 +- .../references/d-guarantees.md | 4 +- .../package_consume_nuget.py | 37 ++-- .../package_consume_pypi.py | 29 ++- .../references/d-guarantees.md | 4 +- .github/workflows/validate-task.yml | 39 +++-- WORKFLOW.md | 4 +- docs/reusable-workflows.md | 2 +- tests/test_package_consume_nuget.py | 14 ++ tests/test_package_consume_pypi.py | 65 ++++++- tests/test_release_guards.py | 165 +++++++++++++++--- 12 files changed, 291 insertions(+), 78 deletions(-) diff --git a/.agents/skills/workflow-ci-contract/references/d-guarantees.md b/.agents/skills/workflow-ci-contract/references/d-guarantees.md index f7e3097b7..7496f7a98 100644 --- a/.agents/skills/workflow-ci-contract/references/d-guarantees.md +++ b/.agents/skills/workflow-ci-contract/references/d-guarantees.md @@ -15,10 +15,10 @@ The required behaviors, organized by domain. Each is a **MUST**, and its `Output - **D1.3 Smoke never publishes and never uploads.** Input: `smoke: true`. Output: full compile/lint/test, but no registry/image push, no release, and **no** artifact uploads. Every `upload-artifact`, including any aggregation job, is gated on smoke being false. That gate is written `!inputs.smoke` at the workflow layer and `inputs.smoke != 'true'` in a composite action, whose inputs are strings. *Prevents: a PR publishing, and orphaned artifacts churning the storage quota.* - **D1.4 Workflow-file changes are not smoke-built.** Input: a PR changing only `.github/workflows/**`. Output: the paths-filter marks no target, so smoke-build skips. An inclusion list satisfying D1.1 reaches this by leaving workflow paths out of every target's entry. *Implication: a workflow-only change is not smoke-built, but actionlint still validates it in CI.* - **D1.5 One required aggregator gates merge.** Input: any PR. Output: a single aggregator job must **succeed**. It must run under `if: always()`, so a failed or skipped dependency cannot skip the gate itself. It must also `needs:` the validation job, and the `changes` and `smoke-build` jobs too wherever the repo has a smoke build. It must treat a **skipped** smoke build as pass, and **block** on `failure`/`cancelled`. Its name is ruleset-bound: the job `name:` and the ruleset `context:` are the same string and MUST be renamed together, never independently. The workflow holding it MUST trigger on `pull_request`. A gate without a `pull_request` trigger never runs the validator's pull-request-only steps, the prose gate among them. A workflow any other event also triggers yields that name only when `github.event_name == 'pull_request'`, through an expression `name:`. Otherwise a dispatch or push run on a PR's head posts the required context without the PR run's gates. *Prevents: a paths-filter error letting a target-changing PR merge unbuilt.* -- **D1.6 Coverage is reported to Codecov (C# and Python).** Input: a C# or Python repo that has tests for that type. Output: the validation job runs those tests under coverage collection, and a `codecov/codecov-action` step uploads the report. The collection is `dotnet test --coverage --coverage-output-format cobertura --results-directory ./coverage`, leaving `--coverage-output` unset so each test project writes its own report rather than overwriting a shared one. A bare call resolves one workspace from the working directory, so it fails at a root holding none or more than one. Unless the repository root holds exactly one solution or project, the hub's validator therefore runs the collection once per tracked `*Tests*.csproj` with `--project`. It names no solution in that case, since a solution holding no test project fails the run. Or it is `pytest --cov-report=xml` in a Python directory with its own `uv.lock` or `requirements*.txt`, whose own `pyproject.toml` selects what to measure. Or it is `coverage run -m unittest discover -s tests` then `coverage xml` in a `lint-only` one. The upload is **best-effort** (`continue-on-error` and/or `fail_ci_if_error: false`), so a Codecov outage or an absent token never reds the gate. Each leg **fails its test step when the run wrote no report**. The reason is that the best-effort upload reads a missing report exactly as it reads a healthy run. A second reason is that, on the Python leg, `--cov-report=xml` alone selects nothing to measure. The C# leg renames each report to `coverage-.cobertura.xml` before the upload step reads the directory, since `codecov-cli`'s own finder does not match the default name. A repo owning its validator rather than calling the hub's owes that rename itself. `CODECOV_TOKEN` lives in the repo's **actions** and **dependabot** secret stores. The token is in the second because a run triggered by a Dependabot pull request reads the Dependabot store. Without the token there, the upload would otherwise skip silently on every bot pull request. A caller reaching the reusable validator across repositories names the secret it passes (`secrets:` with `CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}`). It does so on its pull request path and its publisher path alike. That is because `secrets: inherit` is documented for a caller in the same organization or enterprise, which a personal account is not. A call by local path stays inside one repository, where the caller's own store is the one the callee reads. So `secrets: inherit` is available there instead of naming each secret. The repo ships a **`.codecov.yml`** at the repository root. It sets the project and patch statuses to **`informational: true`**, so a coverage delta never gates a pull request. A repo whose quality bar requires a threshold may turn that off. The same file excludes intentionally-untested, non-shipped code (an example or benchmark project) from the denominator via `ignore`. Codecov reads its configuration under several names, but `.codecov.yml` is the only one the fleet accepts. So a copy under any other name is drift to rename. Coverage output is a build artifact, so `.gitignore` excludes it. The C# invocation runs under **Microsoft.Testing.Platform**, and the runner declaration, package references, and version floor an MTP-based test project needs are `CODESTYLE.md`'s .NET side. The Python invocation needs **`pytest-cov`** and a coverage selector, which are `CODESTYLE.md`'s Python side. A Python directory declared in the validator's `python-directories` input owes a `tests/` suite whatever its profile, so the validator fails one that has none. N/A for a repo carrying no tests for that type. *Prevents: coverage silently going unreported, and a coverage regression blocking an unrelated pull request.* +- **D1.6 Coverage is reported to Codecov (C# and Python).** Input: a C# or Python repo that has tests for that type. Output: the validation job runs those tests under coverage collection, and a `codecov/codecov-action` step uploads the report. The collection is `dotnet test --coverage --coverage-output-format cobertura --results-directory ./coverage`, leaving `--coverage-output` unset so each test project writes its own report rather than overwriting a shared one. A bare call resolves one workspace from the working directory, so it fails at a root holding none or more than one. The hub's validator therefore runs the collection once per tracked `*Tests*.csproj` that declares the leg's line, with `--project`, whatever the root holds. A test project left out of a root solution, or a library whose name matches the glob, is therefore a test project here. It names no solution, since a solution holding no test project fails the run. Or it is `pytest --cov-report=xml` in a Python directory with its own `uv.lock` or `requirements*.txt`, whose own `pyproject.toml` selects what to measure. Or it is `coverage run -m unittest discover -s tests` then `coverage xml` in a `lint-only` one. The upload is **best-effort** (`continue-on-error` and/or `fail_ci_if_error: false`), so a Codecov outage or an absent token never reds the gate. Each leg **fails its test step when the run wrote no report**. The reason is that the best-effort upload reads a missing report exactly as it reads a healthy run. A second reason is that, on the Python leg, `--cov-report=xml` alone selects nothing to measure. The C# leg renames each report to `coverage-.cobertura.xml` before the upload step reads the directory, since `codecov-cli`'s own finder does not match the default name. A repo owning its validator rather than calling the hub's owes that rename itself. `CODECOV_TOKEN` lives in the repo's **actions** and **dependabot** secret stores. The token is in the second because a run triggered by a Dependabot pull request reads the Dependabot store. Without the token there, the upload would otherwise skip silently on every bot pull request. A caller reaching the reusable validator across repositories names the secret it passes (`secrets:` with `CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}`). It does so on its pull request path and its publisher path alike. That is because `secrets: inherit` is documented for a caller in the same organization or enterprise, which a personal account is not. A call by local path stays inside one repository, where the caller's own store is the one the callee reads. So `secrets: inherit` is available there instead of naming each secret. The repo ships a **`.codecov.yml`** at the repository root. It sets the project and patch statuses to **`informational: true`**, so a coverage delta never gates a pull request. A repo whose quality bar requires a threshold may turn that off. The same file excludes intentionally-untested, non-shipped code (an example or benchmark project) from the denominator via `ignore`. Codecov reads its configuration under several names, but `.codecov.yml` is the only one the fleet accepts. So a copy under any other name is drift to rename. Coverage output is a build artifact, so `.gitignore` excludes it. The C# invocation runs under **Microsoft.Testing.Platform**, and the runner declaration, package references, and version floor an MTP-based test project needs are `CODESTYLE.md`'s .NET side. The Python invocation needs **`pytest-cov`** and a coverage selector, which are `CODESTYLE.md`'s Python side. A Python directory declared in the validator's `python-directories` input owes a `tests/` suite whatever its profile, so the validator fails one that has none. N/A for a repo carrying no tests for that type. *Prevents: coverage silently going unreported, and a coverage regression blocking an unrelated pull request.* - **D1.7 A built NuGet package is consumed before it publishes.** Input: a repo whose `build-nuget` job runs the hub's default leaf, in a smoke run or a publish run alike. Output: after the leaf packs, the job restores, builds, and runs a throwaway console project against that exact `.nupkg`. It does so once per target framework the project declares. Each consumer lives outside the checkout, so the caller's `global.json` and `Directory.Build.props` do not apply. Its `nuget.config` resolves the package ID, and the ID of each sibling package in the folder holding the build output, only from that folder. Every other ID resolves from nuget.org. Its package cache is its own, so neither a cached nor a published copy can stand in for the artifact under test. The consumer loads the package assembly and calls `GetExportedTypes()`. The check asserts from `obj/project.assets.json` that the package resolved from the `lib//` folder of the consumer's own framework. It also asserts that the loaded assembly's `TargetFrameworkAttribute` matches that folder. A `netstandard` framework is consumed under the SDK line `global.json` selects, or the newest declared line where there is none. It is asserted against the folder it resolved. A framework the check does not consume is reported skipped. Examples are .NET Framework, `netcoreapp3.1`, and a platform-specific `netX.Y-windows`. The attribute row of a `netstandard` consumer resolving such a folder is skipped too. Four static assertions join them. The package's `lib//` folders equal the declared frameworks. The nuspec `` equals the build version. The nuspec holds a dependency group per framework. A symbol package exists where the project enables symbols. Every declared `netX.Y` and `netstandard` framework is consumed and reported with one summary row per assertion. A failed step ends that framework's rows rather than the run. The job fails at the end if any failed. The check covers a library package, whose assemblies sit under `lib//`. The check uploads nothing, so it honors D1.3. It runs inside the build job, so a failure blocks the publish job that `needs:` that build. A caller's own `build-nuget` hook replaces the whole leaf and is outside the check. A caller's own `.github/actions/package-consume/action.yml` runs once after the default check. It receives the declared frameworks as JSON beside the package ID, version, and package folder. *Prevents: a defect that exists only in the packed form shipping. One example is one target framework's assembly packed under every `lib//` folder while the tests, which reach the library through a project reference, stay green.* - **D1.8 A built PyPI package is consumed before it publishes.** Input: a repo whose `build-pypi` job runs the hub's default leaf, in a smoke run or a publish run alike. Output: after the leaf builds, the job installs the wheel and, separately, the sdist into a fresh `uv venv`. It does so for each line of the `python-versions` input of `build-release-task.yml`. Empty runs the one line the root `.python-version` selects. Where there is none it runs the hub's fallback line. A caller that sets `python-versions` for both `validate-task.yml` and `build-release-task.yml` passes the same value to each. So the lines its tests run under are the lines its artifact is consumed under. Each environment lives outside the checkout. It installs the artifact, then the project's locked dependency groups from `uv.lock` without the project itself. The check asserts that `importlib.metadata` reports the version the leaf computed. It also asserts that every top-level name the installed distribution provides imports from the environment's site-packages, not the source tree. A distribution providing none, such as one of scripts only, reports that row skipped. It then runs the caller's `tests/` folder against the installed copy with pytest in `importlib` import mode. That run has the source tree off `sys.path` and the project's `pythonpath` setting cleared. Its working directory is outside the project. So the caller's suite must not read a path relative to the project root, or a tool setting read from the working directory. It must import a sibling helper as part of a package. The project directory holds its own `uv.lock`. A project with no `tests/` folder, or a run collecting no tests, is reported skipped rather than passed. Every line and artifact reports one summary row per assertion. A failed environment, install, or metadata read ends that artifact's rows rather than the run. The job fails at the end if any failed. The check uploads nothing, so it honors D1.3. It runs inside the build job, so a failure blocks the publish job that `needs:` that build. A caller's own `build-pypi` hook replaces the whole leaf and is outside the check. *Prevents: a defect that exists only in the built form shipping. One example is a module left out of the wheel while the tests, which import it from the source tree, stay green.* -- **D1.9 Each declared test line runs as its own named unit-test leg.** Input: a repo declaring .NET lines in `dotnet-versions` of `validate-task.yml`, Python lines in `python-versions`, or both. Output: each declared .NET line runs as a `Unit test job (.NET X.Y)` leg running `dotnet test --framework netX.Y` under that line's runtime. Each declared Python line runs as a `Unit test job (Python X.Y)` leg, or as the caller's named `test-matrix` legs where it sets one. A caller declaring neither runs the one line each of `global.json` and `.python-version` selects. The hub's fallback line stands in where a file is absent. The .NET legs run only where a `*Tests*.csproj` exists. The Python legs run only where a Python directory resolves. So a repo holding one kind reports no leg of the other. Each leg uploads its own coverage report, and the .NET upload carries a per-line flag beside `dotnet`. A failing leg does not cancel its siblings. *Prevents: a failing target framework or interpreter hiding inside a combined run naming none of them. A .NET-only repo reporting a Python line it never ran is the other.* +- **D1.9 Each declared test line runs as its own named unit-test leg.** Input: a repo declaring .NET lines in `dotnet-versions` of `validate-task.yml`, Python lines in `python-versions`, or both. Output: each declared .NET line runs as a `Unit test job (.NET X.Y)` leg running `dotnet test --framework netX.Y` under that line's runtime. A leg runs only the tracked `*Tests*.csproj` projects declaring `netX.Y` in their `TargetFramework` or `TargetFrameworks`, read with `dotnet msbuild`, and skips and names the rest. A leg where no test project declares its line fails, so a declared line never passes by running nothing. Each declared Python line runs as a `Unit test job (Python X.Y)` leg, or as the caller's named `test-matrix` legs where it sets one. A caller declaring neither runs the one line each of `global.json` and `.python-version` selects. The hub's fallback line stands in where a file is absent. The .NET legs run only where a `*Tests*.csproj` exists. The Python legs run only where a Python directory resolves. So a repo holding one kind reports no leg of the other. Each leg uploads its own coverage report, and the .NET upload carries a per-line flag beside `dotnet`. A failing leg does not cancel its siblings. *Prevents: a failing target framework or interpreter hiding inside a combined run naming none of them. A .NET-only repo reporting a Python line it never ran is the other.* ### D2 - Input/State Validation at Entry diff --git a/.claude-plugin/fleet-skills/.source-digests/workflow-ci-contract b/.claude-plugin/fleet-skills/.source-digests/workflow-ci-contract index 11468940c..9c48c68be 100644 --- a/.claude-plugin/fleet-skills/.source-digests/workflow-ci-contract +++ b/.claude-plugin/fleet-skills/.source-digests/workflow-ci-contract @@ -1 +1 @@ -48bde8411845cb66 +75fec62441fc8729 diff --git a/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/d-guarantees.md b/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/d-guarantees.md index f7e3097b7..7496f7a98 100644 --- a/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/d-guarantees.md +++ b/.claude-plugin/fleet-skills/skills/workflow-ci-contract/references/d-guarantees.md @@ -15,10 +15,10 @@ The required behaviors, organized by domain. Each is a **MUST**, and its `Output - **D1.3 Smoke never publishes and never uploads.** Input: `smoke: true`. Output: full compile/lint/test, but no registry/image push, no release, and **no** artifact uploads. Every `upload-artifact`, including any aggregation job, is gated on smoke being false. That gate is written `!inputs.smoke` at the workflow layer and `inputs.smoke != 'true'` in a composite action, whose inputs are strings. *Prevents: a PR publishing, and orphaned artifacts churning the storage quota.* - **D1.4 Workflow-file changes are not smoke-built.** Input: a PR changing only `.github/workflows/**`. Output: the paths-filter marks no target, so smoke-build skips. An inclusion list satisfying D1.1 reaches this by leaving workflow paths out of every target's entry. *Implication: a workflow-only change is not smoke-built, but actionlint still validates it in CI.* - **D1.5 One required aggregator gates merge.** Input: any PR. Output: a single aggregator job must **succeed**. It must run under `if: always()`, so a failed or skipped dependency cannot skip the gate itself. It must also `needs:` the validation job, and the `changes` and `smoke-build` jobs too wherever the repo has a smoke build. It must treat a **skipped** smoke build as pass, and **block** on `failure`/`cancelled`. Its name is ruleset-bound: the job `name:` and the ruleset `context:` are the same string and MUST be renamed together, never independently. The workflow holding it MUST trigger on `pull_request`. A gate without a `pull_request` trigger never runs the validator's pull-request-only steps, the prose gate among them. A workflow any other event also triggers yields that name only when `github.event_name == 'pull_request'`, through an expression `name:`. Otherwise a dispatch or push run on a PR's head posts the required context without the PR run's gates. *Prevents: a paths-filter error letting a target-changing PR merge unbuilt.* -- **D1.6 Coverage is reported to Codecov (C# and Python).** Input: a C# or Python repo that has tests for that type. Output: the validation job runs those tests under coverage collection, and a `codecov/codecov-action` step uploads the report. The collection is `dotnet test --coverage --coverage-output-format cobertura --results-directory ./coverage`, leaving `--coverage-output` unset so each test project writes its own report rather than overwriting a shared one. A bare call resolves one workspace from the working directory, so it fails at a root holding none or more than one. Unless the repository root holds exactly one solution or project, the hub's validator therefore runs the collection once per tracked `*Tests*.csproj` with `--project`. It names no solution in that case, since a solution holding no test project fails the run. Or it is `pytest --cov-report=xml` in a Python directory with its own `uv.lock` or `requirements*.txt`, whose own `pyproject.toml` selects what to measure. Or it is `coverage run -m unittest discover -s tests` then `coverage xml` in a `lint-only` one. The upload is **best-effort** (`continue-on-error` and/or `fail_ci_if_error: false`), so a Codecov outage or an absent token never reds the gate. Each leg **fails its test step when the run wrote no report**. The reason is that the best-effort upload reads a missing report exactly as it reads a healthy run. A second reason is that, on the Python leg, `--cov-report=xml` alone selects nothing to measure. The C# leg renames each report to `coverage-.cobertura.xml` before the upload step reads the directory, since `codecov-cli`'s own finder does not match the default name. A repo owning its validator rather than calling the hub's owes that rename itself. `CODECOV_TOKEN` lives in the repo's **actions** and **dependabot** secret stores. The token is in the second because a run triggered by a Dependabot pull request reads the Dependabot store. Without the token there, the upload would otherwise skip silently on every bot pull request. A caller reaching the reusable validator across repositories names the secret it passes (`secrets:` with `CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}`). It does so on its pull request path and its publisher path alike. That is because `secrets: inherit` is documented for a caller in the same organization or enterprise, which a personal account is not. A call by local path stays inside one repository, where the caller's own store is the one the callee reads. So `secrets: inherit` is available there instead of naming each secret. The repo ships a **`.codecov.yml`** at the repository root. It sets the project and patch statuses to **`informational: true`**, so a coverage delta never gates a pull request. A repo whose quality bar requires a threshold may turn that off. The same file excludes intentionally-untested, non-shipped code (an example or benchmark project) from the denominator via `ignore`. Codecov reads its configuration under several names, but `.codecov.yml` is the only one the fleet accepts. So a copy under any other name is drift to rename. Coverage output is a build artifact, so `.gitignore` excludes it. The C# invocation runs under **Microsoft.Testing.Platform**, and the runner declaration, package references, and version floor an MTP-based test project needs are `CODESTYLE.md`'s .NET side. The Python invocation needs **`pytest-cov`** and a coverage selector, which are `CODESTYLE.md`'s Python side. A Python directory declared in the validator's `python-directories` input owes a `tests/` suite whatever its profile, so the validator fails one that has none. N/A for a repo carrying no tests for that type. *Prevents: coverage silently going unreported, and a coverage regression blocking an unrelated pull request.* +- **D1.6 Coverage is reported to Codecov (C# and Python).** Input: a C# or Python repo that has tests for that type. Output: the validation job runs those tests under coverage collection, and a `codecov/codecov-action` step uploads the report. The collection is `dotnet test --coverage --coverage-output-format cobertura --results-directory ./coverage`, leaving `--coverage-output` unset so each test project writes its own report rather than overwriting a shared one. A bare call resolves one workspace from the working directory, so it fails at a root holding none or more than one. The hub's validator therefore runs the collection once per tracked `*Tests*.csproj` that declares the leg's line, with `--project`, whatever the root holds. A test project left out of a root solution, or a library whose name matches the glob, is therefore a test project here. It names no solution, since a solution holding no test project fails the run. Or it is `pytest --cov-report=xml` in a Python directory with its own `uv.lock` or `requirements*.txt`, whose own `pyproject.toml` selects what to measure. Or it is `coverage run -m unittest discover -s tests` then `coverage xml` in a `lint-only` one. The upload is **best-effort** (`continue-on-error` and/or `fail_ci_if_error: false`), so a Codecov outage or an absent token never reds the gate. Each leg **fails its test step when the run wrote no report**. The reason is that the best-effort upload reads a missing report exactly as it reads a healthy run. A second reason is that, on the Python leg, `--cov-report=xml` alone selects nothing to measure. The C# leg renames each report to `coverage-.cobertura.xml` before the upload step reads the directory, since `codecov-cli`'s own finder does not match the default name. A repo owning its validator rather than calling the hub's owes that rename itself. `CODECOV_TOKEN` lives in the repo's **actions** and **dependabot** secret stores. The token is in the second because a run triggered by a Dependabot pull request reads the Dependabot store. Without the token there, the upload would otherwise skip silently on every bot pull request. A caller reaching the reusable validator across repositories names the secret it passes (`secrets:` with `CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}`). It does so on its pull request path and its publisher path alike. That is because `secrets: inherit` is documented for a caller in the same organization or enterprise, which a personal account is not. A call by local path stays inside one repository, where the caller's own store is the one the callee reads. So `secrets: inherit` is available there instead of naming each secret. The repo ships a **`.codecov.yml`** at the repository root. It sets the project and patch statuses to **`informational: true`**, so a coverage delta never gates a pull request. A repo whose quality bar requires a threshold may turn that off. The same file excludes intentionally-untested, non-shipped code (an example or benchmark project) from the denominator via `ignore`. Codecov reads its configuration under several names, but `.codecov.yml` is the only one the fleet accepts. So a copy under any other name is drift to rename. Coverage output is a build artifact, so `.gitignore` excludes it. The C# invocation runs under **Microsoft.Testing.Platform**, and the runner declaration, package references, and version floor an MTP-based test project needs are `CODESTYLE.md`'s .NET side. The Python invocation needs **`pytest-cov`** and a coverage selector, which are `CODESTYLE.md`'s Python side. A Python directory declared in the validator's `python-directories` input owes a `tests/` suite whatever its profile, so the validator fails one that has none. N/A for a repo carrying no tests for that type. *Prevents: coverage silently going unreported, and a coverage regression blocking an unrelated pull request.* - **D1.7 A built NuGet package is consumed before it publishes.** Input: a repo whose `build-nuget` job runs the hub's default leaf, in a smoke run or a publish run alike. Output: after the leaf packs, the job restores, builds, and runs a throwaway console project against that exact `.nupkg`. It does so once per target framework the project declares. Each consumer lives outside the checkout, so the caller's `global.json` and `Directory.Build.props` do not apply. Its `nuget.config` resolves the package ID, and the ID of each sibling package in the folder holding the build output, only from that folder. Every other ID resolves from nuget.org. Its package cache is its own, so neither a cached nor a published copy can stand in for the artifact under test. The consumer loads the package assembly and calls `GetExportedTypes()`. The check asserts from `obj/project.assets.json` that the package resolved from the `lib//` folder of the consumer's own framework. It also asserts that the loaded assembly's `TargetFrameworkAttribute` matches that folder. A `netstandard` framework is consumed under the SDK line `global.json` selects, or the newest declared line where there is none. It is asserted against the folder it resolved. A framework the check does not consume is reported skipped. Examples are .NET Framework, `netcoreapp3.1`, and a platform-specific `netX.Y-windows`. The attribute row of a `netstandard` consumer resolving such a folder is skipped too. Four static assertions join them. The package's `lib//` folders equal the declared frameworks. The nuspec `` equals the build version. The nuspec holds a dependency group per framework. A symbol package exists where the project enables symbols. Every declared `netX.Y` and `netstandard` framework is consumed and reported with one summary row per assertion. A failed step ends that framework's rows rather than the run. The job fails at the end if any failed. The check covers a library package, whose assemblies sit under `lib//`. The check uploads nothing, so it honors D1.3. It runs inside the build job, so a failure blocks the publish job that `needs:` that build. A caller's own `build-nuget` hook replaces the whole leaf and is outside the check. A caller's own `.github/actions/package-consume/action.yml` runs once after the default check. It receives the declared frameworks as JSON beside the package ID, version, and package folder. *Prevents: a defect that exists only in the packed form shipping. One example is one target framework's assembly packed under every `lib//` folder while the tests, which reach the library through a project reference, stay green.* - **D1.8 A built PyPI package is consumed before it publishes.** Input: a repo whose `build-pypi` job runs the hub's default leaf, in a smoke run or a publish run alike. Output: after the leaf builds, the job installs the wheel and, separately, the sdist into a fresh `uv venv`. It does so for each line of the `python-versions` input of `build-release-task.yml`. Empty runs the one line the root `.python-version` selects. Where there is none it runs the hub's fallback line. A caller that sets `python-versions` for both `validate-task.yml` and `build-release-task.yml` passes the same value to each. So the lines its tests run under are the lines its artifact is consumed under. Each environment lives outside the checkout. It installs the artifact, then the project's locked dependency groups from `uv.lock` without the project itself. The check asserts that `importlib.metadata` reports the version the leaf computed. It also asserts that every top-level name the installed distribution provides imports from the environment's site-packages, not the source tree. A distribution providing none, such as one of scripts only, reports that row skipped. It then runs the caller's `tests/` folder against the installed copy with pytest in `importlib` import mode. That run has the source tree off `sys.path` and the project's `pythonpath` setting cleared. Its working directory is outside the project. So the caller's suite must not read a path relative to the project root, or a tool setting read from the working directory. It must import a sibling helper as part of a package. The project directory holds its own `uv.lock`. A project with no `tests/` folder, or a run collecting no tests, is reported skipped rather than passed. Every line and artifact reports one summary row per assertion. A failed environment, install, or metadata read ends that artifact's rows rather than the run. The job fails at the end if any failed. The check uploads nothing, so it honors D1.3. It runs inside the build job, so a failure blocks the publish job that `needs:` that build. A caller's own `build-pypi` hook replaces the whole leaf and is outside the check. *Prevents: a defect that exists only in the built form shipping. One example is a module left out of the wheel while the tests, which import it from the source tree, stay green.* -- **D1.9 Each declared test line runs as its own named unit-test leg.** Input: a repo declaring .NET lines in `dotnet-versions` of `validate-task.yml`, Python lines in `python-versions`, or both. Output: each declared .NET line runs as a `Unit test job (.NET X.Y)` leg running `dotnet test --framework netX.Y` under that line's runtime. Each declared Python line runs as a `Unit test job (Python X.Y)` leg, or as the caller's named `test-matrix` legs where it sets one. A caller declaring neither runs the one line each of `global.json` and `.python-version` selects. The hub's fallback line stands in where a file is absent. The .NET legs run only where a `*Tests*.csproj` exists. The Python legs run only where a Python directory resolves. So a repo holding one kind reports no leg of the other. Each leg uploads its own coverage report, and the .NET upload carries a per-line flag beside `dotnet`. A failing leg does not cancel its siblings. *Prevents: a failing target framework or interpreter hiding inside a combined run naming none of them. A .NET-only repo reporting a Python line it never ran is the other.* +- **D1.9 Each declared test line runs as its own named unit-test leg.** Input: a repo declaring .NET lines in `dotnet-versions` of `validate-task.yml`, Python lines in `python-versions`, or both. Output: each declared .NET line runs as a `Unit test job (.NET X.Y)` leg running `dotnet test --framework netX.Y` under that line's runtime. A leg runs only the tracked `*Tests*.csproj` projects declaring `netX.Y` in their `TargetFramework` or `TargetFrameworks`, read with `dotnet msbuild`, and skips and names the rest. A leg where no test project declares its line fails, so a declared line never passes by running nothing. Each declared Python line runs as a `Unit test job (Python X.Y)` leg, or as the caller's named `test-matrix` legs where it sets one. A caller declaring neither runs the one line each of `global.json` and `.python-version` selects. The hub's fallback line stands in where a file is absent. The .NET legs run only where a `*Tests*.csproj` exists. The Python legs run only where a Python directory resolves. So a repo holding one kind reports no leg of the other. Each leg uploads its own coverage report, and the .NET upload carries a per-line flag beside `dotnet`. A failing leg does not cancel its siblings. *Prevents: a failing target framework or interpreter hiding inside a combined run naming none of them. A .NET-only repo reporting a Python line it never ran is the other.* ### D2 - Input/State Validation at Entry diff --git a/.github/actions/package-consume-nuget/package_consume_nuget.py b/.github/actions/package-consume-nuget/package_consume_nuget.py index 6a66f0107..ea725969d 100755 --- a/.github/actions/package-consume-nuget/package_consume_nuget.py +++ b/.github/actions/package-consume-nuget/package_consume_nuget.py @@ -173,21 +173,28 @@ def global_json_line(path: Path) -> str | None: def project_properties(project: str) -> dict[str, str]: # The leaf packs Release on main and Debug elsewhere, and a property can be conditioned on it. configuration = "Release" if os.environ.get("BRANCH") == "main" else "Debug" - result = subprocess.run( - [ - "dotnet", - "msbuild", - project, - "-nologo", - f"-property:Configuration={configuration}", - "-getProperty:" + ",".join(PROPERTIES), - ], - capture_output=True, - text=True, - encoding="utf-8", - check=False, - timeout=COMMAND_TIMEOUT_SECONDS, - ) + try: + result = subprocess.run( + [ + "dotnet", + "msbuild", + project, + "-nologo", + f"-property:Configuration={configuration}", + "-getProperty:" + ",".join(PROPERTIES), + ], + capture_output=True, + text=True, + encoding="utf-8", + check=False, + timeout=COMMAND_TIMEOUT_SECONDS, + ) + except subprocess.TimeoutExpired as error: + # An uncaught timeout is a bare traceback, so it is reported as the annotated failure it is. + print( + f"::error::{escape_command(f'Reading {project} properties timed out after {COMMAND_TIMEOUT_SECONDS} seconds.')}" + ) + raise SystemExit(1) from error if result.returncode != 0: raise SystemExit(f"Reading {project}'s properties failed:\n{result.stdout}{result.stderr}") return {k: str(v) for k, v in json.loads(result.stdout)["Properties"].items()} diff --git a/.github/actions/package-consume-pypi/package_consume_pypi.py b/.github/actions/package-consume-pypi/package_consume_pypi.py index 56aa287ad..327db8e8c 100755 --- a/.github/actions/package-consume-pypi/package_consume_pypi.py +++ b/.github/actions/package-consume-pypi/package_consume_pypi.py @@ -258,7 +258,7 @@ def consume( name: str, version: str, project: Path, - requirements: Sequence[str], + requirements: Sequence[str] | None, work: Path, env: Mapping[str, str], report: Report, @@ -275,8 +275,9 @@ def consume( if not report.add(target, "install", installed.returncode == 0, artifact.name): return # The project is excluded from the groups, so only its dependencies and tools are added to the artifact's. - groups = run(["uv", "pip", "install", "--python", python, *requirements], project, env) - report.add(target, "test dependencies", groups.returncode == 0, "locked groups, no project") + if requirements is not None: + groups = run(["uv", "pip", "install", "--python", python, *requirements], project, env) + report.add(target, "test dependencies", groups.returncode == 0, "locked groups, no project") files = run([python, "-I", "-c", FILES_PROBE, name], work, env) metadata = probe_rows(files.stdout) @@ -321,6 +322,15 @@ def consume( if not tests.is_dir(): report.add(target, "tests", True, f"{tests.name} folder is absent", skipped=True) return + if requirements is None: + # A pass would claim the tests ran against dependencies that were never installed. + report.add( + target, + "tests", + False, + "not run, the locked test dependencies could not be exported", + ) + return # The working directory is outside the project, so the source tree is not on sys.path. cache = f"cache_dir={work / '.pytest_cache'}" outcome = run([python, "-m", "pytest", str(tests), *PYTEST_ARGUMENTS, "-o", cache], work, env) @@ -335,11 +345,18 @@ def check(project: Path, version: str, lines: Sequence[str], work: Path) -> int: env = clean_environment() name = project_name(project / "pyproject.toml") artifacts = find_artifacts(project / "dist") + requirements: list[str] | None try: requirements = export_requirements(project, work / "requirements.txt", env) - except OSError as error: - report.add("all", "test dependencies", False, str(error)) - requirements = [] + except (OSError, subprocess.TimeoutExpired) as error: + # A timed-out export must still reach the per-artifact checks and the summary, and the step still fails. + detail = ( + f"uv export timed out after {COMMAND_TIMEOUT_SECONDS} seconds" + if isinstance(error, subprocess.TimeoutExpired) + else str(error) + ) + report.add("all", "test dependencies", False, detail) + requirements = None for line in lines: print(f"::group::{escape_command(f'consume py{line}')}") try: diff --git a/.github/skills/workflow-ci-contract/references/d-guarantees.md b/.github/skills/workflow-ci-contract/references/d-guarantees.md index f7e3097b7..7496f7a98 100644 --- a/.github/skills/workflow-ci-contract/references/d-guarantees.md +++ b/.github/skills/workflow-ci-contract/references/d-guarantees.md @@ -15,10 +15,10 @@ The required behaviors, organized by domain. Each is a **MUST**, and its `Output - **D1.3 Smoke never publishes and never uploads.** Input: `smoke: true`. Output: full compile/lint/test, but no registry/image push, no release, and **no** artifact uploads. Every `upload-artifact`, including any aggregation job, is gated on smoke being false. That gate is written `!inputs.smoke` at the workflow layer and `inputs.smoke != 'true'` in a composite action, whose inputs are strings. *Prevents: a PR publishing, and orphaned artifacts churning the storage quota.* - **D1.4 Workflow-file changes are not smoke-built.** Input: a PR changing only `.github/workflows/**`. Output: the paths-filter marks no target, so smoke-build skips. An inclusion list satisfying D1.1 reaches this by leaving workflow paths out of every target's entry. *Implication: a workflow-only change is not smoke-built, but actionlint still validates it in CI.* - **D1.5 One required aggregator gates merge.** Input: any PR. Output: a single aggregator job must **succeed**. It must run under `if: always()`, so a failed or skipped dependency cannot skip the gate itself. It must also `needs:` the validation job, and the `changes` and `smoke-build` jobs too wherever the repo has a smoke build. It must treat a **skipped** smoke build as pass, and **block** on `failure`/`cancelled`. Its name is ruleset-bound: the job `name:` and the ruleset `context:` are the same string and MUST be renamed together, never independently. The workflow holding it MUST trigger on `pull_request`. A gate without a `pull_request` trigger never runs the validator's pull-request-only steps, the prose gate among them. A workflow any other event also triggers yields that name only when `github.event_name == 'pull_request'`, through an expression `name:`. Otherwise a dispatch or push run on a PR's head posts the required context without the PR run's gates. *Prevents: a paths-filter error letting a target-changing PR merge unbuilt.* -- **D1.6 Coverage is reported to Codecov (C# and Python).** Input: a C# or Python repo that has tests for that type. Output: the validation job runs those tests under coverage collection, and a `codecov/codecov-action` step uploads the report. The collection is `dotnet test --coverage --coverage-output-format cobertura --results-directory ./coverage`, leaving `--coverage-output` unset so each test project writes its own report rather than overwriting a shared one. A bare call resolves one workspace from the working directory, so it fails at a root holding none or more than one. Unless the repository root holds exactly one solution or project, the hub's validator therefore runs the collection once per tracked `*Tests*.csproj` with `--project`. It names no solution in that case, since a solution holding no test project fails the run. Or it is `pytest --cov-report=xml` in a Python directory with its own `uv.lock` or `requirements*.txt`, whose own `pyproject.toml` selects what to measure. Or it is `coverage run -m unittest discover -s tests` then `coverage xml` in a `lint-only` one. The upload is **best-effort** (`continue-on-error` and/or `fail_ci_if_error: false`), so a Codecov outage or an absent token never reds the gate. Each leg **fails its test step when the run wrote no report**. The reason is that the best-effort upload reads a missing report exactly as it reads a healthy run. A second reason is that, on the Python leg, `--cov-report=xml` alone selects nothing to measure. The C# leg renames each report to `coverage-.cobertura.xml` before the upload step reads the directory, since `codecov-cli`'s own finder does not match the default name. A repo owning its validator rather than calling the hub's owes that rename itself. `CODECOV_TOKEN` lives in the repo's **actions** and **dependabot** secret stores. The token is in the second because a run triggered by a Dependabot pull request reads the Dependabot store. Without the token there, the upload would otherwise skip silently on every bot pull request. A caller reaching the reusable validator across repositories names the secret it passes (`secrets:` with `CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}`). It does so on its pull request path and its publisher path alike. That is because `secrets: inherit` is documented for a caller in the same organization or enterprise, which a personal account is not. A call by local path stays inside one repository, where the caller's own store is the one the callee reads. So `secrets: inherit` is available there instead of naming each secret. The repo ships a **`.codecov.yml`** at the repository root. It sets the project and patch statuses to **`informational: true`**, so a coverage delta never gates a pull request. A repo whose quality bar requires a threshold may turn that off. The same file excludes intentionally-untested, non-shipped code (an example or benchmark project) from the denominator via `ignore`. Codecov reads its configuration under several names, but `.codecov.yml` is the only one the fleet accepts. So a copy under any other name is drift to rename. Coverage output is a build artifact, so `.gitignore` excludes it. The C# invocation runs under **Microsoft.Testing.Platform**, and the runner declaration, package references, and version floor an MTP-based test project needs are `CODESTYLE.md`'s .NET side. The Python invocation needs **`pytest-cov`** and a coverage selector, which are `CODESTYLE.md`'s Python side. A Python directory declared in the validator's `python-directories` input owes a `tests/` suite whatever its profile, so the validator fails one that has none. N/A for a repo carrying no tests for that type. *Prevents: coverage silently going unreported, and a coverage regression blocking an unrelated pull request.* +- **D1.6 Coverage is reported to Codecov (C# and Python).** Input: a C# or Python repo that has tests for that type. Output: the validation job runs those tests under coverage collection, and a `codecov/codecov-action` step uploads the report. The collection is `dotnet test --coverage --coverage-output-format cobertura --results-directory ./coverage`, leaving `--coverage-output` unset so each test project writes its own report rather than overwriting a shared one. A bare call resolves one workspace from the working directory, so it fails at a root holding none or more than one. The hub's validator therefore runs the collection once per tracked `*Tests*.csproj` that declares the leg's line, with `--project`, whatever the root holds. A test project left out of a root solution, or a library whose name matches the glob, is therefore a test project here. It names no solution, since a solution holding no test project fails the run. Or it is `pytest --cov-report=xml` in a Python directory with its own `uv.lock` or `requirements*.txt`, whose own `pyproject.toml` selects what to measure. Or it is `coverage run -m unittest discover -s tests` then `coverage xml` in a `lint-only` one. The upload is **best-effort** (`continue-on-error` and/or `fail_ci_if_error: false`), so a Codecov outage or an absent token never reds the gate. Each leg **fails its test step when the run wrote no report**. The reason is that the best-effort upload reads a missing report exactly as it reads a healthy run. A second reason is that, on the Python leg, `--cov-report=xml` alone selects nothing to measure. The C# leg renames each report to `coverage-.cobertura.xml` before the upload step reads the directory, since `codecov-cli`'s own finder does not match the default name. A repo owning its validator rather than calling the hub's owes that rename itself. `CODECOV_TOKEN` lives in the repo's **actions** and **dependabot** secret stores. The token is in the second because a run triggered by a Dependabot pull request reads the Dependabot store. Without the token there, the upload would otherwise skip silently on every bot pull request. A caller reaching the reusable validator across repositories names the secret it passes (`secrets:` with `CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}`). It does so on its pull request path and its publisher path alike. That is because `secrets: inherit` is documented for a caller in the same organization or enterprise, which a personal account is not. A call by local path stays inside one repository, where the caller's own store is the one the callee reads. So `secrets: inherit` is available there instead of naming each secret. The repo ships a **`.codecov.yml`** at the repository root. It sets the project and patch statuses to **`informational: true`**, so a coverage delta never gates a pull request. A repo whose quality bar requires a threshold may turn that off. The same file excludes intentionally-untested, non-shipped code (an example or benchmark project) from the denominator via `ignore`. Codecov reads its configuration under several names, but `.codecov.yml` is the only one the fleet accepts. So a copy under any other name is drift to rename. Coverage output is a build artifact, so `.gitignore` excludes it. The C# invocation runs under **Microsoft.Testing.Platform**, and the runner declaration, package references, and version floor an MTP-based test project needs are `CODESTYLE.md`'s .NET side. The Python invocation needs **`pytest-cov`** and a coverage selector, which are `CODESTYLE.md`'s Python side. A Python directory declared in the validator's `python-directories` input owes a `tests/` suite whatever its profile, so the validator fails one that has none. N/A for a repo carrying no tests for that type. *Prevents: coverage silently going unreported, and a coverage regression blocking an unrelated pull request.* - **D1.7 A built NuGet package is consumed before it publishes.** Input: a repo whose `build-nuget` job runs the hub's default leaf, in a smoke run or a publish run alike. Output: after the leaf packs, the job restores, builds, and runs a throwaway console project against that exact `.nupkg`. It does so once per target framework the project declares. Each consumer lives outside the checkout, so the caller's `global.json` and `Directory.Build.props` do not apply. Its `nuget.config` resolves the package ID, and the ID of each sibling package in the folder holding the build output, only from that folder. Every other ID resolves from nuget.org. Its package cache is its own, so neither a cached nor a published copy can stand in for the artifact under test. The consumer loads the package assembly and calls `GetExportedTypes()`. The check asserts from `obj/project.assets.json` that the package resolved from the `lib//` folder of the consumer's own framework. It also asserts that the loaded assembly's `TargetFrameworkAttribute` matches that folder. A `netstandard` framework is consumed under the SDK line `global.json` selects, or the newest declared line where there is none. It is asserted against the folder it resolved. A framework the check does not consume is reported skipped. Examples are .NET Framework, `netcoreapp3.1`, and a platform-specific `netX.Y-windows`. The attribute row of a `netstandard` consumer resolving such a folder is skipped too. Four static assertions join them. The package's `lib//` folders equal the declared frameworks. The nuspec `` equals the build version. The nuspec holds a dependency group per framework. A symbol package exists where the project enables symbols. Every declared `netX.Y` and `netstandard` framework is consumed and reported with one summary row per assertion. A failed step ends that framework's rows rather than the run. The job fails at the end if any failed. The check covers a library package, whose assemblies sit under `lib//`. The check uploads nothing, so it honors D1.3. It runs inside the build job, so a failure blocks the publish job that `needs:` that build. A caller's own `build-nuget` hook replaces the whole leaf and is outside the check. A caller's own `.github/actions/package-consume/action.yml` runs once after the default check. It receives the declared frameworks as JSON beside the package ID, version, and package folder. *Prevents: a defect that exists only in the packed form shipping. One example is one target framework's assembly packed under every `lib//` folder while the tests, which reach the library through a project reference, stay green.* - **D1.8 A built PyPI package is consumed before it publishes.** Input: a repo whose `build-pypi` job runs the hub's default leaf, in a smoke run or a publish run alike. Output: after the leaf builds, the job installs the wheel and, separately, the sdist into a fresh `uv venv`. It does so for each line of the `python-versions` input of `build-release-task.yml`. Empty runs the one line the root `.python-version` selects. Where there is none it runs the hub's fallback line. A caller that sets `python-versions` for both `validate-task.yml` and `build-release-task.yml` passes the same value to each. So the lines its tests run under are the lines its artifact is consumed under. Each environment lives outside the checkout. It installs the artifact, then the project's locked dependency groups from `uv.lock` without the project itself. The check asserts that `importlib.metadata` reports the version the leaf computed. It also asserts that every top-level name the installed distribution provides imports from the environment's site-packages, not the source tree. A distribution providing none, such as one of scripts only, reports that row skipped. It then runs the caller's `tests/` folder against the installed copy with pytest in `importlib` import mode. That run has the source tree off `sys.path` and the project's `pythonpath` setting cleared. Its working directory is outside the project. So the caller's suite must not read a path relative to the project root, or a tool setting read from the working directory. It must import a sibling helper as part of a package. The project directory holds its own `uv.lock`. A project with no `tests/` folder, or a run collecting no tests, is reported skipped rather than passed. Every line and artifact reports one summary row per assertion. A failed environment, install, or metadata read ends that artifact's rows rather than the run. The job fails at the end if any failed. The check uploads nothing, so it honors D1.3. It runs inside the build job, so a failure blocks the publish job that `needs:` that build. A caller's own `build-pypi` hook replaces the whole leaf and is outside the check. *Prevents: a defect that exists only in the built form shipping. One example is a module left out of the wheel while the tests, which import it from the source tree, stay green.* -- **D1.9 Each declared test line runs as its own named unit-test leg.** Input: a repo declaring .NET lines in `dotnet-versions` of `validate-task.yml`, Python lines in `python-versions`, or both. Output: each declared .NET line runs as a `Unit test job (.NET X.Y)` leg running `dotnet test --framework netX.Y` under that line's runtime. Each declared Python line runs as a `Unit test job (Python X.Y)` leg, or as the caller's named `test-matrix` legs where it sets one. A caller declaring neither runs the one line each of `global.json` and `.python-version` selects. The hub's fallback line stands in where a file is absent. The .NET legs run only where a `*Tests*.csproj` exists. The Python legs run only where a Python directory resolves. So a repo holding one kind reports no leg of the other. Each leg uploads its own coverage report, and the .NET upload carries a per-line flag beside `dotnet`. A failing leg does not cancel its siblings. *Prevents: a failing target framework or interpreter hiding inside a combined run naming none of them. A .NET-only repo reporting a Python line it never ran is the other.* +- **D1.9 Each declared test line runs as its own named unit-test leg.** Input: a repo declaring .NET lines in `dotnet-versions` of `validate-task.yml`, Python lines in `python-versions`, or both. Output: each declared .NET line runs as a `Unit test job (.NET X.Y)` leg running `dotnet test --framework netX.Y` under that line's runtime. A leg runs only the tracked `*Tests*.csproj` projects declaring `netX.Y` in their `TargetFramework` or `TargetFrameworks`, read with `dotnet msbuild`, and skips and names the rest. A leg where no test project declares its line fails, so a declared line never passes by running nothing. Each declared Python line runs as a `Unit test job (Python X.Y)` leg, or as the caller's named `test-matrix` legs where it sets one. A caller declaring neither runs the one line each of `global.json` and `.python-version` selects. The hub's fallback line stands in where a file is absent. The .NET legs run only where a `*Tests*.csproj` exists. The Python legs run only where a Python directory resolves. So a repo holding one kind reports no leg of the other. Each leg uploads its own coverage report, and the .NET upload carries a per-line flag beside `dotnet`. A failing leg does not cancel its siblings. *Prevents: a failing target framework or interpreter hiding inside a combined run naming none of them. A .NET-only repo reporting a Python line it never ran is the other.* ### D2 - Input/State Validation at Entry diff --git a/.github/workflows/validate-task.yml b/.github/workflows/validate-task.yml index 4ffcfcb0d..64053790b 100644 --- a/.github/workflows/validate-task.yml +++ b/.github/workflows/validate-task.yml @@ -28,7 +28,7 @@ on: type: string default: '' dotnet-versions: - description: JSON array of the X.Y .NET lines a multi-targeted caller's projects build, one per target framework, for example ["11.0", "10.0"]. The first entry is the line the root global.json selects, which builds every target framework, and a first entry differing from it fails the run. Every listed line is installed in each .NET leg, and each entry is its own Unit test job (.NET X.Y) leg running dotnet test --framework netX.Y under that line's runtime. Quote each entry, since an unquoted one is a JSON number rather than a line. Empty installs the one line global.json selects, or the hub's fallback line where it carries none. + description: JSON array of the X.Y .NET lines a multi-targeted caller's projects build, one per target framework, for example ["11.0", "10.0"]. The first entry is the line the root global.json selects, which builds every target framework, and a first entry differing from it fails the run. Every listed line is installed in each .NET leg, and each entry is its own Unit test job (.NET X.Y) leg running dotnet test --framework netX.Y under that line's runtime. A leg runs only the tracked *Tests*.csproj projects declaring netX.Y in their TargetFramework or TargetFrameworks, skips and names the others, and fails where no test project declares its line. Quote each entry, since an unquoted one is a JSON number rather than a line. Empty installs the one line global.json selects, or the hub's fallback line where it carries none. required: false type: string default: '' @@ -1074,32 +1074,39 @@ jobs: with: versions: ${{ inputs.dotnet-versions }} - - name: Resolve .NET workspaces step - id: dotnet - if: hashFiles('**/*Tests*.csproj') != '' - uses: $/.github/actions/dotnet-workspaces - with: - projects: ':(glob)**/*Tests*.csproj' - # --coverage-output stays unset because pinning one filename gives every test project in the solution the same path, and the last to finish overwrites the rest. # The default .cobertura.xml written instead is a name codecov-cli's finder does not match. # Each report is therefore prefixed rather than renamed, keeping the guid that makes it unique. - name: Run unit tests step if: hashFiles('**/*Tests*.csproj') != '' env: - WORKSPACES: ${{ steps.dotnet.outputs.workspaces }} DOTNET_VERSION: ${{ matrix.dotnet-version }} run: | set -Eeuo pipefail rm -rf ./coverage - # A solution holding no test project fails dotnet test with no test projects found, so the tests are named one project at a time. - if [ -z "$WORKSPACES" ]; then - dotnet test --framework "net$DOTNET_VERSION" --coverage --coverage-output-format cobertura --results-directory ./coverage + # A solution holding no test project fails dotnet test with no test projects found, and a project not declaring the leg's line fails --framework. + # So every tracked test project is read and named one at a time, whatever the root holds. + projects="$(git ls-files -- ':(glob)**/*Tests*.csproj')" + # A project not declaring the leg's line fails --framework, so it is skipped by name rather than failing the leg. + selected=() + while IFS= read -r project; do + [ -n "$project" ] || continue + properties="$(dotnet msbuild "$project" -nologo -getProperty:TargetFramework -getProperty:TargetFrameworks < /dev/null)" + # MSBuild trims each list entry and compares a framework without regard to case, so the match does too. + if jq -e --arg line "net$DOTNET_VERSION" '[.Properties.TargetFramework, .Properties.TargetFrameworks] | map(select(. != null) | split(";")[] | gsub("\\s"; "") | ascii_downcase) | any(. == $line)' <<< "$properties" > /dev/null; then + selected+=("$project") + else + echo "Skipping $project, which does not declare net$DOTNET_VERSION." + fi + done <<< "$projects" + # A declared line must never pass by running nothing. + if [ "${#selected[@]}" -eq 0 ]; then + echo "::error::No test project declares net$DOTNET_VERSION in its TargetFramework or TargetFrameworks, so the .NET $DOTNET_VERSION leg would run no tests." + exit 1 fi - while IFS= read -r workspace; do - [ -n "$workspace" ] || continue - dotnet test --framework "net$DOTNET_VERSION" --project "$workspace" --coverage --coverage-output-format cobertura --results-directory ./coverage < /dev/null - done <<< "$WORKSPACES" + for project in "${selected[@]}"; do + dotnet test --framework "net$DOTNET_VERSION" --project "$project" --coverage --coverage-output-format cobertura --results-directory ./coverage < /dev/null + done written=0 for report in ./coverage/*.cobertura.xml; do [ -e "$report" ] || continue diff --git a/WORKFLOW.md b/WORKFLOW.md index 4eadedb23..e42103b7c 100644 --- a/WORKFLOW.md +++ b/WORKFLOW.md @@ -144,10 +144,10 @@ The required behaviors, organized by domain. Each is a **MUST**, and its `Output - **D1.3 Smoke never publishes and never uploads.** Input: `smoke: true`. Output: full compile/lint/test, but no registry/image push, no release, and **no** artifact uploads. Every `upload-artifact`, including any aggregation job, is gated on smoke being false. That gate is written `!inputs.smoke` at the workflow layer and `inputs.smoke != 'true'` in a composite action, whose inputs are strings. *Prevents: a PR publishing, and orphaned artifacts churning the storage quota.* - **D1.4 Workflow-file changes are not smoke-built.** Input: a PR changing only `.github/workflows/**`. Output: the paths-filter marks no target, so smoke-build skips. An inclusion list satisfying D1.1 reaches this by leaving workflow paths out of every target's entry. *Implication: a workflow-only change is not smoke-built, but actionlint still validates it in CI.* - **D1.5 One required aggregator gates merge.** Input: any PR. Output: a single aggregator job must **succeed**. It must run under `if: always()`, so a failed or skipped dependency cannot skip the gate itself. It must also `needs:` the validation job, and the `changes` and `smoke-build` jobs too wherever the repo has a smoke build. It must treat a **skipped** smoke build as pass, and **block** on `failure`/`cancelled`. Its name is ruleset-bound: the job `name:` and the ruleset `context:` are the same string and MUST be renamed together, never independently. The workflow holding it MUST trigger on `pull_request`. A gate without a `pull_request` trigger never runs the validator's pull-request-only steps, the prose gate among them. A workflow any other event also triggers yields that name only when `github.event_name == 'pull_request'`, through an expression `name:`. Otherwise a dispatch or push run on a PR's head posts the required context without the PR run's gates. *Prevents: a paths-filter error letting a target-changing PR merge unbuilt.* -- **D1.6 Coverage is reported to Codecov (C# and Python).** Input: a C# or Python repo that has tests for that type. Output: the validation job runs those tests under coverage collection, and a `codecov/codecov-action` step uploads the report. The collection is `dotnet test --coverage --coverage-output-format cobertura --results-directory ./coverage`, leaving `--coverage-output` unset so each test project writes its own report rather than overwriting a shared one. A bare call resolves one workspace from the working directory, so it fails at a root holding none or more than one. Unless the repository root holds exactly one solution or project, the hub's validator therefore runs the collection once per tracked `*Tests*.csproj` with `--project`. It names no solution in that case, since a solution holding no test project fails the run. Or it is `pytest --cov-report=xml` in a Python directory with its own `uv.lock` or `requirements*.txt`, whose own `pyproject.toml` selects what to measure. Or it is `coverage run -m unittest discover -s tests` then `coverage xml` in a `lint-only` one. The upload is **best-effort** (`continue-on-error` and/or `fail_ci_if_error: false`), so a Codecov outage or an absent token never reds the gate. Each leg **fails its test step when the run wrote no report**. The reason is that the best-effort upload reads a missing report exactly as it reads a healthy run. A second reason is that, on the Python leg, `--cov-report=xml` alone selects nothing to measure. The C# leg renames each report to `coverage-.cobertura.xml` before the upload step reads the directory, since `codecov-cli`'s own finder does not match the default name. A repo owning its validator rather than calling the hub's owes that rename itself. `CODECOV_TOKEN` lives in the repo's **actions** and **dependabot** secret stores. The token is in the second because a run triggered by a Dependabot pull request reads the Dependabot store. Without the token there, the upload would otherwise skip silently on every bot pull request. A caller reaching the reusable validator across repositories names the secret it passes (`secrets:` with `CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}`). It does so on its pull request path and its publisher path alike. That is because `secrets: inherit` is documented for a caller in the same organization or enterprise, which a personal account is not. A call by local path stays inside one repository, where the caller's own store is the one the callee reads. So `secrets: inherit` is available there instead of naming each secret. The repo ships a **`.codecov.yml`** at the repository root. It sets the project and patch statuses to **`informational: true`**, so a coverage delta never gates a pull request. A repo whose quality bar requires a threshold may turn that off. The same file excludes intentionally-untested, non-shipped code (an example or benchmark project) from the denominator via `ignore`. Codecov reads its configuration under several names, but `.codecov.yml` is the only one the fleet accepts. So a copy under any other name is drift to rename. Coverage output is a build artifact, so `.gitignore` excludes it. The C# invocation runs under **Microsoft.Testing.Platform**, and the runner declaration, package references, and version floor an MTP-based test project needs are `CODESTYLE.md`'s .NET side. The Python invocation needs **`pytest-cov`** and a coverage selector, which are `CODESTYLE.md`'s Python side. A Python directory declared in the validator's `python-directories` input owes a `tests/` suite whatever its profile, so the validator fails one that has none. N/A for a repo carrying no tests for that type. *Prevents: coverage silently going unreported, and a coverage regression blocking an unrelated pull request.* +- **D1.6 Coverage is reported to Codecov (C# and Python).** Input: a C# or Python repo that has tests for that type. Output: the validation job runs those tests under coverage collection, and a `codecov/codecov-action` step uploads the report. The collection is `dotnet test --coverage --coverage-output-format cobertura --results-directory ./coverage`, leaving `--coverage-output` unset so each test project writes its own report rather than overwriting a shared one. A bare call resolves one workspace from the working directory, so it fails at a root holding none or more than one. The hub's validator therefore runs the collection once per tracked `*Tests*.csproj` that declares the leg's line, with `--project`, whatever the root holds. A test project left out of a root solution, or a library whose name matches the glob, is therefore a test project here. It names no solution, since a solution holding no test project fails the run. Or it is `pytest --cov-report=xml` in a Python directory with its own `uv.lock` or `requirements*.txt`, whose own `pyproject.toml` selects what to measure. Or it is `coverage run -m unittest discover -s tests` then `coverage xml` in a `lint-only` one. The upload is **best-effort** (`continue-on-error` and/or `fail_ci_if_error: false`), so a Codecov outage or an absent token never reds the gate. Each leg **fails its test step when the run wrote no report**. The reason is that the best-effort upload reads a missing report exactly as it reads a healthy run. A second reason is that, on the Python leg, `--cov-report=xml` alone selects nothing to measure. The C# leg renames each report to `coverage-.cobertura.xml` before the upload step reads the directory, since `codecov-cli`'s own finder does not match the default name. A repo owning its validator rather than calling the hub's owes that rename itself. `CODECOV_TOKEN` lives in the repo's **actions** and **dependabot** secret stores. The token is in the second because a run triggered by a Dependabot pull request reads the Dependabot store. Without the token there, the upload would otherwise skip silently on every bot pull request. A caller reaching the reusable validator across repositories names the secret it passes (`secrets:` with `CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}`). It does so on its pull request path and its publisher path alike. That is because `secrets: inherit` is documented for a caller in the same organization or enterprise, which a personal account is not. A call by local path stays inside one repository, where the caller's own store is the one the callee reads. So `secrets: inherit` is available there instead of naming each secret. The repo ships a **`.codecov.yml`** at the repository root. It sets the project and patch statuses to **`informational: true`**, so a coverage delta never gates a pull request. A repo whose quality bar requires a threshold may turn that off. The same file excludes intentionally-untested, non-shipped code (an example or benchmark project) from the denominator via `ignore`. Codecov reads its configuration under several names, but `.codecov.yml` is the only one the fleet accepts. So a copy under any other name is drift to rename. Coverage output is a build artifact, so `.gitignore` excludes it. The C# invocation runs under **Microsoft.Testing.Platform**, and the runner declaration, package references, and version floor an MTP-based test project needs are `CODESTYLE.md`'s .NET side. The Python invocation needs **`pytest-cov`** and a coverage selector, which are `CODESTYLE.md`'s Python side. A Python directory declared in the validator's `python-directories` input owes a `tests/` suite whatever its profile, so the validator fails one that has none. N/A for a repo carrying no tests for that type. *Prevents: coverage silently going unreported, and a coverage regression blocking an unrelated pull request.* - **D1.7 A built NuGet package is consumed before it publishes.** Input: a repo whose `build-nuget` job runs the hub's default leaf, in a smoke run or a publish run alike. Output: after the leaf packs, the job restores, builds, and runs a throwaway console project against that exact `.nupkg`. It does so once per target framework the project declares. Each consumer lives outside the checkout, so the caller's `global.json` and `Directory.Build.props` do not apply. Its `nuget.config` resolves the package ID, and the ID of each sibling package in the folder holding the build output, only from that folder. Every other ID resolves from nuget.org. Its package cache is its own, so neither a cached nor a published copy can stand in for the artifact under test. The consumer loads the package assembly and calls `GetExportedTypes()`. The check asserts from `obj/project.assets.json` that the package resolved from the `lib//` folder of the consumer's own framework. It also asserts that the loaded assembly's `TargetFrameworkAttribute` matches that folder. A `netstandard` framework is consumed under the SDK line `global.json` selects, or the newest declared line where there is none. It is asserted against the folder it resolved. A framework the check does not consume is reported skipped. Examples are .NET Framework, `netcoreapp3.1`, and a platform-specific `netX.Y-windows`. The attribute row of a `netstandard` consumer resolving such a folder is skipped too. Four static assertions join them. The package's `lib//` folders equal the declared frameworks. The nuspec `` equals the build version. The nuspec holds a dependency group per framework. A symbol package exists where the project enables symbols. Every declared `netX.Y` and `netstandard` framework is consumed and reported with one summary row per assertion. A failed step ends that framework's rows rather than the run. The job fails at the end if any failed. The check covers a library package, whose assemblies sit under `lib//`. The check uploads nothing, so it honors D1.3. It runs inside the build job, so a failure blocks the publish job that `needs:` that build. A caller's own `build-nuget` hook replaces the whole leaf and is outside the check. A caller's own `.github/actions/package-consume/action.yml` runs once after the default check. It receives the declared frameworks as JSON beside the package ID, version, and package folder. *Prevents: a defect that exists only in the packed form shipping. One example is one target framework's assembly packed under every `lib//` folder while the tests, which reach the library through a project reference, stay green.* - **D1.8 A built PyPI package is consumed before it publishes.** Input: a repo whose `build-pypi` job runs the hub's default leaf, in a smoke run or a publish run alike. Output: after the leaf builds, the job installs the wheel and, separately, the sdist into a fresh `uv venv`. It does so for each line of the `python-versions` input of `build-release-task.yml`. Empty runs the one line the root `.python-version` selects. Where there is none it runs the hub's fallback line. A caller that sets `python-versions` for both `validate-task.yml` and `build-release-task.yml` passes the same value to each. So the lines its tests run under are the lines its artifact is consumed under. Each environment lives outside the checkout. It installs the artifact, then the project's locked dependency groups from `uv.lock` without the project itself. The check asserts that `importlib.metadata` reports the version the leaf computed. It also asserts that every top-level name the installed distribution provides imports from the environment's site-packages, not the source tree. A distribution providing none, such as one of scripts only, reports that row skipped. It then runs the caller's `tests/` folder against the installed copy with pytest in `importlib` import mode. That run has the source tree off `sys.path` and the project's `pythonpath` setting cleared. Its working directory is outside the project. So the caller's suite must not read a path relative to the project root, or a tool setting read from the working directory. It must import a sibling helper as part of a package. The project directory holds its own `uv.lock`. A project with no `tests/` folder, or a run collecting no tests, is reported skipped rather than passed. Every line and artifact reports one summary row per assertion. A failed environment, install, or metadata read ends that artifact's rows rather than the run. The job fails at the end if any failed. The check uploads nothing, so it honors D1.3. It runs inside the build job, so a failure blocks the publish job that `needs:` that build. A caller's own `build-pypi` hook replaces the whole leaf and is outside the check. *Prevents: a defect that exists only in the built form shipping. One example is a module left out of the wheel while the tests, which import it from the source tree, stay green.* -- **D1.9 Each declared test line runs as its own named unit-test leg.** Input: a repo declaring .NET lines in `dotnet-versions` of `validate-task.yml`, Python lines in `python-versions`, or both. Output: each declared .NET line runs as a `Unit test job (.NET X.Y)` leg running `dotnet test --framework netX.Y` under that line's runtime. Each declared Python line runs as a `Unit test job (Python X.Y)` leg, or as the caller's named `test-matrix` legs where it sets one. A caller declaring neither runs the one line each of `global.json` and `.python-version` selects. The hub's fallback line stands in where a file is absent. The .NET legs run only where a `*Tests*.csproj` exists. The Python legs run only where a Python directory resolves. So a repo holding one kind reports no leg of the other. Each leg uploads its own coverage report, and the .NET upload carries a per-line flag beside `dotnet`. A failing leg does not cancel its siblings. *Prevents: a failing target framework or interpreter hiding inside a combined run naming none of them. A .NET-only repo reporting a Python line it never ran is the other.* +- **D1.9 Each declared test line runs as its own named unit-test leg.** Input: a repo declaring .NET lines in `dotnet-versions` of `validate-task.yml`, Python lines in `python-versions`, or both. Output: each declared .NET line runs as a `Unit test job (.NET X.Y)` leg running `dotnet test --framework netX.Y` under that line's runtime. A leg runs only the tracked `*Tests*.csproj` projects declaring `netX.Y` in their `TargetFramework` or `TargetFrameworks`, read with `dotnet msbuild`, and skips and names the rest. A leg where no test project declares its line fails, so a declared line never passes by running nothing. Each declared Python line runs as a `Unit test job (Python X.Y)` leg, or as the caller's named `test-matrix` legs where it sets one. A caller declaring neither runs the one line each of `global.json` and `.python-version` selects. The hub's fallback line stands in where a file is absent. The .NET legs run only where a `*Tests*.csproj` exists. The Python legs run only where a Python directory resolves. So a repo holding one kind reports no leg of the other. Each leg uploads its own coverage report, and the .NET upload carries a per-line flag beside `dotnet`. A failing leg does not cancel its siblings. *Prevents: a failing target framework or interpreter hiding inside a combined run naming none of them. A .NET-only repo reporting a Python line it never ran is the other.* ### D2 - Input/State Validation at Entry diff --git a/docs/reusable-workflows.md b/docs/reusable-workflows.md index 6545bd982..0592c4601 100644 --- a/docs/reusable-workflows.md +++ b/docs/reusable-workflows.md @@ -507,7 +507,7 @@ A caller carrying a .NET test project as well runs it in the separate `unit-test Each .NET upload carries the fixed `dotnet` flag and a `dotnet-X.Y` flag naming its line. A caller whose `.codecov.yml` configures flags names `dotnet` for the .NET unit-test share, beside the Python legs' own flags. It may also name a line's flag to read that line apart. A .NET caller's coverage reads as a `dotnet` series from its first pin bump onto a release carrying the flag, rather than unflagged. -A repo whose .NET projects multi-target names every line they build in `dotnet-versions`, such as `'["11.0", "10.0"]'` for `net10.0;net11.0`. It is the .NET counterpart of `python-versions`, and each entry is its own `Unit test job (.NET X.Y)` leg running `dotnet test --framework netX.Y`. One SDK builds every target framework, and each framework's tests run under that framework's own runtime. So every leg installs every listed line beside the selected one. A caller naming none runs the one leg for the line `global.json` selects, or the fallback line. The first entry is the `X.Y` line the root `global.json` selects, the highest target framework's, since the release builds on it. The `dotnet-sdk` action refuses a first entry naming another line, with a named cause. It also refuses an entry that is not a quoted `X.Y` line. The `Build test matrix job` runs that check first, before any job builds, as it does for `python-versions`. The `lint` job repeats it, since it does not wait on that job. A caller carrying no `global.json` `sdk.version` installs every entry instead of the fallback line. Without the input, the one leg runs `--framework` for the selected line alone, so a lower framework's tests never run. +A repo whose .NET projects multi-target names every line they build in `dotnet-versions`, such as `'["11.0", "10.0"]'` for `net10.0;net11.0`. It is the .NET counterpart of `python-versions`, and each entry is its own `Unit test job (.NET X.Y)` leg running `dotnet test --framework netX.Y`. A leg runs only the tracked `*Tests*.csproj` projects declaring `netX.Y` in their `TargetFramework` or `TargetFrameworks`, and logs each project it skips by name. A leg where no test project declares its line fails with an error naming the line. One SDK builds every target framework, and each framework's tests run under that framework's own runtime. So every leg installs every listed line beside the selected one. A caller naming none runs the one leg for the line `global.json` selects, or the fallback line. The first entry is the `X.Y` line the root `global.json` selects, the highest target framework's, since the release builds on it. The `dotnet-sdk` action refuses a first entry naming another line, with a named cause. It also refuses an entry that is not a quoted `X.Y` line. The `Build test matrix job` runs that check first, before any job builds, as it does for `python-versions`. The `lint` job repeats it, since it does not wait on that job. A caller carrying no `global.json` `sdk.version` installs every entry instead of the fallback line. Without the input, the one leg runs `--framework` for the selected line alone, so a lower framework's tests never run. A PyPI repo names the lines its built package must work under in the `python-versions` input of `build-release-task.yml`, as it does for `validate-task.yml`. The two inputs hold the same value, so the lines its tests run under are the lines its wheel and sdist are consumed under. The input is validated like the unit-test one. Empty consumes under the one line the root `.python-version` selects. Where there is none it consumes under the hub's fallback line. After the hub default builds, the `build-pypi` job installs the wheel and, separately, the sdist into a fresh environment per line, outside the checkout. It then installs the project's locked dependency groups without the project. It asserts the installed version and that the package imports from site-packages. It runs the caller's `tests/` folder against the installed copy, from outside the project. The suite must read no path relative to the project root, and no tool setting from the working directory. It must import a sibling helper as part of a package. The project directory must hold its own `uv.lock`. A smoke run runs it unchanged and uploads nothing, and a caller's own `build-pypi` hook is outside it. WORKFLOW.md D1.8 states the guarantee. diff --git a/tests/test_package_consume_nuget.py b/tests/test_package_consume_nuget.py index 896d3468c..2c99dc6e9 100755 --- a/tests/test_package_consume_nuget.py +++ b/tests/test_package_consume_nuget.py @@ -12,6 +12,7 @@ import contextlib import io import re +import subprocess import sys import tempfile import unittest @@ -273,6 +274,19 @@ def test_a_referenced_project_package_does_not_hide_the_projects_own(self) -> No pcn.find_package(directory, "Contoso.Missing") +class PropertyTimeoutTests(unittest.TestCase): + def test_a_timed_out_property_read_is_a_reported_failure_not_a_traceback(self) -> None: + timeout = subprocess.TimeoutExpired(["dotnet", "msbuild"], 900) + with ( + mock.patch.object(pcn.subprocess, "run", side_effect=timeout), + contextlib.redirect_stdout(io.StringIO()) as printed, + self.assertRaises(SystemExit) as raised, + ): + pcn.project_properties("src/Widget.csproj") + self.assertEqual(1, raised.exception.code) + self.assertIn("::error::Reading src/Widget.csproj properties timed out", printed.getvalue()) + + class InterruptTests(unittest.TestCase): def setUp(self) -> None: pcn.received.clear() diff --git a/tests/test_package_consume_pypi.py b/tests/test_package_consume_pypi.py index 1593cda31..0d80450a4 100755 --- a/tests/test_package_consume_pypi.py +++ b/tests/test_package_consume_pypi.py @@ -165,7 +165,11 @@ class ConsumeTests(unittest.TestCase): """consume() with its commands stubbed, so each early return and skip is driven.""" def drive( - self, project: Path, probes: dict[str, str], pytest_status: int = 0 + self, + project: Path, + probes: dict[str, str], + pytest_status: int = 0, + requirements: list[str] | None = None, ) -> dict[str, str]: def fake_run(command: list[str], cwd: Path, env: dict[str, str]) -> mock.Mock: self.cwds.append((command, cwd)) @@ -189,7 +193,7 @@ def fake_run(command: list[str], cwd: Path, env: dict[str, str]) -> mock.Mock: "contoso-widget", "1.2.3", project, - [], + [] if requirements is None else requirements, project, {}, report, @@ -242,6 +246,35 @@ def fake_run(command: list[str], cwd: Path, env: dict[str, str]) -> mock.Mock: FILES = 'VERSION\t1.2.3\nFILES\t["contoso_widget/__init__.py"]\n' GOOD = "ROOTS\t/venv/site\nIMPORT\tcontoso_widget\t/venv/site/contoso_widget/__init__.py\n" + def test_missing_exported_dependencies_fail_the_tests_row_and_skip_their_install(self) -> None: + installs: list[list[str]] = [] + report = pcp.Report() + + def fake_run(command: list[str], cwd: Path, env: dict[str, str]) -> mock.Mock: + installs.append(command) + if "-c" in command: + key = "files" if "dist.version" in command[command.index("-c") + 1] else "import" + return mock.Mock( + returncode=0, stdout={"files": self.FILES, "import": self.GOOD}[key], stderr="" + ) + return mock.Mock(returncode=0, stdout="", stderr="") + + with tempfile.TemporaryDirectory() as name: + project = Path(name) + (project / "tests").mkdir() + with mock.patch.object(pcp, "run", fake_run), contextlib.redirect_stdout(io.StringIO()): + pcp.consume( + "wheel", Path("w.whl"), "3.13", "contoso-widget", "1.2.3", + project, None, project, {}, report, + ) # fmt: skip + rows = {r.check: r for r in report.results} + self.assertNotIn("test dependencies", rows) + self.assertEqual(rows["import location"].ok, True) + self.assertFalse(rows["tests"].ok) + self.assertIn("could not be exported", rows["tests"].detail) + self.assertFalse([c for c in installs if "pytest" in c]) + self.assertEqual(len([c for c in installs if c[:3] == ["uv", "pip", "install"]]), 1) + def test_a_source_tree_import_fails_the_location_row(self) -> None: with tempfile.TemporaryDirectory() as name: rows = self.drive( @@ -288,6 +321,34 @@ def test_pytest_collecting_nothing_skips_and_a_failing_run_fails(self) -> None: self.assertEqual(self.drive(project, probes, 0)["tests"], "pass") +class CheckTests(unittest.TestCase): + def test_a_timed_out_export_still_runs_the_artifact_checks_and_writes_the_summary(self) -> None: + seen: list[object] = [] + + def fake_consume(*args: object) -> None: + seen.append(args[6]) + + with tempfile.TemporaryDirectory() as name: + root = Path(name) + (root / "dist").mkdir() + summary = root / "summary.md" + timeout = subprocess.TimeoutExpired(["uv", "export"], 900) + with ( + mock.patch.object(pcp, "project_name", return_value="contoso-widget"), + mock.patch.object(pcp, "find_artifacts", return_value={"wheel": root / "w.whl"}), + mock.patch.object(pcp, "export_requirements", side_effect=timeout), + mock.patch.object(pcp, "consume", fake_consume), + mock.patch.dict(os.environ, {"GITHUB_STEP_SUMMARY": str(summary)}), + contextlib.redirect_stdout(io.StringIO()), + ): + status = pcp.check(root, "1.2.3", ["3.13"], root) + text = summary.read_text(encoding="utf-8") + self.assertEqual(status, 1) + self.assertEqual(seen, [None]) + self.assertIn("timed out", text) + self.assertIn("| all | test dependencies | fail |", text) + + class ReportTests(unittest.TestCase): def test_a_failure_is_an_escaped_annotation_and_a_table_row(self) -> None: report = pcp.Report() diff --git a/tests/test_release_guards.py b/tests/test_release_guards.py index e1c3727f2..dd60386fc 100755 --- a/tests/test_release_guards.py +++ b/tests/test_release_guards.py @@ -2310,8 +2310,8 @@ def test_validator_runs_each_dotnet_line_and_python_line_as_its_own_leg(self) -> for line in script.splitlines() if re.match(r"\s*(?:\S.*\s)?dotnet test ", line) and not line.lstrip().startswith("#") ] - self.assertEqual(2, len(invocations)) - self.assertEqual(2, script.count('dotnet test --framework "net$DOTNET_VERSION" ')) + self.assertEqual(1, len(invocations)) + self.assertEqual(1, script.count('dotnet test --framework "net$DOTNET_VERSION" ')) run_step = yaml_step(dotnet_job, "Run unit tests step") self.assertEqual( "${{ matrix.dotnet-version }}", yaml_value(run_step, "env", "DOTNET_VERSION") @@ -2359,7 +2359,7 @@ def test_validator_runs_each_dotnet_line_and_python_line_as_its_own_leg(self) -> ) @unittest.skipUnless( - shutil.which("bash") and os.name == "posix", + shutil.which("bash") and shutil.which("git") and shutil.which("jq") and os.name == "posix", "the step runs under bash against a stand-in dotnet that only a POSIX host can execute", ) def test_validator_dotnet_leg_fails_when_no_report_was_written(self) -> None: @@ -2388,10 +2388,15 @@ def test_validator_dotnet_leg_fails_when_no_report_was_written(self) -> None: bin_dir = Path(scratch) / "bin" bin_dir.mkdir() stand_in = bin_dir / "dotnet" - stand_in.write_text(f"#!/usr/bin/env bash\n{writer}\n", encoding="utf-8") + stand_in.write_text( + f"#!/usr/bin/env bash\n{DOTNET_MSBUILD_STAND_IN}{writer}\n", encoding="utf-8" + ) stand_in.chmod(0o755) work = Path(scratch) / "work" (work / "coverage").mkdir(parents=True) + (work / "AppTests.csproj").write_text("net10.0", encoding="utf-8") + for command in (["git", "init", "-q"], ["git", "add", "."]): + run(command, cwd=work, env=without_git_location(), check=True, timeout=60) (work / "coverage/coverage-committed.cobertura.xml").write_text( "", encoding="utf-8" ) @@ -2401,6 +2406,7 @@ def test_validator_dotnet_leg_fails_when_no_report_was_written(self) -> None: env={ **without_git_location(), "PATH": f"{bin_dir}{os.pathsep}{os.environ.get('PATH', os.defpath)}", + "STUB_LOG": os.devnull, "WORKSPACES": "", "DOTNET_VERSION": "10.0", }, @@ -2418,13 +2424,14 @@ def test_validator_dotnet_leg_fails_when_no_report_was_written(self) -> None: self.assertTrue((work / "coverage/coverage-0f1e2d3c.cobertura.xml").exists()) @unittest.skipUnless( - shutil.which("git") and shutil.which("bash") and os.name == "posix", + shutil.which("git") and shutil.which("bash") and shutil.which("jq") and os.name == "posix", "the action reads the tracked tree with git, and the steps run under bash against a stand-in dotnet", ) def test_validator_dotnet_steps_run_once_per_workspace(self) -> None: - """Only a root holding exactly one solution or project keeps the bare call. + """The style step keeps the bare call only at a root holding exactly one solution or project. - Every other tree gets each tracked solution, or each project, named instead. A root holding + Every other tree gets each tracked solution, or each project, named instead. The unit-test + step never keeps it, since each test project is read for the line it declares. A root holding several never takes a nested solution. It names its own solutions, or the projects where it holds none, so a nested one never hides the root's projects. Each job's resolver step is read from the workflow with the inputs it passes, and its output feeds that @@ -2443,7 +2450,7 @@ def wiring(job: str, consumer: str) -> tuple[str, dict[str, str]]: """The consumer's script and the inputs its job passes the resolver, held to one wiring. The two share one condition, since a resolver skipped where its consumer runs leaves the - list empty, which is the bare call. + list empty, which is the style step's bare call. """ resolve = yaml_step(job, "Resolve .NET workspaces step") self.assertEqual(yaml_value(resolve, "uses"), "$/.github/actions/dotnet-workspaces") @@ -2466,7 +2473,9 @@ def wiring(job: str, consumer: str) -> tuple[str, dict[str, str]]: return step_script_text(job, consumer), inputs style, style_inputs = wiring(lint, "Check C# style step") - tests, test_inputs = wiring(unit, "Run unit tests step") + tests = step_script_text(unit, "Run unit tests step") + self.assertNotIn("dotnet-workspaces", unit) + self.assertNotIn("WORKSPACES", tests) flags = "--coverage --coverage-output-format cobertura --results-directory ./coverage" bare_style = ["format style --verify-no-changes --severity=info --verbosity=detailed"] @@ -2480,12 +2489,12 @@ def named_style(*workspaces: str) -> list[str]: "a root solution": ( ["App.sln", "src/Lib/Lib.csproj", "tests/LibTests/LibTests.csproj"], bare_style, - [f"test --framework net10.0 {flags}"], + [f"test --framework net10.0 --project tests/LibTests/LibTests.csproj {flags}"], ), "a root project": ( ["App.csproj", "tests/AppTests/AppTests.csproj"], bare_style, - [f"test --framework net10.0 {flags}"], + [f"test --framework net10.0 --project tests/AppTests/AppTests.csproj {flags}"], ), "solutions below the root": ( [ @@ -2532,7 +2541,7 @@ def named_style(*workspaces: str) -> list[str]: [f"test --framework net10.0 --project tests/AppTests/AppTests.csproj {flags}"], ), } - steps = ((style, style_inputs, 1), (tests, test_inputs, 2)) + steps = ((style, style_inputs, 1), (tests, None, 2)) for label, (tracked, want_style, want_tests) in trees.items(): for (script, inputs, which), want in zip(steps, (want_style, want_tests), strict=True): with ( @@ -2545,7 +2554,7 @@ def named_style(*workspaces: str) -> list[str]: output.write_text("", encoding="utf-8") stand_in = bin_dir / "dotnet" stand_in.write_text( - '#!/usr/bin/env bash\necho "$*" >> "$STUB_LOG"\n' + f'#!/usr/bin/env bash\n{DOTNET_MSBUILD_STAND_IN}echo "$*" >> "$STUB_LOG"\n' 'mkdir -p ./coverage && echo "" > "./coverage/$RANDOM.cobertura.xml"\n', encoding="utf-8", ) @@ -2561,21 +2570,24 @@ def named_style(*workspaces: str) -> list[str]: check=True, timeout=60, ) - resolved = run( - [bash_or_skip(), "-c", resolver], - cwd=work, - env={**without_git_location(), **inputs, "GITHUB_OUTPUT": str(output)}, - capture_output=True, - text=True, - encoding="utf-8", - timeout=60, - check=False, - ) - self.assertEqual(0, resolved.returncode, resolved.stdout + resolved.stderr) - written = output.read_text(encoding="utf-8") - match = re.fullmatch(r"workspaces<<(\S+)\n((?:.+\n)*)\1\n", written) - self.assertIsNotNone(match, written) - assert match is not None + workspaces = "" + if inputs is not None: + resolved = run( + [bash_or_skip(), "-c", resolver], + cwd=work, + env={**without_git_location(), **inputs, "GITHUB_OUTPUT": str(output)}, + capture_output=True, + text=True, + encoding="utf-8", + timeout=60, + check=False, + ) + self.assertEqual(0, resolved.returncode, resolved.stdout + resolved.stderr) + written = output.read_text(encoding="utf-8") + match = re.fullmatch(r"workspaces<<(\S+)\n((?:.+\n)*)\1\n", written) + self.assertIsNotNone(match, written) + assert match is not None + workspaces = match.group(2).removesuffix("\n") result = run( [bash_or_skip(), "-c", script], cwd=work, @@ -2583,7 +2595,7 @@ def named_style(*workspaces: str) -> list[str]: **without_git_location(), "PATH": f"{bin_dir}{os.pathsep}{os.environ.get('PATH', os.defpath)}", "STUB_LOG": str(log), - "WORKSPACES": match.group(2).removesuffix("\n"), + "WORKSPACES": workspaces, "DOTNET_VERSION": "10.0", }, capture_output=True, @@ -2595,6 +2607,93 @@ def named_style(*workspaces: str) -> list[str]: self.assertEqual(0, result.returncode, result.stdout + result.stderr) self.assertEqual(want, log.read_text(encoding="utf-8").splitlines()) + @unittest.skipUnless( + shutil.which("git") and shutil.which("bash") and shutil.which("jq") and os.name == "posix", + "the step reads the tracked tree with git and runs under bash against a stand-in dotnet", + ) + def test_validator_dotnet_leg_runs_only_the_projects_declaring_its_line(self) -> None: + """WORKFLOW.md D1.9: a project not declaring the leg's line is skipped by name, and no declarer fails the leg. + + The step's whole script is run, with the stand-in answering dotnet msbuild from each + project file's TargetFramework|TargetFrameworks content. + Five filter defects fail here as they would on a runner. + They are a prefix match, one property ignored, no trim, no case fold, and an empty selection passing. + """ + workflow = (REPO / ".github/workflows/validate-task.yml").read_text(encoding="utf-8") + job = workflow.split("\n unit-test-dotnet:\n", 1)[1].split("\n validate:\n", 1)[0] + script = step_script_text(job, "Run unit tests step") + self.assertIn("-getProperty:TargetFramework -getProperty:TargetFrameworks", script) + flags = "--coverage --coverage-output-format cobertura --results-directory ./coverage" + # A declares one framework singularly, B a list, and C a suffixed one beside a spaced, upper-case entry. + projects = { + "A/ATests.csproj": "net10.0|", + "B/BTests.csproj": "|net10.0;net11.0", + "C/CTests.csproj": "|net10.0-windows; NET11.0", + } + cases = { + "11.0": ( + 0, + [ + f"test --framework net11.0 --project B/BTests.csproj {flags}", + f"test --framework net11.0 --project C/CTests.csproj {flags}", + ], + ), + "10.0": ( + 0, + [ + f"test --framework net10.0 --project A/ATests.csproj {flags}", + f"test --framework net10.0 --project B/BTests.csproj {flags}", + ], + ), + "9.0": (1, []), + "1.0": (1, []), + } + for line, (status, want) in cases.items(): + with self.subTest(line=line), tempfile.TemporaryDirectory() as scratch: + bin_dir, work, log = ( + Path(scratch) / "bin", + Path(scratch) / "work", + Path(scratch) / "log", + ) + bin_dir.mkdir() + stand_in = bin_dir / "dotnet" + stand_in.write_text( + f'#!/usr/bin/env bash\n{DOTNET_MSBUILD_STAND_IN}echo "$*" >> "$STUB_LOG"\n' + 'mkdir -p ./coverage && echo "" > "./coverage/$RANDOM.cobertura.xml"\n', + encoding="utf-8", + ) + stand_in.chmod(0o755) + for path, frameworks in projects.items(): + (work / path).parent.mkdir(parents=True, exist_ok=True) + (work / path).write_text(frameworks, encoding="utf-8") + for command in (["git", "init", "-q"], ["git", "add", "."]): + run(command, cwd=work, env=without_git_location(), check=True, timeout=60) + log.write_text("", encoding="utf-8") + result = run( + [bash_or_skip(), "-c", script], + cwd=work, + env={ + **without_git_location(), + "PATH": f"{bin_dir}{os.pathsep}{os.environ.get('PATH', os.defpath)}", + "STUB_LOG": str(log), + "DOTNET_VERSION": line, + }, + capture_output=True, + text=True, + encoding="utf-8", + timeout=60, + check=False, + ) + output = result.stdout + result.stderr + self.assertEqual(status, result.returncode, output) + self.assertEqual(want, log.read_text(encoding="utf-8").splitlines()) + if status: + self.assertIn(f"::error::No test project declares net{line}", output) + if line == "11.0": + self.assertIn("Skipping A/ATests.csproj", output) + if line == "10.0": + self.assertIn("Skipping C/CTests.csproj", output) + @unittest.skipUnless(shutil.which("jq"), "jq is what the step under test runs") def test_validator_refuses_a_python_versions_value_fromjson_would_admit(self) -> None: """fromJSON admits a JSON array of numbers, which is not a list of interpreter versions. @@ -2723,6 +2822,14 @@ def test_audit_bash_blocks_are_not_labeled_as_posix_shell(self) -> None: ) +# Answers the property read the way dotnet msbuild does, from a project file holding TargetFramework|TargetFrameworks. +DOTNET_MSBUILD_STAND_IN = ( + 'if [ "$1" = msbuild ]; then fw="$(cat "$2")"; fw="${fw:-|net10.0}"; ' + 'printf \'{"Properties":{"TargetFramework":"%s","TargetFrameworks":"%s"}}\\n\' ' + '"${fw%%|*}" "${fw#*|}"; exit 0; fi\n' +) + + def run_step_script(script: str, workspace: Path, env: dict[str, str]) -> tuple[int, str, str, str]: """Run a step's `script` in `workspace`, with `env` added.