diff --git a/.agents/skills/audit-a-repo/SKILL.md b/.agents/skills/audit-a-repo/SKILL.md index da6126e9c..5e543ea19 100644 --- a/.agents/skills/audit-a-repo/SKILL.md +++ b/.agents/skills/audit-a-repo/SKILL.md @@ -31,7 +31,7 @@ The audit is the fleet's measurement procedure. The failure shapes it guards aga - **Know what the runner does and does not prove.** `spec/audit.py` mechanizes the deterministic subset only: settings, rulesets, secret names, file and section presence, verbatim hashing, interface wiring, Dependabot coverage, branch facts. It evaluates no check under a type in `spec/project-types.json` (`AUDIT.md` section 4). So every per-type check is judged by hand, and a clean run is no evidence for them (`AUDIT.md` section 4). Silence from a tool that was never looking reads exactly like a pass. - **Judge letter and intent per check** and keep the vocabulary. A letter miss with intent satisfied is a drift finding. Both missing is a defect. Operational is binary over the applicable set. That vocabulary is in `AUDIT.md` sections 4 and 7. Do not invent a parallel scheme. - **Assert the Actions implement `WORKFLOW.md`** by outcome, not by matching catalog snippets byte for byte (`AUDIT.md` section 5). The method is the 5A static audit, each applicable guarantee cited in the form 5A sets out, then the 5B trace scenarios (`AUDIT.md` section 5). Read a workflow the repo only calls at the SHA it pins, throughout. The `workflow-ci-contract` skill summarizes that contract. -- **Check live settings, rulesets, and secrets from a hub checkout at `main`** with `AUDIT.md` section 6. Run `repo-config/configure.sh check` with the target repository and model for settings and rulesets, and `uv run --no-project --script spec/audit.py [RepoName]` for secrets, rather than constructing a local comparison. The hub payloads are the only repository-configuration source. +- **Check live settings, rulesets, and secrets from a hub checkout at `main`** with `AUDIT.md` section 6. Use a hub checkout at `develop` instead while the target's registry entry has merged there but not yet reached `main`. Run `repo-config/configure.sh check` with the target repository and model for settings and rulesets, and `uv run --no-project --script spec/audit.py [RepoName]` for secrets, rather than constructing a local comparison. The hub payloads are the only repository-configuration source. ## Reporting diff --git a/.agents/skills/branching-and-release-model/references/branch-protection-and-promotion.md b/.agents/skills/branching-and-release-model/references/branch-protection-and-promotion.md index 86efe171e..ad3c1117a 100644 --- a/.agents/skills/branching-and-release-model/references/branch-protection-and-promotion.md +++ b/.agents/skills/branching-and-release-model/references/branch-protection-and-promotion.md @@ -8,13 +8,15 @@ feature-branch PR, which the SKILL.md summary covers. ## Configuring branch protection: don't hand-build the rules -Delete **all** classic branch-protection rules and stray rulesets because rulesets are the only -protection mechanism. From a hub checkout at `main`, create **exactly two rulesets named `develop` -and `main`** from the hub's `repo-config/*.json` payloads. Run +From a hub checkout at `main`, create **exactly two rulesets named `develop` and `main`** from the +hub's `repo-config/*.json` payloads. Use a hub checkout at `develop` instead +while the repository's registry entry has merged there but not yet reached `main`. Run `repo-config/configure.sh apply / release|operational` from that checkout. The names are load-bearing because governance content and workflows reference them. The registry -`workflowModel` selects the `develop` payload for a registered repository. Pass the model -explicitly for a repository outside the registry. +`workflowModel` selects the `develop` payload for a registered repository. `apply` refuses a +repository outside the registry, writing nothing. Once `apply` has created both rulesets, delete +**all** classic branch-protection rules and stray rulesets, because rulesets are the only protection +mechanism. Deleted first, they would leave the branches unprotected wherever `apply` then refuses. ## Executing a `develop -> main` promotion safely diff --git a/.agents/skills/python-codestyle/SKILL.md b/.agents/skills/python-codestyle/SKILL.md index 54258415c..cd46358b0 100644 --- a/.agents/skills/python-codestyle/SKILL.md +++ b/.agents/skills/python-codestyle/SKILL.md @@ -3,15 +3,15 @@ name: python-codestyle description: >- Governs Python code style for ptr727/ProjectTemplate fleet repos: the build-versus-lint-only profile split, the uv/ruff/pyright/mypy/pytest toolchain, src layout, comment and docstring - conventions, type hints, naming, imports, patterns to avoid, test conventions, versioning, and the - --help and unknown-argument rule for a script. Use this whenever writing, reviewing, or editing a - .py file, a pyproject.toml, or a uv.lock, whenever running or choosing a Python formatting, lint, - type-check, or test command, pyright versus mypy included, whenever deciding whether a Python - subtree is a shippable project or a lint-only scripts tree, or whenever writing or reviewing a - Python test. Triggers even when the task looks like a small local fix ("just add a helper - function", "add a dependency") or a verification step ("run the tests"), because choosing pytest - before reading the profile turns an intentional unittest suite into a false missing-dependency - diagnosis. Applies only to a repo's Python side. + conventions, type hints, naming, imports, patterns to avoid, test conventions, versioning, the + --help and unknown-argument rule, and the SIGINT/SIGTERM rule for a script. Use this whenever + writing, reviewing, or editing a .py file, a pyproject.toml, or a uv.lock, whenever running or + choosing a Python formatting, lint, type-check, or test command, pyright versus mypy included, + whenever deciding whether a Python subtree is a shippable project or a lint-only scripts tree, or + whenever writing or reviewing a Python test. Triggers even when the task looks like a small local + fix ("just add a helper function", "add a dependency") or a verification step ("run the tests"), + because choosing pytest before reading the profile turns an intentional unittest suite into a + false missing-dependency diagnosis. Applies only to a repo's Python side. --- # Python Codestyle @@ -290,6 +290,31 @@ A command-line script is one a person or an agent runs by name. A hook its host +## Interrupts + + + +This applies to every Bash and Python script. `CODESTYLE.md` "Interrupts in Python" and "Interrupts in Shell" state each language's mechanics. + +- **On SIGINT or SIGTERM, a script releases what it holds before it exits.** It removes the temporary paths it created, releases the locks it took, and stops the child processes it started. A path, lock, or child left behind can stop the next run from starting, or feed it a half-written input. +- **A write to persistent state goes to a temporary path beside the target, then is renamed over it.** An interrupt then leaves the old content or the new, never a mix of both. A store with transactions of its own, such as an SQLite database, is written through those instead. A rename over an open database can corrupt it. +- **An interrupted script prints one line naming the signal, with no traceback, and exits 130 for SIGINT or 143 for SIGTERM.** Each status is 128 plus the signal number, the status a shell reports for a process that signal ended. +- **A script takes this rule when it is created or next edited.** An existing script is not edited for this rule alone. +- **A script that holds a lock, temporary state, or a child process owes a test that signals it mid-run.** The test sends SIGINT or SIGTERM, then asserts the matching exit status and that nothing the script held remains. It is skipped on Windows, which cannot deliver either signal for a script to handle. A script holding none of these owes no such test. + + + +## Interrupts in Python + + + +- **SIGINT and SIGTERM take one path.** Python raises `KeyboardInterrupt` on SIGINT. The entry point installs a SIGTERM handler with `signal.signal` that records the signal and raises `KeyboardInterrupt`. +- **The entry point catches `KeyboardInterrupt` once, and any handler below it that catches the exception re-raises it.** It prints the line `CODESTYLE.md` "Interrupts" requires, then exits 143 where the SIGTERM handler recorded a signal and 130 otherwise. +- **What the script holds is released by `with` blocks and `finally` clauses as the exception unwinds.** A `subprocess.Popen` child is stopped in a `finally` clause with `terminate()`, then `wait()`, since leaving its `with` block does not stop it. That child runs without `shell=True`, so `terminate()` reaches the command rather than a shell around it. +- **The rename over persistent state uses `os.replace`.** `os.rename` and `Path.rename` fail on Windows when the target exists. + + + [docs-link]: https://docs.pytest.org/ diff --git a/.agents/skills/shell-codestyle/SKILL.md b/.agents/skills/shell-codestyle/SKILL.md index 575674f75..b9fb0abe8 100644 --- a/.agents/skills/shell-codestyle/SKILL.md +++ b/.agents/skills/shell-codestyle/SKILL.md @@ -4,14 +4,14 @@ description: >- Governs Bash/shell script style for ptr727/ProjectTemplate fleet repos: when a bootstrap or host-tool script may be shell instead of Python, the mandatory set -Eeuo pipefail header, the pipefail-versus-early-reader pitfall, self-recursive command shims, self-locating scripts, the - shellcheck-plus-shfmt clean-compile, the --help and unknown-argument rule, and the why-not-what - comment rule. Use this whenever writing, reviewing, or editing a shell script (`.sh`, or an - extensionless bash/sh shebang script), whenever deciding whether a new script should be Bash or - Python, whenever a `curl`/`grep`/`jq`-style pipeline looks like it silently swallowed a failure, - or whenever a script or probe writes a wrapper or shim named after a command it also calls. - Triggers even when the task looks like a one-line tweak, because a missing `-e`/`pipefail` or a - pipe its producer closes early stays invisible until it fails. Applies in any repo holding a shell - script. + shellcheck-plus-shfmt clean-compile, the --help and unknown-argument rule, the SIGINT/SIGTERM + rule, and the why-not-what comment rule. Use this whenever writing, reviewing, or editing a shell + script (`.sh`, or an extensionless bash/sh shebang script), whenever deciding whether a new script + should be Bash or Python, whenever a `curl`/`grep`/`jq`-style pipeline looks like it silently + swallowed a failure, or whenever a script or probe writes a wrapper or shim named after a command + it also calls. Triggers even when the task looks like a one-line tweak, because a missing + `-e`/`pipefail` or a pipe its producer closes early stays invisible until it fails. Applies in any + repo holding a shell script. --- # Shell Codestyle @@ -92,3 +92,27 @@ A command-line script is one a person or an agent runs by name. A hook its host - **An argument the script does not recognize is refused**, with a non-zero exit before any read or write. The refusal names it as an unknown or unrecognized option, argument, flag, or parameter, and PowerShell's own refusal of a parameter it cannot bind counts. So a PowerShell script declaring its own parameters refuses a literal `--help` like any other unrecognized argument. Where no parameter takes the remaining arguments, the binder's refusal does that. A script with such a parameter refuses a dash-prefixed leftover itself. An unrecognized first argument is never taken as a default mode or as a target. + +## Interrupts + + + +This applies to every Bash and Python script. `CODESTYLE.md` "Interrupts in Python" and "Interrupts in Shell" state each language's mechanics. + +- **On SIGINT or SIGTERM, a script releases what it holds before it exits.** It removes the temporary paths it created, releases the locks it took, and stops the child processes it started. A path, lock, or child left behind can stop the next run from starting, or feed it a half-written input. +- **A write to persistent state goes to a temporary path beside the target, then is renamed over it.** An interrupt then leaves the old content or the new, never a mix of both. A store with transactions of its own, such as an SQLite database, is written through those instead. A rename over an open database can corrupt it. +- **An interrupted script prints one line naming the signal, with no traceback, and exits 130 for SIGINT or 143 for SIGTERM.** Each status is 128 plus the signal number, the status a shell reports for a process that signal ended. +- **A script takes this rule when it is created or next edited.** An existing script is not edited for this rule alone. +- **A script that holds a lock, temporary state, or a child process owes a test that signals it mid-run.** The test sends SIGINT or SIGTERM, then asserts the matching exit status and that nothing the script held remains. It is skipped on Windows, which cannot deliver either signal for a script to handle. A script holding none of these owes no such test. + + + +## Interrupts in Shell + + + +- **Cleanup of temporary paths and locks runs in the script's `EXIT` trap.** Bash runs that trap when SIGINT or SIGTERM ends the script, as well as on a normal exit. +- **Every script sets an `INT` trap and a `TERM` trap, which stop its children and keep the status.** Each one sends SIGTERM with `kill` to the children the script started, then waits for them with `wait`. It then prints the line `CODESTYLE.md` "Interrupts" requires and exits 130 or 143. The children's process IDs are held in an array, such as `pids`, set to `()` before the traps are set. A trap skips the `kill` and the `wait` while `${#pids[@]}` is 0, a test `set -u` allows on an empty array in every Bash version. Under `set -u`, an unset one would end the trap before the line prints. The `kill` takes `2>/dev/null`, since a child that already exited makes it print an error. Both take `|| :`, since under `set -e` a non-zero status from either ends the trap before the line prints. SIGTERM is the signal sent because a background child ignores SIGINT. Other cleanup stays in the `EXIT` trap. +- **A long-running external command runs in the background, and the script waits for it with `wait "$pid"`, so its exit status reaches `set -e`.** Bash runs a trap only after a foreground command returns, while a trapped signal ends a `wait` at once. Only the script's own shell starts such a child. One that a subshell or a pipeline element starts never reaches the script's array or its `wait`. A background child that reads standard input takes `<&0`, since bash otherwise gives it `/dev/null`. The trap's `kill` reaches only the process `$!` names. So a function, a group, a subshell, a pipeline, or `sh -c` runs in the foreground instead. There the trap runs once the command it interrupted returns, so nothing the script started is orphaned. + + diff --git a/.agents/skills/standup-a-repo/SKILL.md b/.agents/skills/standup-a-repo/SKILL.md index 3a97abc58..0bfa9e3ef 100644 --- a/.agents/skills/standup-a-repo/SKILL.md +++ b/.agents/skills/standup-a-repo/SKILL.md @@ -88,8 +88,9 @@ maintainer can supply what section 0A lists. 8. **Settings, rulesets, and secrets.** STANDUP.md section 4: confirm the remote and the GitHub repository agree before running anything else here. Then run `repo-config/configure.sh check owner/repo release` (substitute `operational` for an - operational repo) from the hub at `main`. A non-zero exit there means drift was found, not a - command failure. Review what it reports. Then run the same command's `apply` subcommand, never from a hand-built or carried copy. It + operational repo) from the hub at `main`. Use the hub at `develop` instead while the repo's + registry entry has merged there but not yet reached `main`. A non-zero exit there means drift + was found, not a command failure. Review what it reports. Then run the same command's `apply` subcommand, never from a hand-built or carried copy. It idempotently reconciles the repo to the full committed configuration regardless of what `check` reported. diff --git a/.agents/skills/workflow-ci-contract/references/architecture.md b/.agents/skills/workflow-ci-contract/references/architecture.md index 18dab24ec..d3575a609 100644 --- a/.agents/skills/workflow-ci-contract/references/architecture.md +++ b/.agents/skills/workflow-ci-contract/references/architecture.md @@ -26,7 +26,7 @@ flowchart LR develop -->|merge commit, enforced lint CI| main ``` -The direct commit is an **allowance, not a substitute for review**. The ruleset drops the pull-request *requirement*, which permits a direct push without withdrawing the pull request. So a change worth reviewing still takes one, and both paths reach `develop` legally. Which changes those are is stated as a shape rather than a line count in `GOVERNANCE.md` "Operational Repositories". That section owns the test and is the one place it is written, since nothing in a ruleset can apply it. What differs is when validation lands. On the direct-commit path the commit is already on the branch, so CI can only be advisory after the fact. That is the accepted cost of the model. On the pull-request path the change has not landed, so validation is pre-merge and actionable, the moment it is worth the most. The lint workflow's `pull_request` trigger therefore names `develop` alongside `main` (`WORKFLOW.md` section 6). That is what makes **D1.2** hold here, since its input is *any* PR and the operational model is no exception. The check is reported on a `develop` PR rather than required. That is because a required status check on `develop` binds the direct push too, and would dissolve the allowance the model is built on. +The direct commit is an **allowance, not a substitute for review**. The ruleset drops the pull-request *requirement*, which permits a direct push without withdrawing the pull request. So a change worth reviewing still takes one, and both paths reach `develop` legally. Which changes those are is stated as a shape rather than a line count in `GOVERNANCE.md` "Operational Repositories". That section owns the test and is the one place it is written, since nothing in a ruleset can apply it. What differs is when validation lands. On the direct-commit path the commit is already on the branch, so CI can only be advisory after the fact. That is the accepted cost of the model. On the pull-request path the change has not landed, so validation is pre-merge and actionable, the moment it is worth the most. The lint workflow's `pull_request` trigger therefore filters no base branch (`WORKFLOW.md` section 6). That is what makes **D1.2** hold here, since its input is *any* PR and the operational model is no exception. The check is reported on a `develop` PR rather than required. That is because a required status check on `develop` binds the direct push too, and would dissolve the allowance the model is built on. Their CI is lint/validation only: editorconfig/EOL plus domain linters such as Home Assistant or ESPHome config validation or a firmware build, but **no unit tests**. So the D-guarantees in `WORKFLOW.md` section 4 that assume a build/test pipeline are **N/A** exactly as for `source-only` (`WORKFLOW.md` section 6). What binds is the promotion gate and the source-only release on manual dispatch (`releaseTrigger: dispatch-only`, tag + source zip). At the promotion gate, the `develop -> main` PR must pass the required `Check pull request workflow status job`. Branch-model rulesets are specified in `GOVERNANCE.md` "Branching Model" rather than in `WORKFLOW.md`. diff --git a/.agents/skills/workflow-ci-contract/references/d-guarantees.md b/.agents/skills/workflow-ci-contract/references/d-guarantees.md index 003b878a6..ee54e96f9 100644 --- a/.agents/skills/workflow-ci-contract/references/d-guarantees.md +++ b/.agents/skills/workflow-ci-contract/references/d-guarantees.md @@ -14,8 +14,8 @@ The required behaviors, organized by domain. Each is a **MUST**, and its `Output - **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.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. 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`** setting 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 also reads a **`.codecov.yml`** at the repository root, so that name serves too. 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.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.* ### D2 - Input/State Validation at Entry @@ -70,7 +70,7 @@ The required behaviors, organized by domain. Each is a **MUST**, and its `Output - **D8.1 Merge-bot.** Output: the merge-bot enables auto-merge on `opened`/`reopened` for **every** Dependabot tier including semver-major. The required checks are the gate, not the bump magnitude. The merge-bot dispatches `--squash`/`--merge` by the PR's base ref, and disables on a maintainer-pushed `synchronize`. Its concurrency is keyed on the **PR number**, not `github.ref`. On `closed` it deletes a merged in-repo bot head when the caller opts in. The push leases the branch tip to the merged head, so a moved branch survives. *Prevents: two PRs colliding in auto-merge.* - **D8.2 CodeGen and Dependabot.** Output: codegen runs as a matrix over both branches and is deterministic from an external source. `.github/dependabot.yml` targets both branches, and security PRs go to the default branch. -- **D8.3 Upstream-version tracker.** Output: a scheduled resolver prints a JSON `name -> version` object to a committed state file. It opens a rolling per-branch bump PR naming only the moved keys, and the merge-bot auto-merges it. The `main` pin push publishes via the release gate, while a `develop` pin does not auto-publish. It ships via a `develop` dispatch (prerelease) or the next promotion to `main`. The tracker's `bump-branch-prefix` + `branches` MUST match a merge-bot rule, or auto-merge silently never fires. That rule is one of the built-in `-` head/base pairs or a `rules` entry the caller passes. A tracker whose bump needs a human decision instead sets `auto-merge: false`, which prefixes the head so no merge-bot rule matches it, whatever `bump-branch-prefix` names. +- **D8.3 Upstream-version tracker.** Output: a scheduled resolver prints a JSON `name -> version` object to a committed state file. It opens a rolling per-branch bump PR naming only the moved keys, and the merge-bot auto-merges it. The `main` pin push the merge-bot makes publishes via the release gate, while a `develop` pin does not auto-publish. It ships via a `develop` dispatch (prerelease) or the next promotion to `main`. The tracker's `bump-branch-prefix` + `branches` MUST match a merge-bot rule, or auto-merge silently never fires. That rule is one of the built-in `-` head/base pairs or a `rules` entry the caller passes. A tracker whose bump needs a human decision instead sets `auto-merge: false`, which prefixes the head so no merge-bot rule matches it, whatever `bump-branch-prefix` names. A `main` pin it carries then lands by a human merge, which never auto-publishes (D4.1), so it ships on the next publish. - **D8.4 An identity allowlist used as a gate fails loud.** Where a gate compares `github.actor` (or a PR author) against hard-coded bot identities, the non-matching branch **emits a `::warning::`** on an otherwise-legitimate trigger. There it does not fall through silently. Output: a run that declines to act on an unrecognized identity is visibly annotated. *Prevents: the App being renamed, replaced, or reinstalled under a new slug, after which the comparison quietly evaluates false and the gate stops firing. The result is a green and silent run that looks identical to a healthy one.* The masking matters most where a second path hides the loss. One such path is a weekly schedule that keeps publishing, so the only symptom is release *timeliness*, easily missed for months. Where the failure is self-announcing instead (the merge-bot simply stops merging, so bot PRs visibly pile up) an annotation is optional. The delete job compares the same `user.login` as the merge jobs, so a renamed App already shows as piled-up bot PRs. Resolving the identity at run time (mint an App token, read `GET /app`) removes the hard-coded string entirely. Run-time resolution is the escalation if an allowlist proves fragile in practice. ### D9 - Style / Static diff --git a/.agents/skills/workflow-ci-contract/references/test-methodology.md b/.agents/skills/workflow-ci-contract/references/test-methodology.md index 464cb1416..804d8412a 100644 --- a/.agents/skills/workflow-ci-contract/references/test-methodology.md +++ b/.agents/skills/workflow-ci-contract/references/test-methodology.md @@ -12,7 +12,7 @@ An agent verifies a project in escalating modes, then renders a verdict. **Skip Assert the structural fact each *applicable* D-guarantee implies, and record **pass**, **fail**, or **N/A** per item. This section says how an audit is run and recorded rather than what must hold. A guarantee names its own constructs, and the requirement is `WORKFLOW.md` section 4's item together with whatever that item defers to. -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`. +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`. 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. @@ -28,11 +28,11 @@ For each *applicable* scenario, evaluate every job's `if:`/`needs:` against the | S4 | PR base = default branch, carrying a build target | smoke versions as prerelease, validate-release **succeeds** with its check exited early per D2.2, so the default-branch arm does **not** fire, aggregator **success**, promotion not blocked | D1.5, D2.2, D3.2 | | S5 | bot push to `main` not touching a release path (e.g. an Actions bump) | the paths filter excludes it, so nothing publishes | D4.1 | | S6 | code-affecting **bot** push to `main` (a human push/promotion, or any develop push, does not) | the `plan` job gates it to the App/Dependabot actor, and `main` publishes a release | D3, D4 | -| S7 | publish run (schedule, a bot push to main, or a dispatch) | builds the **one** trigger branch. `main` -> `X.Y.Z`, `prerelease=false`, registry stable, readme run. `develop` -> `X.Y.Z-g`, `prerelease=true`, registry prerelease. `release-asset-*` is consumed then deleted, and each package build-artifact (`nuget-build-*`, `pypi-build-*`) is deleted after its publish. **No dangling artifacts** | D3, D4, D5, D6, D7 | +| S7 | publish run (schedule, a bot push to main, or a dispatch). A schedule or push run at an already-released version is S9 instead | builds the **one** trigger branch. `main` -> `X.Y.Z`, `prerelease=false`, registry stable, readme run. `develop` -> `X.Y.Z-g`, `prerelease=true`, registry prerelease. `release-asset-*` is consumed then deleted, and each package build-artifact (`nuget-build-*`, `pypi-build-*`) is deleted after its publish. **No dangling artifacts** | D3, D4, D5, D6, D7 | | S8 | dispatch from a ref other than `main` or `develop` | **fails fast** | D2.3 | | S9 | re-run publish on a schedule or push trigger, version unchanged (a dispatch re-run refreshes the release instead, per D4.4) | release-create **skipped**, `release-asset-*` delete **skipped**; NuGet/PyPI pushes no-op (server dedupe); **package build-artifacts still deleted** (their download succeeded); **Docker still re-pushes** the image; no duplicate release | D4.4, D5.2 | | S10 | branch/version classification disagree | validate-release **fails loud**, build/publish skip | D2.2 | -| S11 | scheduled upstream-version bump (wrapper) | resolver detects a change -> commits the state file -> opens a per-branch bump PR. The merge-bot auto-merges it, or leaves it for the maintainer where the tracker sets `auto-merge: false` (D8.3). The `main` pin then publishes via the gate. A develop pin does not auto-publish, shipping instead via a develop dispatch or promotion | D8.3, D3.5 | +| S11 | scheduled upstream-version bump (wrapper) | resolver detects a change -> commits the state file -> opens a per-branch bump PR. The merge-bot auto-merges it, or leaves it for the maintainer where the tracker sets `auto-merge: false` (D8.3). A `main` pin the merge-bot merges then publishes via the gate, and one the maintainer merges ships on the next publish (D4.1). A develop pin does not auto-publish, shipping instead via a develop dispatch or promotion | D8.3, D3.5 | | 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 | diff --git a/.claude-plugin/fleet-skills/.source-digests/audit-a-repo b/.claude-plugin/fleet-skills/.source-digests/audit-a-repo index df3ca0687..bf6606459 100644 --- a/.claude-plugin/fleet-skills/.source-digests/audit-a-repo +++ b/.claude-plugin/fleet-skills/.source-digests/audit-a-repo @@ -1 +1 @@ -bdf4e79884d907c5 +3718c3a0989f1e69 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 8bd7c1c14..c2bccce51 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 @@ -5daca42e1358780f +90f9e04a7cb49c9b diff --git a/.claude-plugin/fleet-skills/.source-digests/python-codestyle b/.claude-plugin/fleet-skills/.source-digests/python-codestyle index e893d1e37..67e109950 100644 --- a/.claude-plugin/fleet-skills/.source-digests/python-codestyle +++ b/.claude-plugin/fleet-skills/.source-digests/python-codestyle @@ -1 +1 @@ -c3a73f436e6d2012 +ba17c5c61eb5876c diff --git a/.claude-plugin/fleet-skills/.source-digests/shell-codestyle b/.claude-plugin/fleet-skills/.source-digests/shell-codestyle index b1695c6f3..63c876fa3 100644 --- a/.claude-plugin/fleet-skills/.source-digests/shell-codestyle +++ b/.claude-plugin/fleet-skills/.source-digests/shell-codestyle @@ -1 +1 @@ -518c9ee541665ecd +cd82a59297ef1235 diff --git a/.claude-plugin/fleet-skills/.source-digests/standup-a-repo b/.claude-plugin/fleet-skills/.source-digests/standup-a-repo index c2f1c1333..dd4b9c83c 100644 --- a/.claude-plugin/fleet-skills/.source-digests/standup-a-repo +++ b/.claude-plugin/fleet-skills/.source-digests/standup-a-repo @@ -1 +1 @@ -8c67a1aaf0213a69 +8a38eeb99188b8c4 diff --git a/.claude-plugin/fleet-skills/.source-digests/workflow-ci-contract b/.claude-plugin/fleet-skills/.source-digests/workflow-ci-contract index 0cc58dc61..9e5a04783 100644 --- a/.claude-plugin/fleet-skills/.source-digests/workflow-ci-contract +++ b/.claude-plugin/fleet-skills/.source-digests/workflow-ci-contract @@ -1 +1 @@ -ab64601c6a1d9459 +b7fed1b040a657eb diff --git a/.claude-plugin/fleet-skills/skills/audit-a-repo/SKILL.md b/.claude-plugin/fleet-skills/skills/audit-a-repo/SKILL.md index da6126e9c..5e543ea19 100644 --- a/.claude-plugin/fleet-skills/skills/audit-a-repo/SKILL.md +++ b/.claude-plugin/fleet-skills/skills/audit-a-repo/SKILL.md @@ -31,7 +31,7 @@ The audit is the fleet's measurement procedure. The failure shapes it guards aga - **Know what the runner does and does not prove.** `spec/audit.py` mechanizes the deterministic subset only: settings, rulesets, secret names, file and section presence, verbatim hashing, interface wiring, Dependabot coverage, branch facts. It evaluates no check under a type in `spec/project-types.json` (`AUDIT.md` section 4). So every per-type check is judged by hand, and a clean run is no evidence for them (`AUDIT.md` section 4). Silence from a tool that was never looking reads exactly like a pass. - **Judge letter and intent per check** and keep the vocabulary. A letter miss with intent satisfied is a drift finding. Both missing is a defect. Operational is binary over the applicable set. That vocabulary is in `AUDIT.md` sections 4 and 7. Do not invent a parallel scheme. - **Assert the Actions implement `WORKFLOW.md`** by outcome, not by matching catalog snippets byte for byte (`AUDIT.md` section 5). The method is the 5A static audit, each applicable guarantee cited in the form 5A sets out, then the 5B trace scenarios (`AUDIT.md` section 5). Read a workflow the repo only calls at the SHA it pins, throughout. The `workflow-ci-contract` skill summarizes that contract. -- **Check live settings, rulesets, and secrets from a hub checkout at `main`** with `AUDIT.md` section 6. Run `repo-config/configure.sh check` with the target repository and model for settings and rulesets, and `uv run --no-project --script spec/audit.py [RepoName]` for secrets, rather than constructing a local comparison. The hub payloads are the only repository-configuration source. +- **Check live settings, rulesets, and secrets from a hub checkout at `main`** with `AUDIT.md` section 6. Use a hub checkout at `develop` instead while the target's registry entry has merged there but not yet reached `main`. Run `repo-config/configure.sh check` with the target repository and model for settings and rulesets, and `uv run --no-project --script spec/audit.py [RepoName]` for secrets, rather than constructing a local comparison. The hub payloads are the only repository-configuration source. ## Reporting diff --git a/.claude-plugin/fleet-skills/skills/branching-and-release-model/references/branch-protection-and-promotion.md b/.claude-plugin/fleet-skills/skills/branching-and-release-model/references/branch-protection-and-promotion.md index 86efe171e..ad3c1117a 100644 --- a/.claude-plugin/fleet-skills/skills/branching-and-release-model/references/branch-protection-and-promotion.md +++ b/.claude-plugin/fleet-skills/skills/branching-and-release-model/references/branch-protection-and-promotion.md @@ -8,13 +8,15 @@ feature-branch PR, which the SKILL.md summary covers. ## Configuring branch protection: don't hand-build the rules -Delete **all** classic branch-protection rules and stray rulesets because rulesets are the only -protection mechanism. From a hub checkout at `main`, create **exactly two rulesets named `develop` -and `main`** from the hub's `repo-config/*.json` payloads. Run +From a hub checkout at `main`, create **exactly two rulesets named `develop` and `main`** from the +hub's `repo-config/*.json` payloads. Use a hub checkout at `develop` instead +while the repository's registry entry has merged there but not yet reached `main`. Run `repo-config/configure.sh apply / release|operational` from that checkout. The names are load-bearing because governance content and workflows reference them. The registry -`workflowModel` selects the `develop` payload for a registered repository. Pass the model -explicitly for a repository outside the registry. +`workflowModel` selects the `develop` payload for a registered repository. `apply` refuses a +repository outside the registry, writing nothing. Once `apply` has created both rulesets, delete +**all** classic branch-protection rules and stray rulesets, because rulesets are the only protection +mechanism. Deleted first, they would leave the branches unprotected wherever `apply` then refuses. ## Executing a `develop -> main` promotion safely diff --git a/.claude-plugin/fleet-skills/skills/python-codestyle/SKILL.md b/.claude-plugin/fleet-skills/skills/python-codestyle/SKILL.md index 54258415c..cd46358b0 100644 --- a/.claude-plugin/fleet-skills/skills/python-codestyle/SKILL.md +++ b/.claude-plugin/fleet-skills/skills/python-codestyle/SKILL.md @@ -3,15 +3,15 @@ name: python-codestyle description: >- Governs Python code style for ptr727/ProjectTemplate fleet repos: the build-versus-lint-only profile split, the uv/ruff/pyright/mypy/pytest toolchain, src layout, comment and docstring - conventions, type hints, naming, imports, patterns to avoid, test conventions, versioning, and the - --help and unknown-argument rule for a script. Use this whenever writing, reviewing, or editing a - .py file, a pyproject.toml, or a uv.lock, whenever running or choosing a Python formatting, lint, - type-check, or test command, pyright versus mypy included, whenever deciding whether a Python - subtree is a shippable project or a lint-only scripts tree, or whenever writing or reviewing a - Python test. Triggers even when the task looks like a small local fix ("just add a helper - function", "add a dependency") or a verification step ("run the tests"), because choosing pytest - before reading the profile turns an intentional unittest suite into a false missing-dependency - diagnosis. Applies only to a repo's Python side. + conventions, type hints, naming, imports, patterns to avoid, test conventions, versioning, the + --help and unknown-argument rule, and the SIGINT/SIGTERM rule for a script. Use this whenever + writing, reviewing, or editing a .py file, a pyproject.toml, or a uv.lock, whenever running or + choosing a Python formatting, lint, type-check, or test command, pyright versus mypy included, + whenever deciding whether a Python subtree is a shippable project or a lint-only scripts tree, or + whenever writing or reviewing a Python test. Triggers even when the task looks like a small local + fix ("just add a helper function", "add a dependency") or a verification step ("run the tests"), + because choosing pytest before reading the profile turns an intentional unittest suite into a + false missing-dependency diagnosis. Applies only to a repo's Python side. --- # Python Codestyle @@ -290,6 +290,31 @@ A command-line script is one a person or an agent runs by name. A hook its host +## Interrupts + + + +This applies to every Bash and Python script. `CODESTYLE.md` "Interrupts in Python" and "Interrupts in Shell" state each language's mechanics. + +- **On SIGINT or SIGTERM, a script releases what it holds before it exits.** It removes the temporary paths it created, releases the locks it took, and stops the child processes it started. A path, lock, or child left behind can stop the next run from starting, or feed it a half-written input. +- **A write to persistent state goes to a temporary path beside the target, then is renamed over it.** An interrupt then leaves the old content or the new, never a mix of both. A store with transactions of its own, such as an SQLite database, is written through those instead. A rename over an open database can corrupt it. +- **An interrupted script prints one line naming the signal, with no traceback, and exits 130 for SIGINT or 143 for SIGTERM.** Each status is 128 plus the signal number, the status a shell reports for a process that signal ended. +- **A script takes this rule when it is created or next edited.** An existing script is not edited for this rule alone. +- **A script that holds a lock, temporary state, or a child process owes a test that signals it mid-run.** The test sends SIGINT or SIGTERM, then asserts the matching exit status and that nothing the script held remains. It is skipped on Windows, which cannot deliver either signal for a script to handle. A script holding none of these owes no such test. + + + +## Interrupts in Python + + + +- **SIGINT and SIGTERM take one path.** Python raises `KeyboardInterrupt` on SIGINT. The entry point installs a SIGTERM handler with `signal.signal` that records the signal and raises `KeyboardInterrupt`. +- **The entry point catches `KeyboardInterrupt` once, and any handler below it that catches the exception re-raises it.** It prints the line `CODESTYLE.md` "Interrupts" requires, then exits 143 where the SIGTERM handler recorded a signal and 130 otherwise. +- **What the script holds is released by `with` blocks and `finally` clauses as the exception unwinds.** A `subprocess.Popen` child is stopped in a `finally` clause with `terminate()`, then `wait()`, since leaving its `with` block does not stop it. That child runs without `shell=True`, so `terminate()` reaches the command rather than a shell around it. +- **The rename over persistent state uses `os.replace`.** `os.rename` and `Path.rename` fail on Windows when the target exists. + + + [docs-link]: https://docs.pytest.org/ diff --git a/.claude-plugin/fleet-skills/skills/shell-codestyle/SKILL.md b/.claude-plugin/fleet-skills/skills/shell-codestyle/SKILL.md index 575674f75..b9fb0abe8 100644 --- a/.claude-plugin/fleet-skills/skills/shell-codestyle/SKILL.md +++ b/.claude-plugin/fleet-skills/skills/shell-codestyle/SKILL.md @@ -4,14 +4,14 @@ description: >- Governs Bash/shell script style for ptr727/ProjectTemplate fleet repos: when a bootstrap or host-tool script may be shell instead of Python, the mandatory set -Eeuo pipefail header, the pipefail-versus-early-reader pitfall, self-recursive command shims, self-locating scripts, the - shellcheck-plus-shfmt clean-compile, the --help and unknown-argument rule, and the why-not-what - comment rule. Use this whenever writing, reviewing, or editing a shell script (`.sh`, or an - extensionless bash/sh shebang script), whenever deciding whether a new script should be Bash or - Python, whenever a `curl`/`grep`/`jq`-style pipeline looks like it silently swallowed a failure, - or whenever a script or probe writes a wrapper or shim named after a command it also calls. - Triggers even when the task looks like a one-line tweak, because a missing `-e`/`pipefail` or a - pipe its producer closes early stays invisible until it fails. Applies in any repo holding a shell - script. + shellcheck-plus-shfmt clean-compile, the --help and unknown-argument rule, the SIGINT/SIGTERM + rule, and the why-not-what comment rule. Use this whenever writing, reviewing, or editing a shell + script (`.sh`, or an extensionless bash/sh shebang script), whenever deciding whether a new script + should be Bash or Python, whenever a `curl`/`grep`/`jq`-style pipeline looks like it silently + swallowed a failure, or whenever a script or probe writes a wrapper or shim named after a command + it also calls. Triggers even when the task looks like a one-line tweak, because a missing + `-e`/`pipefail` or a pipe its producer closes early stays invisible until it fails. Applies in any + repo holding a shell script. --- # Shell Codestyle @@ -92,3 +92,27 @@ A command-line script is one a person or an agent runs by name. A hook its host - **An argument the script does not recognize is refused**, with a non-zero exit before any read or write. The refusal names it as an unknown or unrecognized option, argument, flag, or parameter, and PowerShell's own refusal of a parameter it cannot bind counts. So a PowerShell script declaring its own parameters refuses a literal `--help` like any other unrecognized argument. Where no parameter takes the remaining arguments, the binder's refusal does that. A script with such a parameter refuses a dash-prefixed leftover itself. An unrecognized first argument is never taken as a default mode or as a target. + +## Interrupts + + + +This applies to every Bash and Python script. `CODESTYLE.md` "Interrupts in Python" and "Interrupts in Shell" state each language's mechanics. + +- **On SIGINT or SIGTERM, a script releases what it holds before it exits.** It removes the temporary paths it created, releases the locks it took, and stops the child processes it started. A path, lock, or child left behind can stop the next run from starting, or feed it a half-written input. +- **A write to persistent state goes to a temporary path beside the target, then is renamed over it.** An interrupt then leaves the old content or the new, never a mix of both. A store with transactions of its own, such as an SQLite database, is written through those instead. A rename over an open database can corrupt it. +- **An interrupted script prints one line naming the signal, with no traceback, and exits 130 for SIGINT or 143 for SIGTERM.** Each status is 128 plus the signal number, the status a shell reports for a process that signal ended. +- **A script takes this rule when it is created or next edited.** An existing script is not edited for this rule alone. +- **A script that holds a lock, temporary state, or a child process owes a test that signals it mid-run.** The test sends SIGINT or SIGTERM, then asserts the matching exit status and that nothing the script held remains. It is skipped on Windows, which cannot deliver either signal for a script to handle. A script holding none of these owes no such test. + + + +## Interrupts in Shell + + + +- **Cleanup of temporary paths and locks runs in the script's `EXIT` trap.** Bash runs that trap when SIGINT or SIGTERM ends the script, as well as on a normal exit. +- **Every script sets an `INT` trap and a `TERM` trap, which stop its children and keep the status.** Each one sends SIGTERM with `kill` to the children the script started, then waits for them with `wait`. It then prints the line `CODESTYLE.md` "Interrupts" requires and exits 130 or 143. The children's process IDs are held in an array, such as `pids`, set to `()` before the traps are set. A trap skips the `kill` and the `wait` while `${#pids[@]}` is 0, a test `set -u` allows on an empty array in every Bash version. Under `set -u`, an unset one would end the trap before the line prints. The `kill` takes `2>/dev/null`, since a child that already exited makes it print an error. Both take `|| :`, since under `set -e` a non-zero status from either ends the trap before the line prints. SIGTERM is the signal sent because a background child ignores SIGINT. Other cleanup stays in the `EXIT` trap. +- **A long-running external command runs in the background, and the script waits for it with `wait "$pid"`, so its exit status reaches `set -e`.** Bash runs a trap only after a foreground command returns, while a trapped signal ends a `wait` at once. Only the script's own shell starts such a child. One that a subshell or a pipeline element starts never reaches the script's array or its `wait`. A background child that reads standard input takes `<&0`, since bash otherwise gives it `/dev/null`. The trap's `kill` reaches only the process `$!` names. So a function, a group, a subshell, a pipeline, or `sh -c` runs in the foreground instead. There the trap runs once the command it interrupted returns, so nothing the script started is orphaned. + + diff --git a/.claude-plugin/fleet-skills/skills/standup-a-repo/SKILL.md b/.claude-plugin/fleet-skills/skills/standup-a-repo/SKILL.md index 3a97abc58..0bfa9e3ef 100644 --- a/.claude-plugin/fleet-skills/skills/standup-a-repo/SKILL.md +++ b/.claude-plugin/fleet-skills/skills/standup-a-repo/SKILL.md @@ -88,8 +88,9 @@ maintainer can supply what section 0A lists. 8. **Settings, rulesets, and secrets.** STANDUP.md section 4: confirm the remote and the GitHub repository agree before running anything else here. Then run `repo-config/configure.sh check owner/repo release` (substitute `operational` for an - operational repo) from the hub at `main`. A non-zero exit there means drift was found, not a - command failure. Review what it reports. Then run the same command's `apply` subcommand, never from a hand-built or carried copy. It + operational repo) from the hub at `main`. Use the hub at `develop` instead while the repo's + registry entry has merged there but not yet reached `main`. A non-zero exit there means drift + was found, not a command failure. Review what it reports. Then run the same command's `apply` subcommand, never from a hand-built or carried copy. It idempotently reconciles the repo to the full committed configuration regardless of what `check` reported. 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 18dab24ec..d3575a609 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 @@ -26,7 +26,7 @@ flowchart LR develop -->|merge commit, enforced lint CI| main ``` -The direct commit is an **allowance, not a substitute for review**. The ruleset drops the pull-request *requirement*, which permits a direct push without withdrawing the pull request. So a change worth reviewing still takes one, and both paths reach `develop` legally. Which changes those are is stated as a shape rather than a line count in `GOVERNANCE.md` "Operational Repositories". That section owns the test and is the one place it is written, since nothing in a ruleset can apply it. What differs is when validation lands. On the direct-commit path the commit is already on the branch, so CI can only be advisory after the fact. That is the accepted cost of the model. On the pull-request path the change has not landed, so validation is pre-merge and actionable, the moment it is worth the most. The lint workflow's `pull_request` trigger therefore names `develop` alongside `main` (`WORKFLOW.md` section 6). That is what makes **D1.2** hold here, since its input is *any* PR and the operational model is no exception. The check is reported on a `develop` PR rather than required. That is because a required status check on `develop` binds the direct push too, and would dissolve the allowance the model is built on. +The direct commit is an **allowance, not a substitute for review**. The ruleset drops the pull-request *requirement*, which permits a direct push without withdrawing the pull request. So a change worth reviewing still takes one, and both paths reach `develop` legally. Which changes those are is stated as a shape rather than a line count in `GOVERNANCE.md` "Operational Repositories". That section owns the test and is the one place it is written, since nothing in a ruleset can apply it. What differs is when validation lands. On the direct-commit path the commit is already on the branch, so CI can only be advisory after the fact. That is the accepted cost of the model. On the pull-request path the change has not landed, so validation is pre-merge and actionable, the moment it is worth the most. The lint workflow's `pull_request` trigger therefore filters no base branch (`WORKFLOW.md` section 6). That is what makes **D1.2** hold here, since its input is *any* PR and the operational model is no exception. The check is reported on a `develop` PR rather than required. That is because a required status check on `develop` binds the direct push too, and would dissolve the allowance the model is built on. Their CI is lint/validation only: editorconfig/EOL plus domain linters such as Home Assistant or ESPHome config validation or a firmware build, but **no unit tests**. So the D-guarantees in `WORKFLOW.md` section 4 that assume a build/test pipeline are **N/A** exactly as for `source-only` (`WORKFLOW.md` section 6). What binds is the promotion gate and the source-only release on manual dispatch (`releaseTrigger: dispatch-only`, tag + source zip). At the promotion gate, the `develop -> main` PR must pass the required `Check pull request workflow status job`. Branch-model rulesets are specified in `GOVERNANCE.md` "Branching Model" rather than in `WORKFLOW.md`. 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 003b878a6..ee54e96f9 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 @@ -14,8 +14,8 @@ The required behaviors, organized by domain. Each is a **MUST**, and its `Output - **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.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. 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`** setting 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 also reads a **`.codecov.yml`** at the repository root, so that name serves too. 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.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.* ### D2 - Input/State Validation at Entry @@ -70,7 +70,7 @@ The required behaviors, organized by domain. Each is a **MUST**, and its `Output - **D8.1 Merge-bot.** Output: the merge-bot enables auto-merge on `opened`/`reopened` for **every** Dependabot tier including semver-major. The required checks are the gate, not the bump magnitude. The merge-bot dispatches `--squash`/`--merge` by the PR's base ref, and disables on a maintainer-pushed `synchronize`. Its concurrency is keyed on the **PR number**, not `github.ref`. On `closed` it deletes a merged in-repo bot head when the caller opts in. The push leases the branch tip to the merged head, so a moved branch survives. *Prevents: two PRs colliding in auto-merge.* - **D8.2 CodeGen and Dependabot.** Output: codegen runs as a matrix over both branches and is deterministic from an external source. `.github/dependabot.yml` targets both branches, and security PRs go to the default branch. -- **D8.3 Upstream-version tracker.** Output: a scheduled resolver prints a JSON `name -> version` object to a committed state file. It opens a rolling per-branch bump PR naming only the moved keys, and the merge-bot auto-merges it. The `main` pin push publishes via the release gate, while a `develop` pin does not auto-publish. It ships via a `develop` dispatch (prerelease) or the next promotion to `main`. The tracker's `bump-branch-prefix` + `branches` MUST match a merge-bot rule, or auto-merge silently never fires. That rule is one of the built-in `-` head/base pairs or a `rules` entry the caller passes. A tracker whose bump needs a human decision instead sets `auto-merge: false`, which prefixes the head so no merge-bot rule matches it, whatever `bump-branch-prefix` names. +- **D8.3 Upstream-version tracker.** Output: a scheduled resolver prints a JSON `name -> version` object to a committed state file. It opens a rolling per-branch bump PR naming only the moved keys, and the merge-bot auto-merges it. The `main` pin push the merge-bot makes publishes via the release gate, while a `develop` pin does not auto-publish. It ships via a `develop` dispatch (prerelease) or the next promotion to `main`. The tracker's `bump-branch-prefix` + `branches` MUST match a merge-bot rule, or auto-merge silently never fires. That rule is one of the built-in `-` head/base pairs or a `rules` entry the caller passes. A tracker whose bump needs a human decision instead sets `auto-merge: false`, which prefixes the head so no merge-bot rule matches it, whatever `bump-branch-prefix` names. A `main` pin it carries then lands by a human merge, which never auto-publishes (D4.1), so it ships on the next publish. - **D8.4 An identity allowlist used as a gate fails loud.** Where a gate compares `github.actor` (or a PR author) against hard-coded bot identities, the non-matching branch **emits a `::warning::`** on an otherwise-legitimate trigger. There it does not fall through silently. Output: a run that declines to act on an unrecognized identity is visibly annotated. *Prevents: the App being renamed, replaced, or reinstalled under a new slug, after which the comparison quietly evaluates false and the gate stops firing. The result is a green and silent run that looks identical to a healthy one.* The masking matters most where a second path hides the loss. One such path is a weekly schedule that keeps publishing, so the only symptom is release *timeliness*, easily missed for months. Where the failure is self-announcing instead (the merge-bot simply stops merging, so bot PRs visibly pile up) an annotation is optional. The delete job compares the same `user.login` as the merge jobs, so a renamed App already shows as piled-up bot PRs. Resolving the identity at run time (mint an App token, read `GET /app`) removes the hard-coded string entirely. Run-time resolution is the escalation if an allowlist proves fragile in practice. ### D9 - Style / Static 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 464cb1416..804d8412a 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 @@ -12,7 +12,7 @@ An agent verifies a project in escalating modes, then renders a verdict. **Skip Assert the structural fact each *applicable* D-guarantee implies, and record **pass**, **fail**, or **N/A** per item. This section says how an audit is run and recorded rather than what must hold. A guarantee names its own constructs, and the requirement is `WORKFLOW.md` section 4's item together with whatever that item defers to. -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`. +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`. 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. @@ -28,11 +28,11 @@ For each *applicable* scenario, evaluate every job's `if:`/`needs:` against the | S4 | PR base = default branch, carrying a build target | smoke versions as prerelease, validate-release **succeeds** with its check exited early per D2.2, so the default-branch arm does **not** fire, aggregator **success**, promotion not blocked | D1.5, D2.2, D3.2 | | S5 | bot push to `main` not touching a release path (e.g. an Actions bump) | the paths filter excludes it, so nothing publishes | D4.1 | | S6 | code-affecting **bot** push to `main` (a human push/promotion, or any develop push, does not) | the `plan` job gates it to the App/Dependabot actor, and `main` publishes a release | D3, D4 | -| S7 | publish run (schedule, a bot push to main, or a dispatch) | builds the **one** trigger branch. `main` -> `X.Y.Z`, `prerelease=false`, registry stable, readme run. `develop` -> `X.Y.Z-g`, `prerelease=true`, registry prerelease. `release-asset-*` is consumed then deleted, and each package build-artifact (`nuget-build-*`, `pypi-build-*`) is deleted after its publish. **No dangling artifacts** | D3, D4, D5, D6, D7 | +| S7 | publish run (schedule, a bot push to main, or a dispatch). A schedule or push run at an already-released version is S9 instead | builds the **one** trigger branch. `main` -> `X.Y.Z`, `prerelease=false`, registry stable, readme run. `develop` -> `X.Y.Z-g`, `prerelease=true`, registry prerelease. `release-asset-*` is consumed then deleted, and each package build-artifact (`nuget-build-*`, `pypi-build-*`) is deleted after its publish. **No dangling artifacts** | D3, D4, D5, D6, D7 | | S8 | dispatch from a ref other than `main` or `develop` | **fails fast** | D2.3 | | S9 | re-run publish on a schedule or push trigger, version unchanged (a dispatch re-run refreshes the release instead, per D4.4) | release-create **skipped**, `release-asset-*` delete **skipped**; NuGet/PyPI pushes no-op (server dedupe); **package build-artifacts still deleted** (their download succeeded); **Docker still re-pushes** the image; no duplicate release | D4.4, D5.2 | | S10 | branch/version classification disagree | validate-release **fails loud**, build/publish skip | D2.2 | -| S11 | scheduled upstream-version bump (wrapper) | resolver detects a change -> commits the state file -> opens a per-branch bump PR. The merge-bot auto-merges it, or leaves it for the maintainer where the tracker sets `auto-merge: false` (D8.3). The `main` pin then publishes via the gate. A develop pin does not auto-publish, shipping instead via a develop dispatch or promotion | D8.3, D3.5 | +| S11 | scheduled upstream-version bump (wrapper) | resolver detects a change -> commits the state file -> opens a per-branch bump PR. The merge-bot auto-merges it, or leaves it for the maintainer where the tracker sets `auto-merge: false` (D8.3). A `main` pin the merge-bot merges then publishes via the gate, and one the maintainer merges ships on the next publish (D4.1). A develop pin does not auto-publish, shipping instead via a develop dispatch or promotion | D8.3, D3.5 | | 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 | diff --git a/codecov.yml b/.codecov.yml similarity index 100% rename from codecov.yml rename to .codecov.yml diff --git a/.github/skills/audit-a-repo/SKILL.md b/.github/skills/audit-a-repo/SKILL.md index da6126e9c..5e543ea19 100644 --- a/.github/skills/audit-a-repo/SKILL.md +++ b/.github/skills/audit-a-repo/SKILL.md @@ -31,7 +31,7 @@ The audit is the fleet's measurement procedure. The failure shapes it guards aga - **Know what the runner does and does not prove.** `spec/audit.py` mechanizes the deterministic subset only: settings, rulesets, secret names, file and section presence, verbatim hashing, interface wiring, Dependabot coverage, branch facts. It evaluates no check under a type in `spec/project-types.json` (`AUDIT.md` section 4). So every per-type check is judged by hand, and a clean run is no evidence for them (`AUDIT.md` section 4). Silence from a tool that was never looking reads exactly like a pass. - **Judge letter and intent per check** and keep the vocabulary. A letter miss with intent satisfied is a drift finding. Both missing is a defect. Operational is binary over the applicable set. That vocabulary is in `AUDIT.md` sections 4 and 7. Do not invent a parallel scheme. - **Assert the Actions implement `WORKFLOW.md`** by outcome, not by matching catalog snippets byte for byte (`AUDIT.md` section 5). The method is the 5A static audit, each applicable guarantee cited in the form 5A sets out, then the 5B trace scenarios (`AUDIT.md` section 5). Read a workflow the repo only calls at the SHA it pins, throughout. The `workflow-ci-contract` skill summarizes that contract. -- **Check live settings, rulesets, and secrets from a hub checkout at `main`** with `AUDIT.md` section 6. Run `repo-config/configure.sh check` with the target repository and model for settings and rulesets, and `uv run --no-project --script spec/audit.py [RepoName]` for secrets, rather than constructing a local comparison. The hub payloads are the only repository-configuration source. +- **Check live settings, rulesets, and secrets from a hub checkout at `main`** with `AUDIT.md` section 6. Use a hub checkout at `develop` instead while the target's registry entry has merged there but not yet reached `main`. Run `repo-config/configure.sh check` with the target repository and model for settings and rulesets, and `uv run --no-project --script spec/audit.py [RepoName]` for secrets, rather than constructing a local comparison. The hub payloads are the only repository-configuration source. ## Reporting diff --git a/.github/skills/branching-and-release-model/references/branch-protection-and-promotion.md b/.github/skills/branching-and-release-model/references/branch-protection-and-promotion.md index 86efe171e..ad3c1117a 100644 --- a/.github/skills/branching-and-release-model/references/branch-protection-and-promotion.md +++ b/.github/skills/branching-and-release-model/references/branch-protection-and-promotion.md @@ -8,13 +8,15 @@ feature-branch PR, which the SKILL.md summary covers. ## Configuring branch protection: don't hand-build the rules -Delete **all** classic branch-protection rules and stray rulesets because rulesets are the only -protection mechanism. From a hub checkout at `main`, create **exactly two rulesets named `develop` -and `main`** from the hub's `repo-config/*.json` payloads. Run +From a hub checkout at `main`, create **exactly two rulesets named `develop` and `main`** from the +hub's `repo-config/*.json` payloads. Use a hub checkout at `develop` instead +while the repository's registry entry has merged there but not yet reached `main`. Run `repo-config/configure.sh apply / release|operational` from that checkout. The names are load-bearing because governance content and workflows reference them. The registry -`workflowModel` selects the `develop` payload for a registered repository. Pass the model -explicitly for a repository outside the registry. +`workflowModel` selects the `develop` payload for a registered repository. `apply` refuses a +repository outside the registry, writing nothing. Once `apply` has created both rulesets, delete +**all** classic branch-protection rules and stray rulesets, because rulesets are the only protection +mechanism. Deleted first, they would leave the branches unprotected wherever `apply` then refuses. ## Executing a `develop -> main` promotion safely diff --git a/.github/skills/python-codestyle/SKILL.md b/.github/skills/python-codestyle/SKILL.md index 54258415c..cd46358b0 100644 --- a/.github/skills/python-codestyle/SKILL.md +++ b/.github/skills/python-codestyle/SKILL.md @@ -3,15 +3,15 @@ name: python-codestyle description: >- Governs Python code style for ptr727/ProjectTemplate fleet repos: the build-versus-lint-only profile split, the uv/ruff/pyright/mypy/pytest toolchain, src layout, comment and docstring - conventions, type hints, naming, imports, patterns to avoid, test conventions, versioning, and the - --help and unknown-argument rule for a script. Use this whenever writing, reviewing, or editing a - .py file, a pyproject.toml, or a uv.lock, whenever running or choosing a Python formatting, lint, - type-check, or test command, pyright versus mypy included, whenever deciding whether a Python - subtree is a shippable project or a lint-only scripts tree, or whenever writing or reviewing a - Python test. Triggers even when the task looks like a small local fix ("just add a helper - function", "add a dependency") or a verification step ("run the tests"), because choosing pytest - before reading the profile turns an intentional unittest suite into a false missing-dependency - diagnosis. Applies only to a repo's Python side. + conventions, type hints, naming, imports, patterns to avoid, test conventions, versioning, the + --help and unknown-argument rule, and the SIGINT/SIGTERM rule for a script. Use this whenever + writing, reviewing, or editing a .py file, a pyproject.toml, or a uv.lock, whenever running or + choosing a Python formatting, lint, type-check, or test command, pyright versus mypy included, + whenever deciding whether a Python subtree is a shippable project or a lint-only scripts tree, or + whenever writing or reviewing a Python test. Triggers even when the task looks like a small local + fix ("just add a helper function", "add a dependency") or a verification step ("run the tests"), + because choosing pytest before reading the profile turns an intentional unittest suite into a + false missing-dependency diagnosis. Applies only to a repo's Python side. --- # Python Codestyle @@ -290,6 +290,31 @@ A command-line script is one a person or an agent runs by name. A hook its host +## Interrupts + + + +This applies to every Bash and Python script. `CODESTYLE.md` "Interrupts in Python" and "Interrupts in Shell" state each language's mechanics. + +- **On SIGINT or SIGTERM, a script releases what it holds before it exits.** It removes the temporary paths it created, releases the locks it took, and stops the child processes it started. A path, lock, or child left behind can stop the next run from starting, or feed it a half-written input. +- **A write to persistent state goes to a temporary path beside the target, then is renamed over it.** An interrupt then leaves the old content or the new, never a mix of both. A store with transactions of its own, such as an SQLite database, is written through those instead. A rename over an open database can corrupt it. +- **An interrupted script prints one line naming the signal, with no traceback, and exits 130 for SIGINT or 143 for SIGTERM.** Each status is 128 plus the signal number, the status a shell reports for a process that signal ended. +- **A script takes this rule when it is created or next edited.** An existing script is not edited for this rule alone. +- **A script that holds a lock, temporary state, or a child process owes a test that signals it mid-run.** The test sends SIGINT or SIGTERM, then asserts the matching exit status and that nothing the script held remains. It is skipped on Windows, which cannot deliver either signal for a script to handle. A script holding none of these owes no such test. + + + +## Interrupts in Python + + + +- **SIGINT and SIGTERM take one path.** Python raises `KeyboardInterrupt` on SIGINT. The entry point installs a SIGTERM handler with `signal.signal` that records the signal and raises `KeyboardInterrupt`. +- **The entry point catches `KeyboardInterrupt` once, and any handler below it that catches the exception re-raises it.** It prints the line `CODESTYLE.md` "Interrupts" requires, then exits 143 where the SIGTERM handler recorded a signal and 130 otherwise. +- **What the script holds is released by `with` blocks and `finally` clauses as the exception unwinds.** A `subprocess.Popen` child is stopped in a `finally` clause with `terminate()`, then `wait()`, since leaving its `with` block does not stop it. That child runs without `shell=True`, so `terminate()` reaches the command rather than a shell around it. +- **The rename over persistent state uses `os.replace`.** `os.rename` and `Path.rename` fail on Windows when the target exists. + + + [docs-link]: https://docs.pytest.org/ diff --git a/.github/skills/shell-codestyle/SKILL.md b/.github/skills/shell-codestyle/SKILL.md index 575674f75..b9fb0abe8 100644 --- a/.github/skills/shell-codestyle/SKILL.md +++ b/.github/skills/shell-codestyle/SKILL.md @@ -4,14 +4,14 @@ description: >- Governs Bash/shell script style for ptr727/ProjectTemplate fleet repos: when a bootstrap or host-tool script may be shell instead of Python, the mandatory set -Eeuo pipefail header, the pipefail-versus-early-reader pitfall, self-recursive command shims, self-locating scripts, the - shellcheck-plus-shfmt clean-compile, the --help and unknown-argument rule, and the why-not-what - comment rule. Use this whenever writing, reviewing, or editing a shell script (`.sh`, or an - extensionless bash/sh shebang script), whenever deciding whether a new script should be Bash or - Python, whenever a `curl`/`grep`/`jq`-style pipeline looks like it silently swallowed a failure, - or whenever a script or probe writes a wrapper or shim named after a command it also calls. - Triggers even when the task looks like a one-line tweak, because a missing `-e`/`pipefail` or a - pipe its producer closes early stays invisible until it fails. Applies in any repo holding a shell - script. + shellcheck-plus-shfmt clean-compile, the --help and unknown-argument rule, the SIGINT/SIGTERM + rule, and the why-not-what comment rule. Use this whenever writing, reviewing, or editing a shell + script (`.sh`, or an extensionless bash/sh shebang script), whenever deciding whether a new script + should be Bash or Python, whenever a `curl`/`grep`/`jq`-style pipeline looks like it silently + swallowed a failure, or whenever a script or probe writes a wrapper or shim named after a command + it also calls. Triggers even when the task looks like a one-line tweak, because a missing + `-e`/`pipefail` or a pipe its producer closes early stays invisible until it fails. Applies in any + repo holding a shell script. --- # Shell Codestyle @@ -92,3 +92,27 @@ A command-line script is one a person or an agent runs by name. A hook its host - **An argument the script does not recognize is refused**, with a non-zero exit before any read or write. The refusal names it as an unknown or unrecognized option, argument, flag, or parameter, and PowerShell's own refusal of a parameter it cannot bind counts. So a PowerShell script declaring its own parameters refuses a literal `--help` like any other unrecognized argument. Where no parameter takes the remaining arguments, the binder's refusal does that. A script with such a parameter refuses a dash-prefixed leftover itself. An unrecognized first argument is never taken as a default mode or as a target. + +## Interrupts + + + +This applies to every Bash and Python script. `CODESTYLE.md` "Interrupts in Python" and "Interrupts in Shell" state each language's mechanics. + +- **On SIGINT or SIGTERM, a script releases what it holds before it exits.** It removes the temporary paths it created, releases the locks it took, and stops the child processes it started. A path, lock, or child left behind can stop the next run from starting, or feed it a half-written input. +- **A write to persistent state goes to a temporary path beside the target, then is renamed over it.** An interrupt then leaves the old content or the new, never a mix of both. A store with transactions of its own, such as an SQLite database, is written through those instead. A rename over an open database can corrupt it. +- **An interrupted script prints one line naming the signal, with no traceback, and exits 130 for SIGINT or 143 for SIGTERM.** Each status is 128 plus the signal number, the status a shell reports for a process that signal ended. +- **A script takes this rule when it is created or next edited.** An existing script is not edited for this rule alone. +- **A script that holds a lock, temporary state, or a child process owes a test that signals it mid-run.** The test sends SIGINT or SIGTERM, then asserts the matching exit status and that nothing the script held remains. It is skipped on Windows, which cannot deliver either signal for a script to handle. A script holding none of these owes no such test. + + + +## Interrupts in Shell + + + +- **Cleanup of temporary paths and locks runs in the script's `EXIT` trap.** Bash runs that trap when SIGINT or SIGTERM ends the script, as well as on a normal exit. +- **Every script sets an `INT` trap and a `TERM` trap, which stop its children and keep the status.** Each one sends SIGTERM with `kill` to the children the script started, then waits for them with `wait`. It then prints the line `CODESTYLE.md` "Interrupts" requires and exits 130 or 143. The children's process IDs are held in an array, such as `pids`, set to `()` before the traps are set. A trap skips the `kill` and the `wait` while `${#pids[@]}` is 0, a test `set -u` allows on an empty array in every Bash version. Under `set -u`, an unset one would end the trap before the line prints. The `kill` takes `2>/dev/null`, since a child that already exited makes it print an error. Both take `|| :`, since under `set -e` a non-zero status from either ends the trap before the line prints. SIGTERM is the signal sent because a background child ignores SIGINT. Other cleanup stays in the `EXIT` trap. +- **A long-running external command runs in the background, and the script waits for it with `wait "$pid"`, so its exit status reaches `set -e`.** Bash runs a trap only after a foreground command returns, while a trapped signal ends a `wait` at once. Only the script's own shell starts such a child. One that a subshell or a pipeline element starts never reaches the script's array or its `wait`. A background child that reads standard input takes `<&0`, since bash otherwise gives it `/dev/null`. The trap's `kill` reaches only the process `$!` names. So a function, a group, a subshell, a pipeline, or `sh -c` runs in the foreground instead. There the trap runs once the command it interrupted returns, so nothing the script started is orphaned. + + diff --git a/.github/skills/standup-a-repo/SKILL.md b/.github/skills/standup-a-repo/SKILL.md index 3a97abc58..0bfa9e3ef 100644 --- a/.github/skills/standup-a-repo/SKILL.md +++ b/.github/skills/standup-a-repo/SKILL.md @@ -88,8 +88,9 @@ maintainer can supply what section 0A lists. 8. **Settings, rulesets, and secrets.** STANDUP.md section 4: confirm the remote and the GitHub repository agree before running anything else here. Then run `repo-config/configure.sh check owner/repo release` (substitute `operational` for an - operational repo) from the hub at `main`. A non-zero exit there means drift was found, not a - command failure. Review what it reports. Then run the same command's `apply` subcommand, never from a hand-built or carried copy. It + operational repo) from the hub at `main`. Use the hub at `develop` instead while the repo's + registry entry has merged there but not yet reached `main`. A non-zero exit there means drift + was found, not a command failure. Review what it reports. Then run the same command's `apply` subcommand, never from a hand-built or carried copy. It idempotently reconciles the repo to the full committed configuration regardless of what `check` reported. diff --git a/.github/skills/workflow-ci-contract/references/architecture.md b/.github/skills/workflow-ci-contract/references/architecture.md index 18dab24ec..d3575a609 100644 --- a/.github/skills/workflow-ci-contract/references/architecture.md +++ b/.github/skills/workflow-ci-contract/references/architecture.md @@ -26,7 +26,7 @@ flowchart LR develop -->|merge commit, enforced lint CI| main ``` -The direct commit is an **allowance, not a substitute for review**. The ruleset drops the pull-request *requirement*, which permits a direct push without withdrawing the pull request. So a change worth reviewing still takes one, and both paths reach `develop` legally. Which changes those are is stated as a shape rather than a line count in `GOVERNANCE.md` "Operational Repositories". That section owns the test and is the one place it is written, since nothing in a ruleset can apply it. What differs is when validation lands. On the direct-commit path the commit is already on the branch, so CI can only be advisory after the fact. That is the accepted cost of the model. On the pull-request path the change has not landed, so validation is pre-merge and actionable, the moment it is worth the most. The lint workflow's `pull_request` trigger therefore names `develop` alongside `main` (`WORKFLOW.md` section 6). That is what makes **D1.2** hold here, since its input is *any* PR and the operational model is no exception. The check is reported on a `develop` PR rather than required. That is because a required status check on `develop` binds the direct push too, and would dissolve the allowance the model is built on. +The direct commit is an **allowance, not a substitute for review**. The ruleset drops the pull-request *requirement*, which permits a direct push without withdrawing the pull request. So a change worth reviewing still takes one, and both paths reach `develop` legally. Which changes those are is stated as a shape rather than a line count in `GOVERNANCE.md` "Operational Repositories". That section owns the test and is the one place it is written, since nothing in a ruleset can apply it. What differs is when validation lands. On the direct-commit path the commit is already on the branch, so CI can only be advisory after the fact. That is the accepted cost of the model. On the pull-request path the change has not landed, so validation is pre-merge and actionable, the moment it is worth the most. The lint workflow's `pull_request` trigger therefore filters no base branch (`WORKFLOW.md` section 6). That is what makes **D1.2** hold here, since its input is *any* PR and the operational model is no exception. The check is reported on a `develop` PR rather than required. That is because a required status check on `develop` binds the direct push too, and would dissolve the allowance the model is built on. Their CI is lint/validation only: editorconfig/EOL plus domain linters such as Home Assistant or ESPHome config validation or a firmware build, but **no unit tests**. So the D-guarantees in `WORKFLOW.md` section 4 that assume a build/test pipeline are **N/A** exactly as for `source-only` (`WORKFLOW.md` section 6). What binds is the promotion gate and the source-only release on manual dispatch (`releaseTrigger: dispatch-only`, tag + source zip). At the promotion gate, the `develop -> main` PR must pass the required `Check pull request workflow status job`. Branch-model rulesets are specified in `GOVERNANCE.md` "Branching Model" rather than in `WORKFLOW.md`. diff --git a/.github/skills/workflow-ci-contract/references/d-guarantees.md b/.github/skills/workflow-ci-contract/references/d-guarantees.md index 003b878a6..ee54e96f9 100644 --- a/.github/skills/workflow-ci-contract/references/d-guarantees.md +++ b/.github/skills/workflow-ci-contract/references/d-guarantees.md @@ -14,8 +14,8 @@ The required behaviors, organized by domain. Each is a **MUST**, and its `Output - **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.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. 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`** setting 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 also reads a **`.codecov.yml`** at the repository root, so that name serves too. 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.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.* ### D2 - Input/State Validation at Entry @@ -70,7 +70,7 @@ The required behaviors, organized by domain. Each is a **MUST**, and its `Output - **D8.1 Merge-bot.** Output: the merge-bot enables auto-merge on `opened`/`reopened` for **every** Dependabot tier including semver-major. The required checks are the gate, not the bump magnitude. The merge-bot dispatches `--squash`/`--merge` by the PR's base ref, and disables on a maintainer-pushed `synchronize`. Its concurrency is keyed on the **PR number**, not `github.ref`. On `closed` it deletes a merged in-repo bot head when the caller opts in. The push leases the branch tip to the merged head, so a moved branch survives. *Prevents: two PRs colliding in auto-merge.* - **D8.2 CodeGen and Dependabot.** Output: codegen runs as a matrix over both branches and is deterministic from an external source. `.github/dependabot.yml` targets both branches, and security PRs go to the default branch. -- **D8.3 Upstream-version tracker.** Output: a scheduled resolver prints a JSON `name -> version` object to a committed state file. It opens a rolling per-branch bump PR naming only the moved keys, and the merge-bot auto-merges it. The `main` pin push publishes via the release gate, while a `develop` pin does not auto-publish. It ships via a `develop` dispatch (prerelease) or the next promotion to `main`. The tracker's `bump-branch-prefix` + `branches` MUST match a merge-bot rule, or auto-merge silently never fires. That rule is one of the built-in `-` head/base pairs or a `rules` entry the caller passes. A tracker whose bump needs a human decision instead sets `auto-merge: false`, which prefixes the head so no merge-bot rule matches it, whatever `bump-branch-prefix` names. +- **D8.3 Upstream-version tracker.** Output: a scheduled resolver prints a JSON `name -> version` object to a committed state file. It opens a rolling per-branch bump PR naming only the moved keys, and the merge-bot auto-merges it. The `main` pin push the merge-bot makes publishes via the release gate, while a `develop` pin does not auto-publish. It ships via a `develop` dispatch (prerelease) or the next promotion to `main`. The tracker's `bump-branch-prefix` + `branches` MUST match a merge-bot rule, or auto-merge silently never fires. That rule is one of the built-in `-` head/base pairs or a `rules` entry the caller passes. A tracker whose bump needs a human decision instead sets `auto-merge: false`, which prefixes the head so no merge-bot rule matches it, whatever `bump-branch-prefix` names. A `main` pin it carries then lands by a human merge, which never auto-publishes (D4.1), so it ships on the next publish. - **D8.4 An identity allowlist used as a gate fails loud.** Where a gate compares `github.actor` (or a PR author) against hard-coded bot identities, the non-matching branch **emits a `::warning::`** on an otherwise-legitimate trigger. There it does not fall through silently. Output: a run that declines to act on an unrecognized identity is visibly annotated. *Prevents: the App being renamed, replaced, or reinstalled under a new slug, after which the comparison quietly evaluates false and the gate stops firing. The result is a green and silent run that looks identical to a healthy one.* The masking matters most where a second path hides the loss. One such path is a weekly schedule that keeps publishing, so the only symptom is release *timeliness*, easily missed for months. Where the failure is self-announcing instead (the merge-bot simply stops merging, so bot PRs visibly pile up) an annotation is optional. The delete job compares the same `user.login` as the merge jobs, so a renamed App already shows as piled-up bot PRs. Resolving the identity at run time (mint an App token, read `GET /app`) removes the hard-coded string entirely. Run-time resolution is the escalation if an allowlist proves fragile in practice. ### D9 - Style / Static diff --git a/.github/skills/workflow-ci-contract/references/test-methodology.md b/.github/skills/workflow-ci-contract/references/test-methodology.md index 464cb1416..804d8412a 100644 --- a/.github/skills/workflow-ci-contract/references/test-methodology.md +++ b/.github/skills/workflow-ci-contract/references/test-methodology.md @@ -12,7 +12,7 @@ An agent verifies a project in escalating modes, then renders a verdict. **Skip Assert the structural fact each *applicable* D-guarantee implies, and record **pass**, **fail**, or **N/A** per item. This section says how an audit is run and recorded rather than what must hold. A guarantee names its own constructs, and the requirement is `WORKFLOW.md` section 4's item together with whatever that item defers to. -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`. +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`. 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. @@ -28,11 +28,11 @@ For each *applicable* scenario, evaluate every job's `if:`/`needs:` against the | S4 | PR base = default branch, carrying a build target | smoke versions as prerelease, validate-release **succeeds** with its check exited early per D2.2, so the default-branch arm does **not** fire, aggregator **success**, promotion not blocked | D1.5, D2.2, D3.2 | | S5 | bot push to `main` not touching a release path (e.g. an Actions bump) | the paths filter excludes it, so nothing publishes | D4.1 | | S6 | code-affecting **bot** push to `main` (a human push/promotion, or any develop push, does not) | the `plan` job gates it to the App/Dependabot actor, and `main` publishes a release | D3, D4 | -| S7 | publish run (schedule, a bot push to main, or a dispatch) | builds the **one** trigger branch. `main` -> `X.Y.Z`, `prerelease=false`, registry stable, readme run. `develop` -> `X.Y.Z-g`, `prerelease=true`, registry prerelease. `release-asset-*` is consumed then deleted, and each package build-artifact (`nuget-build-*`, `pypi-build-*`) is deleted after its publish. **No dangling artifacts** | D3, D4, D5, D6, D7 | +| S7 | publish run (schedule, a bot push to main, or a dispatch). A schedule or push run at an already-released version is S9 instead | builds the **one** trigger branch. `main` -> `X.Y.Z`, `prerelease=false`, registry stable, readme run. `develop` -> `X.Y.Z-g`, `prerelease=true`, registry prerelease. `release-asset-*` is consumed then deleted, and each package build-artifact (`nuget-build-*`, `pypi-build-*`) is deleted after its publish. **No dangling artifacts** | D3, D4, D5, D6, D7 | | S8 | dispatch from a ref other than `main` or `develop` | **fails fast** | D2.3 | | S9 | re-run publish on a schedule or push trigger, version unchanged (a dispatch re-run refreshes the release instead, per D4.4) | release-create **skipped**, `release-asset-*` delete **skipped**; NuGet/PyPI pushes no-op (server dedupe); **package build-artifacts still deleted** (their download succeeded); **Docker still re-pushes** the image; no duplicate release | D4.4, D5.2 | | S10 | branch/version classification disagree | validate-release **fails loud**, build/publish skip | D2.2 | -| S11 | scheduled upstream-version bump (wrapper) | resolver detects a change -> commits the state file -> opens a per-branch bump PR. The merge-bot auto-merges it, or leaves it for the maintainer where the tracker sets `auto-merge: false` (D8.3). The `main` pin then publishes via the gate. A develop pin does not auto-publish, shipping instead via a develop dispatch or promotion | D8.3, D3.5 | +| S11 | scheduled upstream-version bump (wrapper) | resolver detects a change -> commits the state file -> opens a per-branch bump PR. The merge-bot auto-merges it, or leaves it for the maintainer where the tracker sets `auto-merge: false` (D8.3). A `main` pin the merge-bot merges then publishes via the gate, and one the maintainer merges ships on the next publish (D4.1). A develop pin does not auto-publish, shipping instead via a develop dispatch or promotion | D8.3, D3.5 | | 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 | diff --git a/.vscode/tasks.json b/.vscode/tasks.json index a4676156d..705f6afc2 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -2,7 +2,7 @@ "version": "2.0.0", "tasks": [ { - "label": "Ruff Format", + "label": "ruff format", "type": "process", "command": "uvx", "args": [ @@ -18,7 +18,7 @@ } }, { - "label": "Ruff Check", + "label": "ruff check", "type": "process", "command": "uvx", "args": [ @@ -50,8 +50,8 @@ "label": "Python Format", "dependsOrder": "sequence", "dependsOn": [ - "Ruff Format", - "Ruff Check", + "ruff format", + "ruff check", "Python Types" ], "group": { "kind": "build", "isDefault": true }, diff --git a/AUDIT.md b/AUDIT.md index 26390e025..a743bf233 100644 --- a/AUDIT.md +++ b/AUDIT.md @@ -100,7 +100,7 @@ Run [`WORKFLOW.md`][workflow]'s methodology against the repo's **own** Actions, ## 6. Validate Settings, Rulesets, and Secrets -- **General settings, the registry description, labels, rulesets, the Dependabot security features, the fleet project link, and deployment environments**. Fetch the hub and check out `main`. Run `repo-config/configure.sh check "/" ""` from that checkout. Pass the target repository and its registry `workflowModel` explicitly. The token needs project access as well as the admin the ruleset endpoints require. That is because a token without it cannot read the project link, and the command reports that group as failing rather than as clean. The command's own error names the scope to grant. The host needs a runnable `py -3` or `python3` too. That is because a run against a hub checkout resolves the registry description through [`spec/resolve_description.py`][resolve-description] and exits before the first check when neither interpreter answers. The command checks what `configure.sh apply` writes. That covers the declared settings, the derived settings and the registry description, the declared labels, and the Dependabot security features. It also covers the shared `main` ruleset, the `develop` ruleset the model selects, and the link to the fleet project the hub declares. It reports the live `bypass_actors` list without asserting it, because bypass authority is a per-repository human decision. It also checks one group apply never writes, the deployment environments the registry's `environments` declares for the repo. It checks that each one exists and that its deployment-branch policy is the form declared. It also checks that under a `custom` policy the entries it allows are exactly the declared branches. So anything added by hand reads as drift. An environment the registry declares nothing about is reported rather than asserted, since GitHub creates some on its own. Neither this command nor the **Secrets** bullet below queries an environment's own secret and variable stores. So a clean run says nothing about whether an environment holds what a deploy needs. In those stores the API exposes a secret's name but not its value, and a variable's name and value both. +- **General settings, the registry description, labels, rulesets, the Dependabot security features, the fleet project link, and deployment environments**. Fetch the hub and check out `main`. Check out `develop` instead where the target's registry entry has merged there but not yet reached `main`. Run `repo-config/configure.sh check "/" ""` from that checkout. Pass the target repository and its registry `workflowModel` explicitly. The token needs project access as well as the admin the ruleset endpoints require. That is because a token without it cannot read the project link, and the command reports that group as failing rather than as clean. The command's own error names the scope to grant. The host needs a runnable `py -3` or `python3` too. That is because a run against a hub checkout resolves the registry description through [`spec/resolve_description.py`][resolve-description] and exits before the first check when neither interpreter answers. The command checks what `configure.sh apply` writes. That covers the declared settings, the derived settings and the registry description, the declared labels, and the Dependabot security features. It also covers the shared `main` ruleset, the `develop` ruleset the model selects, and the link to the fleet project the hub declares. It reports the live `bypass_actors` list without asserting it, because bypass authority is a per-repository human decision. It also checks one group apply never writes, the deployment environments the registry's `environments` declares for the repo. It checks that each one exists and that its deployment-branch policy is the form declared. It also checks that under a `custom` policy the entries it allows are exactly the declared branches. So anything added by hand reads as drift. An environment the registry declares nothing about is reported rather than asserted, since GitHub creates some on its own. Neither this command nor the **Secrets** bullet below queries an environment's own secret and variable stores. So a clean run says nothing about whether an environment holds what a deploy needs. In those stores the API exposes a secret's name but not its value, and a variable's name and value both. - **Secrets** - from the same hub checkout, run [`spec/audit.py`][audit-runner] as `uv run --no-project --script spec/audit.py ""` and read the findings it prints with a `secrets:` prefix. That argument is the registry entry name rather than the `/` form `configure.sh` takes, and an `/` argument prints `Not cataloged` and exits 2. The runner reads both the Actions and the Dependabot store on every repo. A token that cannot read either one fails that repo's whole run with an error rather than reporting names as missing. It resolves what each store must hold from the hub's own [`spec/secrets.json`][secrets] plus the registry entry's `publish[]`/`types[]`/`requiredSecrets[]`. That file's `baseline` requires its names in both stores for every fleet repo. A mechanism adds to a store only where the mechanism's own `stores` list names that store. A declared type claims nothing where the entry's profile for it reads `lint-only`. It claims no coverage token where the tree carries no tests for it. So a repo declaring a language can still owe nothing beyond the baseline. It reports three things. They are a required name missing from a store and a forbidden name present in either store. The third is a configured name outside its store's required set, which the baseline and the applicable mechanisms make up. The entry's `requiredSecrets` adds to both stores, as the baseline does, since a workflow run a Dependabot pull request triggers reads the Dependabot store alone. A claim is per store, so a name only one store owes is reported when the other store holds it. A forbidden name present draws the third as well as the second, since each store's claimed set is built from its required names alone. Names are read, never values. A shallow hub clone fails the whole run, so no `secrets:` line prints, per section 8. diff --git a/CODESTYLE.md b/CODESTYLE.md index 50299baef..ad9595738 100644 --- a/CODESTYLE.md +++ b/CODESTYLE.md @@ -35,6 +35,16 @@ Each language defines a **clean-compile** verification: the combination of build - **Classify a subprocess failure by which command failed and the status code it reports, never by the prose of its message.** That prose varies by tool version and locale, and a status code's value does not, even one printed inside the message. A printed code is read by the notation that marks it, and a match finding none counts as an unexpected failure. Where one command's status code cannot separate the failures its caller handles differently, give each expected failure its own real operation. Where no such operation exists, treat the failure as unexpected. A test asserting a script's output, such as the refusal "Command-Line Arguments" requires, verifies that output rather than classifying a failure. - **A failure message states the error, the path or other target, and the remedy, and claims nothing about the state the failure left.** The error the operation raised is the one fact the code holds at that point. A description of what the failure left behind is a prediction. It reads false once an unforeseen state reaches the message, such as a file written in full that then fails to close. A remedy such as "fix what it names, then re-run" needs no such claim. +### Interrupts + +This applies to every Bash and Python script. `CODESTYLE.md` "Interrupts in Python" and "Interrupts in Shell" state each language's mechanics. + +- **On SIGINT or SIGTERM, a script releases what it holds before it exits.** It removes the temporary paths it created, releases the locks it took, and stops the child processes it started. A path, lock, or child left behind can stop the next run from starting, or feed it a half-written input. +- **A write to persistent state goes to a temporary path beside the target, then is renamed over it.** An interrupt then leaves the old content or the new, never a mix of both. A store with transactions of its own, such as an SQLite database, is written through those instead. A rename over an open database can corrupt it. +- **An interrupted script prints one line naming the signal, with no traceback, and exits 130 for SIGINT or 143 for SIGTERM.** Each status is 128 plus the signal number, the status a shell reports for a process that signal ended. +- **A script takes this rule when it is created or next edited.** An existing script is not edited for this rule alone. +- **A script that holds a lock, temporary state, or a child process owes a test that signals it mid-run.** The test sends SIGINT or SIGTERM, then asserts the matching exit status and that nothing the script held remains. It is skipped on Windows, which cannot deliver either signal for a script to handle. A script holding none of these owes no such test. + ### Parsing Structured Formats - **A program reading a structured format uses a maintained parser rather than a hand-written one, where a field-tested parser exists for the runtime in use.** That covers YAML, Markdown, TOML, JSON, a programming language's comments or strings, and a shell command line. The standard library's own parsers count, such as Python's `json`, `tomllib`, `ast`, `tokenize`, and `html.parser`. A hand-written reader converges on the format's full grammar one review finding at a time, and every script that grows one pays that cost again. @@ -98,10 +108,23 @@ This is packaged as the `python-codestyle` Skill at `.agents/skills/python-codes - **A test lives in a `tests/` directory, never inside the production file it tests.** A deployed script may keep a `--selftest` that runs a small smoke check in seconds, and the case matrix lives in `tests/`. A self-test shipped inside the file it tests grows the file every reviewer reads, and its cases can come to outweigh the code they test. - **A hub-hosted standalone script that needs a third-party library declares it in PEP 723 inline script metadata, and runs as `uv run --no-project --script `.** The block opens on `# /// script`, closes on `# ///`, and carries `dependencies` and `requires-python`. The fleet already installs uv on hosts and in CI. `--no-project` keeps uv from syncing the project around a script that has no block yet, where it would write a lockfile and a virtual environment. A script with no such block runs under `python3` and uv alike. A hook an agent harness runs on every tool call stays standard-library only, since it runs before any toolchain is guaranteed. +### Interrupts in Python + +- **SIGINT and SIGTERM take one path.** Python raises `KeyboardInterrupt` on SIGINT. The entry point installs a SIGTERM handler with `signal.signal` that records the signal and raises `KeyboardInterrupt`. +- **The entry point catches `KeyboardInterrupt` once, and any handler below it that catches the exception re-raises it.** It prints the line `CODESTYLE.md` "Interrupts" requires, then exits 143 where the SIGTERM handler recorded a signal and 130 otherwise. +- **What the script holds is released by `with` blocks and `finally` clauses as the exception unwinds.** A `subprocess.Popen` child is stopped in a `finally` clause with `terminate()`, then `wait()`, since leaving its `with` block does not stop it. That child runs without `shell=True`, so `terminate()` reaches the command rather than a shell around it. +- **The rename over persistent state uses `os.replace`.** `os.rename` and `Path.rename` fail on Windows when the target exists. + ## Shell Bash, and only where a program cannot be Python: a bootstrap that installs the interpreter cannot be written in it. Nor can a host tool that must run before a development toolchain exists depend on Python. Everything else is Python, with a test under its own scripts tree's `tests/` directory. The `shell-codestyle` Skill packages the mandatory `set -Eeuo pipefail` header, the pipefail-versus-early-reader pitfall, and self-recursive command shims. It also packages self-locating scripts, the `shellcheck`-plus-`shfmt` clean-compile, and the why-not-what comment rule. It is at `.agents/skills/shell-codestyle/SKILL.md` in the hub, not a repo-relative link since that path is hub-local and not carried into every fleet repo. Read the skill for the full rules. A script's own arguments follow "Command-Line Arguments" under General, which the Skill carries whole. Run the clean-compile check itself per `GOVERNANCE.md` "Running the Linters Locally (Known-Working Invocations)", not by probing `command -v shellcheck`. That section is hub-only, read in a hub checkout rather than carried into every fleet repo. +### Interrupts in Shell + +- **Cleanup of temporary paths and locks runs in the script's `EXIT` trap.** Bash runs that trap when SIGINT or SIGTERM ends the script, as well as on a normal exit. +- **Every script sets an `INT` trap and a `TERM` trap, which stop its children and keep the status.** Each one sends SIGTERM with `kill` to the children the script started, then waits for them with `wait`. It then prints the line `CODESTYLE.md` "Interrupts" requires and exits 130 or 143. The children's process IDs are held in an array, such as `pids`, set to `()` before the traps are set. A trap skips the `kill` and the `wait` while `${#pids[@]}` is 0, a test `set -u` allows on an empty array in every Bash version. Under `set -u`, an unset one would end the trap before the line prints. The `kill` takes `2>/dev/null`, since a child that already exited makes it print an error. Both take `|| :`, since under `set -e` a non-zero status from either ends the trap before the line prints. SIGTERM is the signal sent because a background child ignores SIGINT. Other cleanup stays in the `EXIT` trap. +- **A long-running external command runs in the background, and the script waits for it with `wait "$pid"`, so its exit status reaches `set -e`.** Bash runs a trap only after a foreground command returns, while a trapped signal ends a `wait` at once. Only the script's own shell starts such a child. One that a subshell or a pipeline element starts never reaches the script's array or its `wait`. A background child that reads standard input takes `<&0`, since bash otherwise gives it `/dev/null`. The trap's `kill` reaches only the process `$!` names. So a function, a group, a subshell, a pipeline, or `sh -c` runs in the foreground instead. There the trap runs once the command it interrupted returns, so nothing the script started is orphaned. + [governance]: ./GOVERNANCE.md diff --git a/GOVERNANCE.md b/GOVERNANCE.md index 7990c033a..2aa6b9f5c 100644 --- a/GOVERNANCE.md +++ b/GOVERNANCE.md @@ -116,6 +116,7 @@ A repo whose own stacks or scripts read local runtime credentials from disk keep - **The directory is named `.secrets/`, dotted, never a bare `secrets/`.** - **A secret file's name is lowercase fields joined by `_`** (`homeassistant_db_password`, `mail_relay.env`), per [`CODESTYLE.md` "Script and Utility File Names"](./CODESTYLE.md#script-and-utility-file-names). +- **A host secret file a repository installs in `~/.secrets/` is named `_[_]`**, `` being its registry `shortName`, and the `github_` provisioning namespace is unchanged. - **A single opaque credential file carries no extension** (`homeassistant_db_password`, not `homeassistant_db_password.txt`), the same reason `README` and `LICENSE` carry none. It is a security property, read but never sourced, not a formatting preference. - **A structured credential keeps its format's extension** (`.json` for structured config). - **The shared env file is named for what it configures**, not a bare `.env` (`docker.env` for a repo whose stacks are Docker Compose). A second env-shaped file added later then stays unambiguous. @@ -148,7 +149,7 @@ The fleet's tooling lives in the hub once and a repository runs it from there ra **Code a repository's own runtime executes is the exception, and it is carried.** Such a library runs on a host the project owns, often unattended and sometimes as root. Fetched from the hub at run time, it would let a GitHub outage or a bad `main` commit stop a scheduled host job. It would also run code the repository never reviewed against its own secrets. So offline operation and review in the repository that runs it outweigh the staleness of a copy. A gate differs, since "the tool did not run" is an acceptable answer there and CI is the backstop. The hub hosts the library once. A repository whose declared types select it carries it byte-for-byte, as a tree the hub's `spec/files.json` declares. The hub owns the carried directory whole. The repository extends the library in a file of its own outside it that sources it, never by editing the copy. The staleness is made visible rather than accepted. The repository gate compares each carried tree with the hub tree its pinned action holds. It reports a difference as a warning that never fails the gate. A failure would break every downstream pull request on each hub fix. The audit reports a stale copy, and the resync refreshes it. -**Reaching it is a checkout of the hub rather than a copy of one file.** A tool reads the payloads, tables, and sibling modules beside it. So a single file lifted out of the tree runs against whatever the caller happens to have. That is the copy problem again in a shorter loop. Read `main`, the promoted and gated state, and fetch immediately before running. That is because a clone is whatever it last fetched rather than the branch it names, and a stale clone answers confidently instead of failing. Name the tool by its path in that checkout and name the target explicitly. That is because a tool that defaults to the current directory or the current repository resolves somewhere either way. It is also because a result computed against the wrong repository is well-formed. Which directory the command runs in is the tool's own contract rather than a rule here. So a gate reading a working tree runs in the repository under test. Likewise, a tool taking its target as an argument runs anywhere and is given one. What the rule forbids is letting a default decide which repository the answer is about. +**Reaching it is a checkout of the hub rather than a copy of one file.** A tool reads the payloads, tables, and sibling modules beside it. So a single file lifted out of the tree runs against whatever the caller happens to have. That is the copy problem again in a shorter loop. Read `main`, the promoted and gated state, and fetch immediately before running. That is because a clone is whatever it last fetched rather than the branch it names, and a stale clone answers confidently instead of failing. For a repository whose registry entry has merged to `develop` but not yet reached `main`, run `repo-config/configure.sh` and `spec/audit.py` from `develop`. Name the tool by its path in that checkout and name the target explicitly. That is because a tool that defaults to the current directory or the current repository resolves somewhere either way. It is also because a result computed against the wrong repository is well-formed. Which directory the command runs in is the tool's own contract rather than a rule here. So a gate reading a working tree runs in the repository under test. Likewise, a tool taking its target as an argument runs anywhere and is given one. What the rule forbids is letting a default decide which repository the answer is about. **A loader is outside this section rather than exempt from it.** The rule above governs a tool that reads hub content, because a tool reads the payloads, tables, and sibling modules beside it. A loader reads none of them. It obtains a tree and hands control to a tool inside that tree, on a host that cannot yet obtain one. The bound is what it may contain rather than who runs it, and it is one line. A loader references no path inside the tree it fetches except the single entry point it hands control to. Everything else it touches is the machine or the network. A loader that grows a second path into that tree has become a tool and is governed above. @@ -297,7 +298,7 @@ CI runs the full lint set, but run the linters locally before pushing to catch i **Each surface runs the lint with the tool that fits it, all from the same config files** (`.markdownlint-cli2.jsonc`, `cspell.json`, `.editorconfig`): - **CI (authoritative)** runs **markdownlint-cli2**, **cspell**, and **actionlint** as pinned action wrappers, which Dependabot bumps. It runs **editorconfig-checker** via Docker `:latest`, since its action only installs the CLI and the Docker one-liner is what actually runs the check. **shellcheck** and **shfmt** run the same way for a repo that carries a shell script, and **PSScriptAnalyzer** does for a repo that carries `.ps1` files. None of shellcheck, shfmt, and PSScriptAnalyzer has an action. For a repo that carries an action under `.github/actions/`, the repo gate's `composite-actions` check runs **shellcheck** in Docker over each bash or sh `run:` body. It also runs **check-jsonschema** through `uvx`, because actionlint reads workflows only. The `composite-actions` check runs shellcheck at warning severity without SC2154, weaker than for a `.sh` file. markdownlint covers all `**/*.md`, and **cspell is scoped to `README.md` + `HISTORY.md`** (see [CODESTYLE.md](./CODESTYLE.md) "Markdown and Spelling" for why), matching the wrapper's CSpell scope below. A "shell script" here is a tracked `.sh` file, plus a tracked, extension-less file whose shebang names bash or sh. That second shape is the one a script meant to run as a bare command takes. A bare `*.sh` glob misses that second case, so both discovery paths run before either tool does. This whole block is the hub's `validate-task.yml` reusable workflow, so a fleet repo reaches it rather than carrying a copy of these steps. -- **A working local hook is strongly suggested fleet-wide, and its absence is a measured audit finding, not an invisible gap.** `spec/project-types.json`'s `parity.hooks` check reads this section for its rationale. It is judged by hand during an `AUDIT.md` run like every sibling check in its dimension, never mechanized by `spec/audit.py`. A repo with no local hook mechanism wired at all is a `linter-parity` defect, the same severity a missing markdownlint config already gets. A repo mid-convergence (below) stays operational. CI remains the authoritative run regardless. Catalog snippets carry the canonical shape, each with a copy of `catalog/snippets/hub_fetch_run.py` alongside it. `catalog/snippets/husky/` is Husky.Net, for a repo that already keeps a .NET tool manifest declaring it. That is because `dotnet tool restore` then `dotnet husky install` is what generates the `.husky/_/husky.sh` its hook sources. It is also because the snippet ships no manifest of its own. `catalog/snippets/pre-commit/` is the `pre-commit` framework, for a repo without one and for any repo that prefers it. No snippet is scoped to a language by what it runs. Each carries the repo's own language checks plus the shared doc gates. A repo drops the block for a language it does not have. A Docker, config, or docs repo therefore wires the doc gates alone, which is a mechanism rather than the absence of one. Which snippet a repo starts from is bounded by the toolchain it already keeps, never by which languages its checks cover. A snippet is a starting point rather than the only shape. A repo may wire an equivalent hook of its own at `.husky/pre-commit`, enabled with `core.hooksPath` and sourcing nothing. That is what this repository does. That path matters, since `parity.hooks` reads the tracked file at `.husky/pre-commit` or `.pre-commit-config.yaml` rather than a per-clone hooks path it cannot observe. +- **A working local hook is strongly suggested fleet-wide, and its absence is a measured audit finding, not an invisible gap.** `spec/project-types.json`'s `parity.hooks` check reads this section for its rationale. It is judged by hand during an `AUDIT.md` run like every sibling check in its dimension, never mechanized by `spec/audit.py`. A repo with no local hook mechanism wired at all is a `linter-parity` defect, the same severity a missing markdownlint config already gets. A repo mid-convergence (below) stays operational. CI remains the authoritative run regardless. Catalog snippets carry the canonical shape, each with a copy of `catalog/snippets/hub_fetch_run.py` in the repo root, the one location both shapes share. `catalog/snippets/husky/` is Husky.Net, for a repo that already keeps a .NET tool manifest declaring it. That is because `dotnet tool restore` then `dotnet husky install` is what generates the `.husky/_/husky.sh` its hook sources. It is also because the snippet ships no manifest of its own. `catalog/snippets/pre-commit/` is the `pre-commit` framework, for a repo without one and for any repo that prefers it. No snippet is scoped to a language by what it runs. Each carries the repo's own language checks plus the shared doc gates. A repo drops the block for a language it does not have. A Docker, config, or docs repo therefore wires the doc gates alone, which is a mechanism rather than the absence of one. Which snippet a repo starts from is bounded by the toolchain it already keeps, never by which languages its checks cover. A snippet is a starting point rather than the only shape. A repo may wire an equivalent hook of its own at `.husky/pre-commit`, enabled with `core.hooksPath` and sourcing nothing. That is what this repository does. That path matters, since `parity.hooks` reads the tracked file at `.husky/pre-commit` or `.pre-commit-config.yaml` rather than a per-clone hooks path it cannot observe. - **The hook** runs **language formatting** and the **doc gates**, never Docker, so it stays fast. The formatting half is whatever the repo's own language needs, via native tooling. That is CSharpier and `dotnet format` for .NET, or ruff and the repo's type checker for Python. A repo adds each half once its tree passes that half. That is because a gate that fails on the corpus it guards blocks every commit from the moment it lands. So a hook running one half is a repo mid-convergence rather than a repo out of conformance. The doc half runs each gate at the scope that fits it. The prose gate is scoped to the working tree diff against `HEAD` rather than swept over the tree. That is the difference between about 2.2 seconds and about 0.13, and is what makes it affordable in a hook at all. Under a plain git hook that scope is the working tree rather than the staged index. So a partially staged file is judged on all of its edits. Under the `pre-commit` framework it is the staged state instead. That is because that runner sets unstaged changes aside before running a hook, which is measured rather than assumed. That set-aside leaves untracked files in place, so the hook there passes the gate the paths `pre-commit` names instead of the tree. The pull request gate re-checks every line the branch changes against its base, which is the scope a review is judged on. A whole-repo check belongs in the hook too when it is already fast and takes no file list. The line-ending consistency check is one such check. So scope is a property of the gate rather than a rule the hook applies to all of them. `repo_gate.py --check sha-pin` stays out of the hook regardless, since it resolves a same-owner pin against the GitHub API. - **The doc gates reach a downstream repo by fetching `.github/actions/prose-gate/prose_lint.py` with the `prose-gate.json` beside it and `.github/actions/repo-gate/repo_gate.py`. Each file comes fresh from `ptr727/ProjectTemplate`'s `main` branch, via `hub_fetch_run.py`, never vendored and never pinned.** Pinning anything Dependabot does not maintain goes stale by construction. CI (this repo's own, and the hub's) is the backstop. It catches a change landing broken on `main` before a locally fetched copy does real damage. The prose gate adds one `api.github.com` commit lookup to its fetch, with a `git ls-remote` against `github.com` where that fails. `uv` resolves the packages its script block declares on a cache miss. Beyond fetching the scripts, those lookups and that resolution are the only network calls the doc gates make. An allow-list permitting only `raw.githubusercontent.com` still runs the gate, with the commit reported as unresolved. The unresolved-commit fallback reads the prose gate and its data from `main` twice. When the two reads differ, it refuses to run a mixed pair, and a re-run is the remedy. A Python repo's `uvx`-run ruff and type checker can also reach the network, to resolve `@latest` on a cache miss or refresh. That is the same category of dependency as the Docker pulls the VS Code Lint tasks already do routinely, not a new one. A fetch failure fails the commit, and it never silently skips the gate. The **hub's own** `.husky/pre-commit` is the one exception, staying local and offline, since it carries both gates directly and has no hub to reach. A repo enables its hook per clone with `git config core.hooksPath .husky` or (`uv tool install pre-commit` once, then) `pre-commit install`. The Husky.Net snippet needs one more step per clone, `dotnet tool restore` then `dotnet husky install`, which generates `.husky/_/husky.sh`, the file the hook sources. CI remains the authoritative run either way. - **The hub carries a second hook, `.husky/pre-push`, gating the local-review rule rather than lint.** It runs `scripts/local_review.py check`, refusing a branch push whose diff no recorded review pass covers, per "Verification Discipline" above. It fires only for a branch update, so a tag push and a branch delete pass through. A branch holding no net content against its target has nothing for a review to cover. It refuses rather than guesses in every state it cannot speak for. That is because the engine reads the checkout it runs in while a push delivers a commit, and those describe the same content only sometimes. The order that keeps them describing the same content is to commit the change, then review the diff, record its receipt, and push. The receipt is untracked and so is recorded after the last commit. A change that also carries the canonical ledger records those passes ahead of that commit instead. The ledger is tracked content the commit has to hold. It reads `develop` and accepts no override from the environment. That is because an environment variable is set inline on the very command being gated, by whoever is being gated. It is the same reason an authorization is never read from a channel the agent itself can set. The cost is that it measures a branch based on anything but `develop` against `develop` anyway. So its refusal there is not a verdict about that branch. Each refusal names its own case. The `local-strict-review` Skill carries the fleet's one enumeration of them with what clears each, deliberately in one place rather than restated here. It folds the engine's three-valued exit honestly. A check that could not run blocks too, and says so in different words than a check that ran and found no pass. That is because a gate that waves a push through when it could not run is a gate that stopped gating. It is a backstop rather than a seal, and it is bypassable by construction. `--no-verify` is the documented route out of a pickle and is not the only one, since a git hook cannot police its own invocation. A Claude Code session meets a narrower surface, that flag being denied unconditionally by the agent-safety hook's explicit-bypass rule. That denial is Claude Code's alone, since Codex and opencode carry no such hook yet. So the committed hook raises the cost of skipping the rule for one agent and lowers it for none. The prose layer above therefore stays the agent-agnostic one that actually binds. It is hub-only for now. `local_review.py` is hub-hosted per "Hub-Hosted Tooling". A downstream repo reaches it as a hub checkout's copy run with its own worktree as the working directory. So a catalog snippet carrying this hook fleet-wide is a later step rather than part of this one. `canonical_review.py` is not run here at all. Nothing else gates a push or a pull request over a canonical unit either, that read being swept on a schedule instead, per "Verification Discipline" above. The hub's own `.github/actions/validate` composite action renders its coverage burn-down into every run's job summary. It fails no pull request over what that shows. It still fails where the engine could not read the manifest or the ledger at all, that being a boundary rather than a verdict. @@ -329,7 +330,7 @@ In a configured editor the `DavidAnson.vscode-markdownlint` extension is enough When pulling a public image fails on a Docker-Desktop/WSL credential-helper error (`docker-credential-desktop.exe: exec format error`), retry with an empty Docker config: `DOCKER_CONFIG=$(mktemp -d) docker run ...` after writing `{}` to `$DOCKER_CONFIG/config.json`. -**Reproducing a prose-gate finding a downstream repository reports.** The gate a repository runs is the hub copy its own workflow pins, never the copy a hub checkout holds. So a rule that changed after that pin is a rule no local run has. Every verdict names its own copy on the scope line, which is where to look first. `gate /@` is a pinned remote action. `gate local ` is a checkout that tracks the script at that commit, and `gate local -dirty` is the same with the file edited. And `gate unknown` is a copy no commit describes. The `hub_fetch_run.py` route is its own shape, `gate ptr727/ProjectTemplate@ (hub-fetch-run main)`, or `@main (hub-fetch-run, commit unresolved)` when the commit could not be read, so it never reads as a CI pin. A verdict carrying no `gate` clause at all predates this rule, which dates the copy just as usefully. A `local` value is meaningful only inside the repository that produced it, since it names a commit and not the repository holding it. A hand-set value is whatever its caller typed, so say in it that the run is a reproduction. Otherwise the verdict is indistinguishable from the CI one it is being compared against. Take the reporting repository's pin from the `@` in its workflow's `uses:` line. The pin is the commit alone rather than the whole reference that line spells. Then run that copy against the same worktree and the same diff base CI used. Name the pin yourself, because an extracted copy sits under no checkout and would otherwise report `unknown`: +**Reproducing a prose-gate finding a downstream repository reports.** The gate a repository runs is the hub copy its own workflow pins, never the copy a hub checkout holds. So a rule that changed after that pin is a rule no local run has. Every verdict names its own copy on the scope line, which is where to look first. `gate /@` is a pinned remote action. `gate local ` is a checkout that tracks the script at that commit, and `gate local -dirty` is the same with the file edited. And `gate unknown` is a copy no commit describes. The `hub_fetch_run.py` route is its own shape, `gate ptr727/ProjectTemplate@ (hub_fetch_run.py main)`, or `@main (hub_fetch_run.py, commit unresolved)` when the commit could not be read, so it never reads as a CI pin. A verdict carrying no `gate` clause at all predates this rule, which dates the copy just as usefully. A `local` value is meaningful only inside the repository that produced it, since it names a commit and not the repository holding it. A hand-set value is whatever its caller typed, so say in it that the run is a reproduction. Otherwise the verdict is indistinguishable from the CI one it is being compared against. Take the reporting repository's pin from the `@` in its workflow's `uses:` line. The pin is the commit alone rather than the whole reference that line spells. Then run that copy against the same worktree and the same diff base CI used. Name the pin yourself, because an extracted copy sits under no checkout and would otherwise report `unknown`: ```sh scratch="$(mktemp -d)" diff --git a/OPERATIONS.md b/OPERATIONS.md index b9ba7b919..7a6a1854c 100644 --- a/OPERATIONS.md +++ b/OPERATIONS.md @@ -77,14 +77,14 @@ Findings are a point-in-time snapshot read live over the API. Re-run before acti ### Apply or verify repository configuration -Run these commands from a hub checkout at `main`. The payloads, registry, and script are hub-hosted. +Run these commands from a hub checkout at `main`. A repo whose registry entry has merged to `develop` but not yet reached `main` runs them from a hub checkout at `develop` instead. The payloads, registry, and script are hub-hosted. ```sh repo-config/configure.sh check owner/repo release|operational repo-config/configure.sh apply owner/repo release|operational ``` -**Always pass the command, the repository, and the model.** The command is required. A missing or unknown command, an unknown option, a repository not shaped `owner/name`, and an unknown model are each refused before any read. `--help` prints the usage. An omitted target resolves to the hub repository. Applying fleet configuration there while meaning to configure a downstream repo is a well-formed write to the wrong place. The hub checkout has the registry beside the script, so a repo the registry does not name resolves through `defaults.workflowModel` to `release`. An operational repo outside the registry therefore requires the explicit model argument. +**Always pass the command, the repository, and the model.** The command is required. A missing or unknown command, an unknown option, a repository not shaped `owner/name`, and an unknown model are each refused before any read. `--help` prints the usage. An omitted target resolves to the hub repository. Applying fleet configuration there while meaning to configure a downstream repo is a well-formed write to the wrong place. The hub checkout has the registry beside the script, so under `check` a repo the registry does not name resolves through `defaults.workflowModel` to `release`. An operational repo outside the registry therefore requires the explicit model argument. `apply` refuses a repo the registry does not name, writing nothing. `check` is read-only and exits non-zero on drift. `apply` is idempotent and drives from the committed payloads, its rulesets composed for the repo, so it changes no setting on a conformant repo. The secrets group is the exception, since a stored value can never be read back to compare. Each run rewrites every secret the repo owes from `~/.secrets/`, so a value rotated in the GitHub UI and not in that file is overwritten. `check` also asserts one group `apply` never writes, the existence and deployment-branch policy of every environment the registry's `environments` declares for the repo. So the two are not exact inverses. [docs/repo-config.md](./docs/repo-config.md) "Deployment Environments" says why. diff --git a/RESYNC.md b/RESYNC.md index cf3e300b1..fd99de4ee 100644 --- a/RESYNC.md +++ b/RESYNC.md @@ -81,7 +81,7 @@ The order is load-bearing. Each step below either changes the rules the later st **A skill path lands with the instruction file that names it.** Where this re-vendor adds, removes, or renames a `.github/skills` directory that `.github/copilot-instructions.md` names, edit that path in the instruction file in the same change. Do this ahead of step 6. Copilot reads both from the pull request head, so a path naming a pruned directory leaves it reviewing without its skill. 4. **Interface workflows.** Honor the named contract (required jobs, the ruleset-bound check name, the artifact-name handoff) rather than copying bytes. The body is the repository's own. 5. **Settings, rulesets, and secrets.** From a hub checkout at `main`, run `repo-config/configure.sh check / release|operational`, then `apply` for what it reports. Pass the model explicitly. `apply` ends by writing every secret the repository owes from the running host's `~/.secrets/`, overwriting each stored value. A file the repository owes that is missing or refused makes it exit non-zero after every other group is applied. An empty placeholder from `scaffold` is one such refusal. That exit reports the secrets listed as missing or refused, rather than a failed resync. Delete each target-repository path under `repo-config/` that the audit classified `retire`. Inspect every untriaged path collision before deciding its disposition. -6. **Intent files last, and by hand.** See section 5, which states why these carry no mechanical signal at all. A repository's `.vscode/tasks.json` is a presence unit, so the audit only asserts that it exists. Bring its task groups, the Lint group included, in line with the catalog snippet for each of its types by hand. Copy the hook helper's content from `catalog/snippets/hub_fetch_run.py` in the same commit, since the Lint tasks fetch their hub scripts through the companion list it holds. A hook helper still named `hub-fetch-run.py` is renamed to `hub_fetch_run.py` in place. Every call to it in the hook config and `.vscode/tasks.json` changes in the same commit. Nothing mechanical carries the helper, so copying the new snippet beside it would leave both. +6. **Intent files last, and by hand.** See section 5, which states why these carry no mechanical signal at all. A repository's `.vscode/tasks.json` is a presence unit, so the audit only asserts that it exists. Bring its task groups, the Lint group included, in line with the catalog snippet for each of its types by hand. Copy the hook helper's content from `catalog/snippets/hub_fetch_run.py` in the same commit, since the Lint tasks fetch their hub script through it. A hook helper still named `hub-fetch-run.py` is renamed to `hub_fetch_run.py`, and one under `.husky/` moves to the repo root. Every repo keeps it there, whichever hook it wires. Every call to it in the hook config and `.vscode/tasks.json` changes in the same commit. Nothing mechanical carries the helper, so copying the new snippet beside it would leave both. **Reconcile the registry entry in the same pass.** `status`, `types`, `releaseTrigger`, `workflowModel` and `driftNotes` record reality rather than intent. A `driftNote` describing work that is now finished is deleted rather than left standing. A note asserting outstanding work in prose ("pending", "not yet", "behind") contradicts a clean audit outright. diff --git a/STANDUP.md b/STANDUP.md index cb7dd5504..aef74daef 100644 --- a/STANDUP.md +++ b/STANDUP.md @@ -153,7 +153,7 @@ uv run --no-project --script scripts/carry.py apply "" --target /path/to/w Read every extra-path report before `apply` prunes it. Finish with another `check`. It uses the same comparison as `apply` and must report clean. -Copy every [`spec/files.json`][files] entry whose `appliesTo` matches the repo's **selector set**, **adapted, not cloned**. The selector set is the repo's `types` plus its `workflowModel`, `releaseTrigger`, and `consumerModel`. So filtering on type alone silently drops the entries a non-type selector carries ([`spec/scope-model.md`][scope-model] defines the four namespaces and how they resolve). The prose files (`CODESTYLE.md`, `README.md`, and the like) describe the repo's own toolchain. So adapt them to reality rather than propagating template specifics verbatim (see the "Adapt before propagating" callout in [`CODESTYLE.md`][codestyle]). That is because a verbatim copy that misdescribes the repo is rejected in review. The baseline covers `WORKFLOW.md`, `version.json`, `.github/dependabot.yml`, `.editorconfig`, `.gitattributes`, `host-tools.json`, the linter configs, and the per-type files (`.vscode/tasks.json` from the language's snippet, `codecov.yml`, `.dockerignore`, `Docker/README.md`). Repository settings and ruleset payloads stay in the hub's `repo-config/` directory. +Copy every [`spec/files.json`][files] entry whose `appliesTo` matches the repo's **selector set**, **adapted, not cloned**. The selector set is the repo's `types` plus its `workflowModel`, `releaseTrigger`, and `consumerModel`. So filtering on type alone silently drops the entries a non-type selector carries ([`spec/scope-model.md`][scope-model] defines the four namespaces and how they resolve). The prose files (`CODESTYLE.md`, `README.md`, and the like) describe the repo's own toolchain. So adapt them to reality rather than propagating template specifics verbatim (see the "Adapt before propagating" callout in [`CODESTYLE.md`][codestyle]). That is because a verbatim copy that misdescribes the repo is rejected in review. The baseline covers `WORKFLOW.md`, `version.json`, `.github/dependabot.yml`, `.editorconfig`, `.gitattributes`, `host-tools.json`, the linter configs, and the per-type files (`.vscode/tasks.json` from the language's snippet, `.codecov.yml`, `.dockerignore`, `Docker/README.md`). Repository settings and ruleset payloads stay in the hub's `repo-config/` directory. Carry `AGENTS.md`'s skill-dependency pointer paragraph as one more verbatim unit in this same step, not a separate pass. It is the one naming `scripts/skills_install.py` and where the fleet's Skills live. It reads like boilerplate next to the surrounding text a new repo adapts to describe itself. A repo that carries `AGENTS.md` without it stands up with no path to the fleet's Skills at all. `RESYNC.md` carries the identical instruction for a repo already stood up, so the two procedures agree on what belongs in every copy. @@ -185,7 +185,7 @@ Carry `AGENTS.md`'s skill-dependency pointer paragraph as one more verbatim unit Choose the destination while scaffolding rather than after. Repo-specific content left in a carried file is drift, which the audit lists as an undeclared section to reconcile. Reconciling it later means moving prose that downstream readers have already started trusting in the wrong place. -**Wire a local commit hook here, not after the fact.** `.husky/pre-commit` and `.pre-commit-config.yaml` are deliberately excluded from the baseline above (each repo's own formatters make the content repo-owned, per [`spec/divergences.json`][divergences]). So nothing in the carry step above wires one. Copy and adapt the applicable catalog snippet with `catalog/snippets/hub_fetch_run.py` alongside it, then enable it, before the section 5 audit run. Which shape applies, what the gate must cover, and the per-clone enablement steps are all in [`GOVERNANCE.md`][governance] "Running the Linters Locally (Known-Working Invocations)", not restated here. A freshly stood-up repo with nothing wired starts pre-failed on `parity.hooks`. +**Wire a local commit hook here, not after the fact.** `.husky/pre-commit` and `.pre-commit-config.yaml` are deliberately excluded from the baseline above (each repo's own formatters make the content repo-owned, per [`spec/divergences.json`][divergences]). So nothing in the carry step above wires one. Copy and adapt the applicable catalog snippet with `catalog/snippets/hub_fetch_run.py` copied into the repo root, then enable it, before the section 5 audit run. Which shape applies, what the gate must cover, and the per-clone enablement steps are all in [`GOVERNANCE.md`][governance] "Running the Linters Locally (Known-Working Invocations)", not restated here. A freshly stood-up repo with nothing wired starts pre-failed on `parity.hooks`. ## 3. Stand Up the Workflows @@ -212,7 +212,7 @@ Three conditions fail here, and the two commands together are what separate them Each is step 0A's escalation rather than something to work around. -Run `repo-config/configure.sh apply owner/repo release|operational` from a hub checkout at `main`, naming the repo being stood up and its model. It applies the fleet settings, Dependabot security features, label set, two rulesets, and the link to the fleet project idempotently. Import the JSON, never hand-build it, per [`docs/repo-config.md`][repo-config-doc]. Then run `repo-config/configure.sh check owner/repo release|operational` from the same checkout. Pass the model explicitly because the repository is outside the registry during this step. Both commands need project access on the token, and a token without it fails at this step rather than at any check before it. Configure every required secret per [`spec/secrets.json`][secrets] (the registry `requiredSecrets[]` list plus the implicit baseline) in the right store(s). A baseline name and every `requiredSecrets[]` name go in both the Actions and the Dependabot store. A mechanism's names go in the stores its own `stores` list names. Also confirm no forbidden secret is present. The required check binds by name (`Check pull request workflow status job`) and turns green only after the PR workflow has run once. That is why this step follows step 3 rather than preceding it. A ruleset requiring a name no run has ever reported leaves the first pull request waiting on a status nothing produces. On an operational repo the `develop -> main` promotion is a pull request too, so the same wait applies there. +Run `repo-config/configure.sh apply owner/repo release|operational` from a hub checkout at `main`, naming the repo being stood up and its model. `apply` refuses, writing nothing, a repository with no entry in the registry it reads. A new entry reaches `main` only at the next hub promotion. Until then, run it from a hub checkout at `develop`, once the entry has merged there. Every other repository's run stays on `main`. It applies the fleet settings, Dependabot security features, label set, two rulesets, and the link to the fleet project idempotently. Import the JSON, never hand-build it, per [`docs/repo-config.md`][repo-config-doc]. Then run `repo-config/configure.sh check owner/repo release|operational` from the same checkout. Both commands need project access on the token, and a token without it fails at this step rather than at any check before it. Configure every required secret per [`spec/secrets.json`][secrets] (the registry `requiredSecrets[]` list plus the implicit baseline) in the right store(s). A baseline name and every `requiredSecrets[]` name go in both the Actions and the Dependabot store. A mechanism's names go in the stores its own `stores` list names. Also confirm no forbidden secret is present. The required check binds by name (`Check pull request workflow status job`) and turns green only after the PR workflow has run once. That is why this step follows step 3 rather than preceding it. A ruleset requiring a name no run has ever reported leaves the first pull request waiting on a status nothing produces. On an operational repo the `develop -> main` promotion is a pull request too, so the same wait applies there. For a **private** repo, confirm the owner-level toggle named `Dependabot on self-hosted runners`, which for a user-account owner sits at `https://github.com/settings/security_analysis`, is off, along with `Automatically enable for new repositories` beside it. If self-hosted routing is wanted instead, register a matching self-hosted runner rather than disabling the toggle. Left on with no self-hosted runner registered on the owner, Dependabot's own update jobs queue for up to 24 hours, then get cancelled. Ordinary CI is unaffected throughout. A routed job is visible through the Actions API, carrying `labels: ["dependabot"]` with an empty `runner_name` and no steps. By contrast, a job GitHub's own runners took carries `labels: ["ubuntu-latest"]` with a runner name. [`AUDIT.md`][audit] section 6 carries the query that reads a routed job. GitHub never routes a public repo through this setting, so a public standup is unaffected. A repo standing up from a **partial state** may already carry queued or cancelled jobs from before this check ran. Fixing the toggle does not rerun those. A manual `Check for Updates` click on the repo's own Dependabot page does. diff --git a/WORKFLOW.md b/WORKFLOW.md index eeb023d2b..ddbd1cd55 100644 --- a/WORKFLOW.md +++ b/WORKFLOW.md @@ -49,7 +49,7 @@ flowchart LR develop -->|merge commit, enforced lint CI| main ``` -The direct commit is an **allowance, not a substitute for review**. The ruleset drops the pull-request *requirement*, which permits a direct push without withdrawing the pull request. So a change worth reviewing still takes one, and both paths reach `develop` legally. Which changes those are is stated as a shape rather than a line count in `GOVERNANCE.md` "Operational Repositories". That section owns the test and is the one place it is written, since nothing in a ruleset can apply it. What differs is when validation lands. On the direct-commit path the commit is already on the branch, so CI can only be advisory after the fact. That is the accepted cost of the model. On the pull-request path the change has not landed, so validation is pre-merge and actionable, the moment it is worth the most. The lint workflow's `pull_request` trigger therefore names `develop` alongside `main` (`WORKFLOW.md` section 6). That is what makes **D1.2** hold here, since its input is *any* PR and the operational model is no exception. The check is reported on a `develop` PR rather than required. That is because a required status check on `develop` binds the direct push too, and would dissolve the allowance the model is built on. +The direct commit is an **allowance, not a substitute for review**. The ruleset drops the pull-request *requirement*, which permits a direct push without withdrawing the pull request. So a change worth reviewing still takes one, and both paths reach `develop` legally. Which changes those are is stated as a shape rather than a line count in `GOVERNANCE.md` "Operational Repositories". That section owns the test and is the one place it is written, since nothing in a ruleset can apply it. What differs is when validation lands. On the direct-commit path the commit is already on the branch, so CI can only be advisory after the fact. That is the accepted cost of the model. On the pull-request path the change has not landed, so validation is pre-merge and actionable, the moment it is worth the most. The lint workflow's `pull_request` trigger therefore filters no base branch (`WORKFLOW.md` section 6). That is what makes **D1.2** hold here, since its input is *any* PR and the operational model is no exception. The check is reported on a `develop` PR rather than required. That is because a required status check on `develop` binds the direct push too, and would dissolve the allowance the model is built on. Their CI is lint/validation only: editorconfig/EOL plus domain linters such as Home Assistant or ESPHome config validation or a firmware build, but **no unit tests**. So the D-guarantees in `WORKFLOW.md` section 4 that assume a build/test pipeline are **N/A** exactly as for `source-only` (`WORKFLOW.md` section 6). What binds is the promotion gate and the source-only release on manual dispatch (`releaseTrigger: dispatch-only`, tag + source zip). At the promotion gate, the `develop -> main` PR must pass the required `Check pull request workflow status job`. Branch-model rulesets are specified in `GOVERNANCE.md` "Branching Model" rather than in `WORKFLOW.md`. @@ -142,8 +142,8 @@ The required behaviors, organized by domain. Each is a **MUST**, and its `Output - **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.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. 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`** setting 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 also reads a **`.codecov.yml`** at the repository root, so that name serves too. 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.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.* ### D2 - Input/State Validation at Entry @@ -198,7 +198,7 @@ The required behaviors, organized by domain. Each is a **MUST**, and its `Output - **D8.1 Merge-bot.** Output: the merge-bot enables auto-merge on `opened`/`reopened` for **every** Dependabot tier including semver-major. The required checks are the gate, not the bump magnitude. The merge-bot dispatches `--squash`/`--merge` by the PR's base ref, and disables on a maintainer-pushed `synchronize`. Its concurrency is keyed on the **PR number**, not `github.ref`. On `closed` it deletes a merged in-repo bot head when the caller opts in. The push leases the branch tip to the merged head, so a moved branch survives. *Prevents: two PRs colliding in auto-merge.* - **D8.2 CodeGen and Dependabot.** Output: codegen runs as a matrix over both branches and is deterministic from an external source. `.github/dependabot.yml` targets both branches, and security PRs go to the default branch. -- **D8.3 Upstream-version tracker.** Output: a scheduled resolver prints a JSON `name -> version` object to a committed state file. It opens a rolling per-branch bump PR naming only the moved keys, and the merge-bot auto-merges it. The `main` pin push publishes via the release gate, while a `develop` pin does not auto-publish. It ships via a `develop` dispatch (prerelease) or the next promotion to `main`. The tracker's `bump-branch-prefix` + `branches` MUST match a merge-bot rule, or auto-merge silently never fires. That rule is one of the built-in `-` head/base pairs or a `rules` entry the caller passes. A tracker whose bump needs a human decision instead sets `auto-merge: false`, which prefixes the head so no merge-bot rule matches it, whatever `bump-branch-prefix` names. +- **D8.3 Upstream-version tracker.** Output: a scheduled resolver prints a JSON `name -> version` object to a committed state file. It opens a rolling per-branch bump PR naming only the moved keys, and the merge-bot auto-merges it. The `main` pin push the merge-bot makes publishes via the release gate, while a `develop` pin does not auto-publish. It ships via a `develop` dispatch (prerelease) or the next promotion to `main`. The tracker's `bump-branch-prefix` + `branches` MUST match a merge-bot rule, or auto-merge silently never fires. That rule is one of the built-in `-` head/base pairs or a `rules` entry the caller passes. A tracker whose bump needs a human decision instead sets `auto-merge: false`, which prefixes the head so no merge-bot rule matches it, whatever `bump-branch-prefix` names. A `main` pin it carries then lands by a human merge, which never auto-publishes (D4.1), so it ships on the next publish. - **D8.4 An identity allowlist used as a gate fails loud.** Where a gate compares `github.actor` (or a PR author) against hard-coded bot identities, the non-matching branch **emits a `::warning::`** on an otherwise-legitimate trigger. There it does not fall through silently. Output: a run that declines to act on an unrecognized identity is visibly annotated. *Prevents: the App being renamed, replaced, or reinstalled under a new slug, after which the comparison quietly evaluates false and the gate stops firing. The result is a green and silent run that looks identical to a healthy one.* The masking matters most where a second path hides the loss. One such path is a weekly schedule that keeps publishing, so the only symptom is release *timeliness*, easily missed for months. Where the failure is self-announcing instead (the merge-bot simply stops merging, so bot PRs visibly pile up) an annotation is optional. The delete job compares the same `user.login` as the merge jobs, so a renamed App already shows as piled-up bot PRs. Resolving the identity at run time (mint an App token, read `GET /app`) removes the hard-coded string entirely. Run-time resolution is the escalation if an allowlist proves fragile in practice. ### D9 - Style / Static @@ -221,7 +221,7 @@ An agent verifies a project in escalating modes, then renders a verdict. **Skip Assert the structural fact each *applicable* D-guarantee implies, and record **pass**, **fail**, or **N/A** per item. This section says how an audit is run and recorded rather than what must hold. A guarantee names its own constructs, and the requirement is `WORKFLOW.md` section 4's item together with whatever that item defers to. -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`. +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`. 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. @@ -237,11 +237,11 @@ For each *applicable* scenario, evaluate every job's `if:`/`needs:` against the | S4 | PR base = default branch, carrying a build target | smoke versions as prerelease, validate-release **succeeds** with its check exited early per D2.2, so the default-branch arm does **not** fire, aggregator **success**, promotion not blocked | D1.5, D2.2, D3.2 | | S5 | bot push to `main` not touching a release path (e.g. an Actions bump) | the paths filter excludes it, so nothing publishes | D4.1 | | S6 | code-affecting **bot** push to `main` (a human push/promotion, or any develop push, does not) | the `plan` job gates it to the App/Dependabot actor, and `main` publishes a release | D3, D4 | -| S7 | publish run (schedule, a bot push to main, or a dispatch) | builds the **one** trigger branch. `main` -> `X.Y.Z`, `prerelease=false`, registry stable, readme run. `develop` -> `X.Y.Z-g`, `prerelease=true`, registry prerelease. `release-asset-*` is consumed then deleted, and each package build-artifact (`nuget-build-*`, `pypi-build-*`) is deleted after its publish. **No dangling artifacts** | D3, D4, D5, D6, D7 | +| S7 | publish run (schedule, a bot push to main, or a dispatch). A schedule or push run at an already-released version is S9 instead | builds the **one** trigger branch. `main` -> `X.Y.Z`, `prerelease=false`, registry stable, readme run. `develop` -> `X.Y.Z-g`, `prerelease=true`, registry prerelease. `release-asset-*` is consumed then deleted, and each package build-artifact (`nuget-build-*`, `pypi-build-*`) is deleted after its publish. **No dangling artifacts** | D3, D4, D5, D6, D7 | | S8 | dispatch from a ref other than `main` or `develop` | **fails fast** | D2.3 | | S9 | re-run publish on a schedule or push trigger, version unchanged (a dispatch re-run refreshes the release instead, per D4.4) | release-create **skipped**, `release-asset-*` delete **skipped**; NuGet/PyPI pushes no-op (server dedupe); **package build-artifacts still deleted** (their download succeeded); **Docker still re-pushes** the image; no duplicate release | D4.4, D5.2 | | S10 | branch/version classification disagree | validate-release **fails loud**, build/publish skip | D2.2 | -| S11 | scheduled upstream-version bump (wrapper) | resolver detects a change -> commits the state file -> opens a per-branch bump PR. The merge-bot auto-merges it, or leaves it for the maintainer where the tracker sets `auto-merge: false` (D8.3). The `main` pin then publishes via the gate. A develop pin does not auto-publish, shipping instead via a develop dispatch or promotion | D8.3, D3.5 | +| S11 | scheduled upstream-version bump (wrapper) | resolver detects a change -> commits the state file -> opens a per-branch bump PR. The merge-bot auto-merges it, or leaves it for the maintainer where the tracker sets `auto-merge: false` (D8.3). A `main` pin the merge-bot merges then publishes via the gate, and one the maintainer merges ships on the next publish (D4.1). A develop pin does not auto-publish, shipping instead via a develop dispatch or promotion | D8.3, D3.5 | | 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 | @@ -295,14 +295,14 @@ What each type adds beyond that, and how its leaf behaves, is below. - **`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. -- **`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 the `main` pin is the gated publish D8.3 describes. Nothing in this row depends on which build-target types the wrapper also declares. +- **`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. - **`homeassistant`.** Adds a **file target**: distribution is a GitHub release that HACS installs from, so the release carries the integration zip. The contract's seam for that is D6.1's `release-asset--` upload collected by `pattern:`. A repo owning its release task supplies it itself, and a repo calling the hub-hosted task supplies it through its `build-release-asset` hook. A repo reaching the same tag-plus-asset outcome through a differently-named artifact diverges from D4.3 and D6.1 alike. That is a defect against the seam rather than against the release it produces. Its Python side follows home-assistant/core conventions rather than this fleet's defaults: pip with `requirements*.txt`, a `custom_components/` layout, and standalone `.ruff.toml` and `pyrightconfig.json`. That is expected rather than drift. And `mypy --strict` runs in CI. Test: S1 smoke-builds the zip, and S7 attaches it where the repo has a publisher. - **`eda`.** Adds a **file target**: distribution is a GitHub release data zip that a local EDA install pulls, supplied the way the `homeassistant` row gives. It also adds design-data validation to the pull request gate, the analogue of the code linters, `kicad-cli` ERC/DRC or library linting in practice. Where the repo generates build-time artifacts (gerbers, drill files, a BOM), that generation is deterministic from the design inputs. A data-only repo not yet building artifacts owes that only once it starts. Test: S1 smoke-builds the zip, S2 and S3 cover the validation gate, and S7 attaches it where the repo has a publisher. - **`codegen`.** Adds a generation workflow that runs as a matrix over both branches and is deterministic from an external source (D8.2). That workflow carries no per-run timestamp or GUID. It contributes no build target and no publish scenario of its own, so it changes no row of the table above. - **`csharp`, `python`, `cpp`, `docs`.** Add no pipeline construct. They decide what the validation job runs and what the repo's project configuration must hold. For `csharp` that is the analyzer and central-MSBuild rules and D1.6's C# coverage leg, and for `python` the profile split and D1.6's Python one. For `cpp` it is a shared `clang-format` feeding the lint gate, and for `docs` a lint-only CI with no build or test. A repo declaring one of these and nothing else reaches only the scenarios its publisher and its pull request workflow already supply. - **`source-only`.** Adds no build leaf of its own. In a repo declaring no build-target type beside it, the publish job reaches the reusable release task with `github: true`, every `enable_*` input false, and `expect_release_assets: false`. That produces tag + source zip + README + LICENSE with no asset download. In such a repo, the paths-filter matches nothing, so a retained `smoke-build` job is **structurally always skipped**, and the repo may drop that never-running job. A repo declaring a build-target type as well enables that target instead, this row taking nothing away from it. NBGV and `version.json` own the tag. Validation remains the caller's own job reaching the reusable validator. The aggregator `needs:` that validation job (D1.2), and a retained `smoke-build` job `needs:` the `changes` job rather than the validation job. The publish job depends on the same reusable validation task the PR workflow runs, which prevents a dispatch from releasing a ref that fails validation. The release task carries the D6.1 `pattern:` download and the `release-asset-*` cleanup step (D5.1 to D5.3 and D5.5). So a repo contains them whether it owns that task or calls the hub-hosted copy, and is checked on them either way. **Owning it changes only where the evidence is cited**, in the repo's own file or at the SHA it pins, per section 5A's citation rule. Test, where the repo has a publisher: S7 covers the release, S8 the dispatch guard, and S10 the classification gate. - **`hugo` (a static site deployed to a host the project owns).** Two independent surfaces, and keeping them apart is the point. The **release** is the `source-only` shape above, unchanged. The **deploy** is its own `workflow_dispatch` carrying an `environment` choice input, so redeploying an unchanged commit mints no tag, which matters because redeploying is routine. It runs a ref gate **first**, before anything is installed or written. The gate admits production from the default branch only. Any ref may reach a non-production environment, since proving a branch before it merges is what that environment is for. The deploy then runs the **same** reusable validation task the PR gate runs, so a dispatch cannot deploy a ref that fails validation. Then the deploy calls the hub-hosted `deploy-site-task.yml`. That task declares the `environment:` inside itself rather than on the calling job, since GitHub rejects a job carrying both `uses:` and `environment:`. The caller still maps the crossing secrets explicitly under `secrets:`. It maps `DEPLOY_SSH_PRIVATE_KEY` because the task declares it required. It maps the `SITE_AUTH_TOKEN_ID`/`SITE_AUTH_TOKEN` pair, or the `SITE_EXTRA_AUTH_TOKEN_ID`/`SITE_EXTRA_AUTH_TOKEN` pair for a second site, only where a token-gated live check needs it. The mapping is explicit because `secrets: inherit` is not used on a cross-repository call. For a secret the environment defines, the value the task's job reads is resolved by the task's own `environment:` binding. It comes from the caller's environment store, not from that mapping. That task hard-asserts the interfaces that follow. It requires the environment to carry `SITE_BASE_URL`, `DEPLOY_SSH_USER`, `DEPLOY_SSH_HOST` and `DEPLOY_SSH_KNOWN_HOSTS` as variables and `DEPLOY_SSH_PRIVATE_KEY` as a secret, each non-empty. It fails fast naming every missing one. It requires `SITE_AUTH_TOKEN_ID` and `SITE_AUTH_TOKEN` to be mapped together or not at all, and the same of `SITE_EXTRA_AUTH_TOKEN_ID` and `SITE_EXTRA_AUTH_TOKEN`. That second pair also needs a non-empty `SITE_EXTRA_BASE_URL` variable. And it requires a **deploy hook** at `.github/actions/deploy/action.yml`, one composite action the caller owns, run once for each `mode` input value, `build`, `prune` and `verify`. The hook declares every input the task passes across those runs, `mode`, `bundle-path`, `release-id` and `environment`. Its `build` run leaves `releases//` and `current` under `bundle-path`, each of which the task asserts. The task re-asserts the environment *name*, `production` or `staging`, in a job of its own. It does so because the `environment:` binding resolves before any step runs. Another reason is that a `workflow_call` caller is not bound by the dispatch choice list a human sees. The ref gate gets no counterpart re-assertion, so a caller reaching the task directly is trusted for the ref and not for the environment. That is a deliberate asymmetry rather than an omission. Its environment-bound job then does the following. It checks out full history (a shallow clone silently changes page metadata). It derives the release id **once** and exports it. Deriving it twice yields ids seconds apart, and the live check then asserts a version nothing installed. It runs the hook's `build` invocation, and installs the deploy credential from the environment. It uploads into a per-release directory hard-linked against the current release. The upload carries **no** delete flag (at an environment root a delete removes the rollback targets). It flips the pointer as a separate atomic step, so a failed transfer cannot half-publish. Then it runs the hook's `prune` and `verify` invocations. The second checks the running host (D4.6) against the site's own URL contract. Retention (D5.6) is bounded by a declared count with one side recorded as owning it. A deploy whose credential can observe the destination prunes and asserts the count in the `prune` hook. A credential confined **write-only**, by contrast, can neither delete nor read back. So that repo's `prune` hook is a no-op, the prune is a host-side timer, and the repo's runbook records that ownership. Widening the credential to bring the prune in-pipeline would trade a real confinement boundary for a check, and is the wrong trade. What the guarantee rejects is neither side owning it. There is one thing the pipeline cannot assert and the server config must. A non-public environment serving a byte-identical copy must not be indexed. That default belongs on the side that is harmless in production. That is because a non-public container missing the value is still behind its gate, while a production container inheriting it deindexes the site silently. -- **Operational (a `workflowModel`, not a type).** A `workflowModel: operational` repo layers direct commits to `develop` onto the `source-only` release shape above. It has the following workflows. The first is a **lint/validation** PR workflow that feeds the required `Check pull request workflow status job`. It uses the generic linters (editorconfig/EOL, markdownlint, cspell, actionlint) plus a domain validator, with **no unit tests**. Examples include Home Assistant `hass --script check_config`, `esphome config`, or a firmware build. Its triggers differ from the `release` model. It runs on pushes to `develop`, on every pull request, and on `workflow_dispatch`. Push validation is advisory. Pull request validation is enforced on `main` and reported but not required on `develop`. The second workflow is the standard `source-only` publisher. NBGV and `version.json` own the tag. The reusable release task creates tag + source zip + README + LICENSE. **The PR trigger filters no base branch.** A filter naming `main` alone starts no validation when a PR opens against `develop`. The aggregator then never reports, and the PR appears clean with an empty check list. D1.2 forbids that output. A filter naming both branches still strands a stacked PR retargeted onto `develop`. A retarget fires the `edited` activity type, which the default types omit. The push trigger causes a duplicate run after a PR merge. The change validates on the PR and again on the resulting push, regardless of merge method. The operational `develop` ruleset prescribes no merge method. The concurrency group uses the workflow name plus `${{ github.ref }}` (`GOVERNANCE.md` "Workflow YAML Conventions"). A pull request uses `refs/pull//merge`, while its push uses `refs/heads/develop`. The runs occupy different groups and neither cancels the other. Pay that cost. The lint-only gate costs only a few runner-minutes. Suppressing the push requires distinguishing a merge commit from a direct commit, which restores the ambiguity the trigger set removes. Having no build target, such a repo never reaches S1, whose input is a target change, on any pull request. That includes promotion and `develop` pull requests. See the branch-model note in Section 3 and [GOVERNANCE.md "Branching Model"][governance-branching-model]. +- **Operational (a `workflowModel`, not a type).** A `workflowModel: operational` repo layers direct commits to `develop` onto the `source-only` release shape above. It has the following workflows. The first is a **lint/validation** PR workflow that feeds the required `Check pull request workflow status job`. It uses the generic linters (editorconfig/EOL, markdownlint, cspell, actionlint) plus a domain validator, with **no unit tests**. Examples include Home Assistant `hass --script check_config`, `esphome config`, or a firmware build. Its triggers differ from the `release` model. It runs on pushes to `develop`, on every pull request, and on `workflow_dispatch`. Push validation is advisory. Pull request validation is enforced on `main` and reported but not required on `develop`. The second workflow is the standard `source-only` publisher. NBGV and `version.json` own the tag. The reusable release task creates tag + source zip + README + LICENSE. **The PR trigger filters no base branch.** A filter naming `main` alone starts no validation when a PR opens against `develop`. The aggregator then never reports, and the PR appears clean with an empty check list. D1.2 forbids that output. A filter naming both branches still starts none for a stacked PR, one opened against another feature branch. The trigger keeps the default activity types, so a retarget starts no run. The head keeps the check its last run posted against the old base. So a retargeted PR is pushed to, or closed and reopened, before it merges, which validates it against its new base. The push trigger causes a duplicate run after a PR merge. The change validates on the PR and again on the resulting push, regardless of merge method. The operational `develop` ruleset prescribes no merge method. The concurrency group uses the workflow name plus `${{ github.ref }}` (`GOVERNANCE.md` "Workflow YAML Conventions"). A pull request uses `refs/pull//merge`, while its push uses `refs/heads/develop`. The runs occupy different groups and neither cancels the other. Pay that cost. The lint-only gate costs only a few runner-minutes. Suppressing the push requires distinguishing a merge commit from a direct commit, which restores the ambiguity the trigger set removes. Having no build target, such a repo never reaches S1, whose input is a target change, on any pull request. That includes promotion and `develop` pull requests. See the branch-model note in Section 3 and [GOVERNANCE.md "Branching Model"][governance-branching-model]. diff --git a/catalog/snippets/configs/codecov.yml b/catalog/snippets/configs/.codecov.yml similarity index 100% rename from catalog/snippets/configs/codecov.yml rename to catalog/snippets/configs/.codecov.yml diff --git a/catalog/snippets/configs/vscode-tasks-python.json b/catalog/snippets/configs/vscode-tasks-python.json index c9e8189c8..c28a3b04b 100644 --- a/catalog/snippets/configs/vscode-tasks-python.json +++ b/catalog/snippets/configs/vscode-tasks-python.json @@ -29,7 +29,7 @@ // The type-checker swap composes with it: `uvx mypy@latest` for a mypy repo, `uvx pyright@latest` otherwise. // It omits "uv Sync" and "uv Upgrade", and "Python Test" runs the unittest command the repository's OPERATIONS.md gives rather than pytest, per the python-codestyle Skill "Two profiles". { - "label": "Ruff Format", + "label": "ruff format", "type": "process", "command": "uv", "args": [ @@ -44,7 +44,7 @@ } }, { - "label": "Ruff Check", + "label": "ruff check", "type": "process", "command": "uv", "args": [ @@ -79,8 +79,8 @@ "label": "Python Format", "dependsOrder": "sequence", "dependsOn": [ - "Ruff Format", - "Ruff Check", + "ruff format", + "ruff check", "Python Types" ], "group": { "kind": "build", "isDefault": true }, @@ -137,8 +137,6 @@ // Pre-commit already runs the prose gate diff-scoped and the EOL gate over the whole tree. // Lint: Prose below adds the prose gate in whole-repo mode, and Lint: EOL runs the hook's own EOL check on demand. // Every Lint task is language-agnostic, the same check as in the .NET snippet's Lint group. - // Each assumes the pre-commit-framework layout (hub_fetch_run.py at the workspace root). - // A repo using the Husky.Net snippet instead points them at .husky/hub_fetch_run.py. { "label": "Lint: EditorConfig", "type": "process", diff --git a/catalog/snippets/configs/vscode-tasks.json b/catalog/snippets/configs/vscode-tasks.json index 43dbc31fc..c230c6b08 100644 --- a/catalog/snippets/configs/vscode-tasks.json +++ b/catalog/snippets/configs/vscode-tasks.json @@ -132,10 +132,10 @@ "label": "Lint: EditorConfig", "type": "process", "command": "python3", - "args": [ "${workspaceFolder}/.husky/hub_fetch_run.py", "scripts/docker_lint.py", "--linter", "editorconfig-checker" ], + "args": [ "${workspaceFolder}/hub_fetch_run.py", "scripts/docker_lint.py", "--linter", "editorconfig-checker" ], "windows": { "command": "py", - "args": [ "-3", "${workspaceFolder}/.husky/hub_fetch_run.py", "scripts/docker_lint.py", "--linter", "editorconfig-checker" ] + "args": [ "-3", "${workspaceFolder}/hub_fetch_run.py", "scripts/docker_lint.py", "--linter", "editorconfig-checker" ] }, "problemMatcher": [], "presentation": { @@ -147,10 +147,10 @@ "label": "Lint: Workflows", "type": "process", "command": "python3", - "args": [ "${workspaceFolder}/.husky/hub_fetch_run.py", "scripts/docker_lint.py", "--linter", "actionlint" ], + "args": [ "${workspaceFolder}/hub_fetch_run.py", "scripts/docker_lint.py", "--linter", "actionlint" ], "windows": { "command": "py", - "args": [ "-3", "${workspaceFolder}/.husky/hub_fetch_run.py", "scripts/docker_lint.py", "--linter", "actionlint" ] + "args": [ "-3", "${workspaceFolder}/hub_fetch_run.py", "scripts/docker_lint.py", "--linter", "actionlint" ] }, "problemMatcher": [], "presentation": { @@ -162,10 +162,10 @@ "label": "Lint: Markdown", "type": "process", "command": "python3", - "args": [ "${workspaceFolder}/.husky/hub_fetch_run.py", "scripts/docker_lint.py", "--linter", "markdownlint" ], + "args": [ "${workspaceFolder}/hub_fetch_run.py", "scripts/docker_lint.py", "--linter", "markdownlint" ], "windows": { "command": "py", - "args": [ "-3", "${workspaceFolder}/.husky/hub_fetch_run.py", "scripts/docker_lint.py", "--linter", "markdownlint" ] + "args": [ "-3", "${workspaceFolder}/hub_fetch_run.py", "scripts/docker_lint.py", "--linter", "markdownlint" ] }, "problemMatcher": [], "presentation": { @@ -177,10 +177,10 @@ "label": "Lint: Spelling", "type": "process", "command": "python3", - "args": [ "${workspaceFolder}/.husky/hub_fetch_run.py", "scripts/docker_lint.py", "--linter", "cspell" ], + "args": [ "${workspaceFolder}/hub_fetch_run.py", "scripts/docker_lint.py", "--linter", "cspell" ], "windows": { "command": "py", - "args": [ "-3", "${workspaceFolder}/.husky/hub_fetch_run.py", "scripts/docker_lint.py", "--linter", "cspell" ] + "args": [ "-3", "${workspaceFolder}/hub_fetch_run.py", "scripts/docker_lint.py", "--linter", "cspell" ] }, "problemMatcher": [], "presentation": { @@ -192,10 +192,10 @@ "label": "Lint: Prose", "type": "process", "command": "python3", - "args": [ "${workspaceFolder}/.husky/hub_fetch_run.py", ".github/actions/prose-gate/prose_lint.py", "." ], + "args": [ "${workspaceFolder}/hub_fetch_run.py", ".github/actions/prose-gate/prose_lint.py", "." ], "windows": { "command": "py", - "args": [ "-3", "${workspaceFolder}/.husky/hub_fetch_run.py", ".github/actions/prose-gate/prose_lint.py", "." ] + "args": [ "-3", "${workspaceFolder}/hub_fetch_run.py", ".github/actions/prose-gate/prose_lint.py", "." ] }, "problemMatcher": [], "presentation": { @@ -207,10 +207,10 @@ "label": "Lint: EOL", "type": "process", "command": "python3", - "args": [ "${workspaceFolder}/.husky/hub_fetch_run.py", ".github/actions/repo-gate/repo_gate.py", "--check", "eol" ], + "args": [ "${workspaceFolder}/hub_fetch_run.py", ".github/actions/repo-gate/repo_gate.py", "--check", "eol" ], "windows": { "command": "py", - "args": [ "-3", "${workspaceFolder}/.husky/hub_fetch_run.py", ".github/actions/repo-gate/repo_gate.py", "--check", "eol" ] + "args": [ "-3", "${workspaceFolder}/hub_fetch_run.py", ".github/actions/repo-gate/repo_gate.py", "--check", "eol" ] }, "problemMatcher": [], "presentation": { diff --git a/catalog/snippets/hub_fetch_run.py b/catalog/snippets/hub_fetch_run.py index 893eb98d3..40f527256 100644 --- a/catalog/snippets/hub_fetch_run.py +++ b/catalog/snippets/hub_fetch_run.py @@ -28,7 +28,7 @@ # The files a script reads or imports from the hub tree, fetched before it runs. COMPANIONS = { PROSE_GATE_PATH: (".github/actions/prose-gate/prose-gate.json",), - "scripts/docker_lint.py": ("scripts/local_review.py", "spec/git_env.py"), + "scripts/docker_lint.py": (), } PROBE_TIMEOUT = 30 LOOKUP_TIMEOUT = 5 @@ -193,9 +193,9 @@ def main(argv: list[str]) -> int: env = dict(os.environ) if is_prose_gate and not env.get(PROVENANCE_VAR, "").strip(): if commit: - env[PROVENANCE_VAR] = f"{HUB_REPO}@{commit} (hub-fetch-run main)" + env[PROVENANCE_VAR] = f"{HUB_REPO}@{commit} (hub_fetch_run.py main)" else: - env[PROVENANCE_VAR] = f"{HUB_REPO}@main (hub-fetch-run, commit unresolved)" + env[PROVENANCE_VAR] = f"{HUB_REPO}@main (hub_fetch_run.py, commit unresolved)" with tempfile.TemporaryDirectory() as scratch: paths = (*COMPANIONS.get(hub_path, ()), hub_path) try: diff --git a/catalog/snippets/husky/README.md b/catalog/snippets/husky/README.md index 038c0ed27..7aed39ae3 100644 --- a/catalog/snippets/husky/README.md +++ b/catalog/snippets/husky/README.md @@ -6,7 +6,7 @@ runs **language formatting/lint and the fleet's shared doc gates**. For .NET it `ruff check` / the repo's type checker (native tooling, no Docker, the same checks the `../pre-commit/.pre-commit-config.yaml` snippet runs). It also runs the diff-scoped prose/comment-style gate over the paths the commit stages, and the whole-tree line-ending check. Copy `../hub_fetch_run.py` -alongside `pre-commit` for the doc gates to run. The script fetches those two checks fresh from +into the repo root for the doc gates to run. The root is where every downstream repo keeps it, whichever hook it wires. The script fetches those two checks fresh from `ptr727/ProjectTemplate`'s `main` branch and runs them, rather than vendoring or pinning a copy. A pin that nothing keeps current goes stale by construction. CI (this repo's own, and the hub's) is the backstop for a change that lands broken on `main` before it does real damage locally. The prose gate adds one diff --git a/catalog/snippets/husky/pre-commit b/catalog/snippets/husky/pre-commit index 19b5ec124..341c76598 100644 --- a/catalog/snippets/husky/pre-commit +++ b/catalog/snippets/husky/pre-commit @@ -4,18 +4,17 @@ set -eu # Local pre-commit: language formatting/lint, plus the fleet's shared doc gates. -# The doc gates run via hub_fetch_run.py, copied alongside this file. +# The doc gates run via hub_fetch_run.py, copied into the repo root, where every downstream repo keeps it. # It fetches them fresh from ptr727/ProjectTemplate's `main` branch rather than vendoring or pinning them. # See hub_fetch_run.py's own docstring, and catalog/snippets/husky/README.md, for why. # Full doc-lint set (Markdown, spelling, workflow YAML, EditorConfig) stays in CI and the VS Code Lint tasks, since those need Docker. -# The absolute path is captured before the cd below, since $0 resolves against the original directory. -hub_fetch_run="$(cd "$(dirname "$0")" && pwd)/hub_fetch_run.py" - # Git already runs a hook from the top level, but this is belt and braces for an invocation that does not. # The doc gates below take a relative scan root, which would otherwise resolve against whatever directory the caller stood in. cd "$(git rev-parse --show-toplevel)" || exit 1 +hub_fetch_run="$PWD/hub_fetch_run.py" + # .NET: CSharpier + dotnet format style via Husky.Net. # Drop this block in a non-.NET repo, rather than guarding it. # A repo that keeps it declares dotnet required, and a missing tool fails the commit loudly, not silently. diff --git a/docs/pre-commit-hooks-rollout.md b/docs/pre-commit-hooks-rollout.md index efd897edf..cfe460934 100644 --- a/docs/pre-commit-hooks-rollout.md +++ b/docs/pre-commit-hooks-rollout.md @@ -33,7 +33,7 @@ vendored or pinned. ## Per-Repo Conversion -Copy and adapt the applicable catalog snippet plus `catalog/snippets/hub_fetch_run.py`. +Copy and adapt the applicable catalog snippet, and copy `catalog/snippets/hub_fetch_run.py` into the repo root. Enable it (`git config core.hooksPath .husky`, or `uv tool install pre-commit` once then `pre-commit install`). For the Husky.Net snippet specifically, also run `dotnet tool restore` then `dotnet husky install`, which generates `.husky/_/husky.sh`, the file the hook sources. diff --git a/docs/repo-config.md b/docs/repo-config.md index 9525328c2..37026771c 100644 --- a/docs/repo-config.md +++ b/docs/repo-config.md @@ -1,6 +1,6 @@ # Repository Configuration (Hub-Only) -The process for applying, checking, and regenerating the canonical repository configuration. This document and the entire `repo-config/` directory are hub-only. Every command runs from a hub checkout at `main` and names its target repository. +The process for applying, checking, and regenerating the canonical repository configuration. This document and the entire `repo-config/` directory are hub-only. Every command names its target repository and runs from a hub checkout at `main`, except for the `develop` case that "Applying the Config" names. ## Configuration Source @@ -15,9 +15,9 @@ The hub holds all fleet-wide repository configuration: - `configure.sh` applies or checks those payloads through the GitHub API. - `central/` holds the READMEs `scripts/central_config.py` writes into the central bot-settings repositories, per "Central Bot Settings" below. -Downstream repositories carry no `repo-config/` directory. The registry's `workflowModel` selects the `develop` payload, and its `environments` declares the deployment environments the check mode asserts. Both are read from `registry/repos.json` rather than from a payload here. Commands that operate before registry enrollment pass the model explicitly. +Downstream repositories carry no `repo-config/` directory. The registry's `workflowModel` selects the `develop` payload, and its `environments` declares the deployment environments the check mode asserts. Both are read from `registry/repos.json` rather than from a payload here. A `check` before registry enrollment passes the model explicitly, and `apply` refuses a repository with no registry entry. -The carried `AUDIT.md` reaches the hub at `main` for its configuration check. The fleet-wide `spec/audit.py` reads the same hub payloads directly. Both paths compare live state against one source. +The carried `AUDIT.md` reaches the hub at `main` for its configuration check, or at `develop` for an entry not yet promoted. The fleet-wide `spec/audit.py` reads the same hub payloads directly. Both paths compare live state against one source. ## Per-Repository Secrets @@ -29,7 +29,7 @@ Downstream repositories carry no copy of `spec/secrets.json`. `baseline` applies **Configure by importing the JSON payloads, never by hand-building the rules** (hand reconstruction has gone wrong on past setups). The result must be **exactly two rulesets named `develop` and `main`**, and the names are load-bearing (`AGENTS.md` and the workflows reference them). Only the `develop` *content* varies by model. -Remove all classic branch-protection rules and stray rulesets. Run `configure.sh apply` from a hub checkout at `main`, naming the target repository and its model. Both modes need project access on the token as well as admin on the repository, since the project link is read and written through GraphQL. A token that cannot read projects stops `apply` in its pre-flight with nothing written, naming the scope to grant. Under `check` such a token reads as a failing project group. A token that can read them but not write one reaches the link write itself and fails there. The script applies `settings.json`, the Dependabot security features, the label set, both rulesets, the link to the fleet project, and the repository's secrets from `~/.secrets/`. The link is written only where it is absent. The declared project title is compared with the live one first. The comparison exists because a project number is reusable and the same declared number is applied to every fleet repository. A registered repository can omit the model and use the registry lookup. A repository outside the registry passes the model explicitly: +Run `configure.sh apply` from a hub checkout at `main`, naming the target repository and its model. `apply` refuses, writing nothing, a repository with no entry in the registry it reads. Without the entry, the rulesets and policy files would come from the default policy. Once `apply` has created both rulesets, remove all classic branch-protection rules and stray rulesets. Removed first, they would leave the branches unprotected wherever `apply` then refuses. A repository whose entry has merged to `develop` but not yet been promoted is configured and checked from a hub checkout at `develop`. Every other repository's run stays on `main`. Both modes need project access on the token as well as admin on the repository, since the project link is read and written through GraphQL. A token that cannot read projects stops `apply` in its pre-flight with nothing written, naming the scope to grant. Under `check` such a token reads as a failing project group. A token that can read them but not write one reaches the link write itself and fails there. The script applies `settings.json`, the Dependabot security features, the label set, both rulesets, the link to the fleet project, and the repository's secrets from `~/.secrets/`. The link is written only where it is absent. The declared project title is compared with the live one first. The comparison exists because a project number is reusable and the same declared number is applied to every fleet repository. A registered repository can omit the model and use the registry lookup. The model is passed as: ```sh repo-config/configure.sh apply owner/repo release|operational diff --git a/docs/reusable-workflows.md b/docs/reusable-workflows.md index 5139d4579..af34f36e5 100644 --- a/docs/reusable-workflows.md +++ b/docs/reusable-workflows.md @@ -416,7 +416,7 @@ jobs: fi ``` -Both stub shapes share two trigger rules. The `pull_request` trigger names no base branch. A retarget fires the `edited` activity type, which the default types omit. So a base filter strands a stacked pull request retargeted onto `develop` at "Expected, waiting for status to be reported". The aggregator's `name:` is an expression yielding the ruleset-bound name only on a `pull_request` run, per [WORKFLOW.md][workflow] D1.5. A `workflow_dispatch` run, and the no-build shape's push to `develop`, report `Check workflow status job` instead. So a run on a pull request's head that skipped that pull request's gates cannot post its required check. The audit's `interface` check reports a literal aggregator name in a stub that any other event also triggers. +Both stub shapes share two trigger rules. The `pull_request` trigger names no base branch. A base filter starts no run for a stacked pull request, one opened against another feature branch. Once retargeted onto `develop`, it waits at "Expected, waiting for status to be reported". The trigger keeps the default activity types, so a retarget starts no run. The head keeps the check its last run posted against the old base. So a retargeted pull request is pushed to, or closed and reopened, before it merges, which validates it against its new base. The aggregator's `name:` is an expression yielding the ruleset-bound name only on a `pull_request` run, per [WORKFLOW.md][workflow] D1.5. A `workflow_dispatch` run, and the no-build shape's push to `develop`, report `Check workflow status job` instead. So a run on a pull request's head that skipped that pull request's gates cannot post its required check. The audit's `interface` check reports a literal aggregator name in a stub that any other event also triggers. The task expects three things of the repository it gates, and each one fails quietly where it is missing: @@ -495,7 +495,7 @@ Quote each entry, and give each one a version. The `Build test matrix job` runs 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. So a `uv.lock` whose `requires-python` floor is above the default still syncs there. 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 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. +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. 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. Any other key is the repo's own, passed through to its hook. diff --git a/registry/repos.json b/registry/repos.json index 57779239f..d2ccdb99c 100644 --- a/registry/repos.json +++ b/registry/repos.json @@ -143,7 +143,7 @@ } } }, - "driftNotes": ["Carries ARCHITECTURE.md and codecov.yml beyond the baseline.", "First csharp+python repo: a .NET application at the root plus a stdlib-only Python tooling subtree (RegressionTests/, uvx scripts profile - no uv.lock, pyproject carries only ruff+mypy config, PlexCleaner#855). python.uvlock.pinned is N/A for that subtree (no uv project). codecov.yml stays required for the C# side. Reference for the csharp+python shape (issue #339)."] + "driftNotes": ["Carries ARCHITECTURE.md beyond the baseline.", "First csharp+python repo: a .NET application at the root plus a stdlib-only Python tooling subtree (RegressionTests/, uvx scripts profile - no uv.lock, pyproject carries only ruff+mypy config, PlexCleaner#855). python.uvlock.pinned is N/A for that subtree (no uv project). The .codecov.yml file stays required for the C# side. Reference for the csharp+python shape (issue #339)."] }, { "name": "ESPHome-NonRoot", diff --git a/repo-config/README.md b/repo-config/README.md index 2ab3f2d6c..18f765df9 100644 --- a/repo-config/README.md +++ b/repo-config/README.md @@ -1,11 +1,11 @@ # repo-config -Hub-only repository and branch configuration held as committed files, kept out of `.github/` (which holds the GitHub-consumed configuration: workflows, Dependabot). Downstream repositories carry no `repo-config/` directory. Apply and check commands run from a hub checkout at `main` and name the target repository. +Hub-only repository and branch configuration held as committed files, kept out of `.github/` (which holds the GitHub-consumed configuration: workflows, Dependabot). Downstream repositories carry no `repo-config/` directory. Apply and check commands name the target repository. They run from a hub checkout at `main`, except for the `develop` case that the `configure.sh` entry below names. - `main.json`, `develop.json`, and `operational/develop.json`: the canonical branch rulesets as the managed part of the writable API subset (`name`, `target`, `enforcement`, `conditions`, `rules`). `main.json` is shared. `develop.json` serves release repos, and `operational/develop.json` serves operational repos. `repo-config/configure.sh check owner/repo release|operational` compares the selected payloads with the live rulesets. `bypass_actors` is writable and deliberately unmanaged, so no payload declares one and nothing diffs it. Who may bypass a ruleset is a human decision taken in the UI, which `repo-config/configure.sh` preserves on `apply` and reports without asserting on `check`. - `labels.json`: the fleet label set, one `name`, `color`, and `description` per label. `repo-config/configure.sh apply owner/repo release|operational` creates or updates every declared label by name and deletes nothing, so a label a repo adds of its own stays. `check` asserts each declared label on all three fields and reports the undeclared ones without judging them. - `project.json`: the fleet project every repository is linked to, declared as the project owner, the project number, and the project title. `repo-config/configure.sh apply owner/repo release|operational` resolves the number to a live project and refuses the run when that project's title is not the declared one. It writes the link only when the repository does not already hold it, so a second apply is a read. `check` asserts the link and counts the repository's other project links without judging them, the same way it treats a label the payload never declared. -- `configure.sh`: run from a hub checkout at `main`, per [GOVERNANCE.md "Hub-Hosted Tooling"][governance-hub-hosted-tooling]. It resolves every payload path against the hub's `repo-config/` directory. Name the target repository explicitly, since the command defaults to whichever repository the shell is sitting in. `repo-config/configure.sh apply owner/repo release|operational` creates or updates the settings, Dependabot security features, labels, rulesets, and the fleet project link idempotently. With `--checkout ` it also writes the agent policy files into that local checkout. See [Agent Policy][agent-policy]. `repo-config/configure.sh check owner/repo release|operational` is the read-only counterpart and exits non-zero on drift. It is not an exact inverse. It also asserts the agent policy files on the default branch. It asserts that every environment the registry's `environments` declares for the repo exists and carries the declared deployment-branch policy. `apply` writes neither, for the reason [docs/repo-config.md][repo-config-doc] "Deployment Environments" gives. The model defaults to the registry `workflowModel` lookup. Pass it explicitly for a repository outside the registry. Both commands exit early, writing nothing, when the target's registry entry carries `status: "archived"`. GitHub rejects every write to an archived repository, so `apply` could never clear the drift `check` would otherwise report there forever. +- `configure.sh`: run from a hub checkout at `main`, per [GOVERNANCE.md "Hub-Hosted Tooling"][governance-hub-hosted-tooling]. It resolves every payload path against the hub's `repo-config/` directory. Name the target repository explicitly, since the command defaults to whichever repository the shell is sitting in. `repo-config/configure.sh apply owner/repo release|operational` creates or updates the settings, Dependabot security features, labels, rulesets, and the fleet project link idempotently. With `--checkout ` it also writes the agent policy files into that local checkout. See [Agent Policy][agent-policy]. `repo-config/configure.sh check owner/repo release|operational` is the read-only counterpart and exits non-zero on drift. It is not an exact inverse. It also asserts the agent policy files on the default branch. It asserts that every environment the registry's `environments` declares for the repo exists and carries the declared deployment-branch policy. `apply` writes neither, for the reason [docs/repo-config.md][repo-config-doc] "Deployment Environments" gives. The model defaults to the registry `workflowModel` lookup. Pass it explicitly to `check` for a repository outside the registry. `apply` refuses such a repository before any write, as the entry may be on `develop` only. A repository whose entry is merged to `develop` but not promoted is configured and checked from a hub checkout at `develop`. Every other repository's run stays on `main`. Both commands exit early, writing nothing, when the target's registry entry carries `status: "archived"`. GitHub rejects every write to an archived repository, so `apply` could never clear the drift `check` would otherwise report there forever. - `central/`: the README sources for the owner's central CodeRabbit and Qodo settings repositories, which `scripts/central_config.py` writes. See [docs/repo-config.md][repo-config-doc] "Central Bot Settings". diff --git a/repo-config/configure.sh b/repo-config/configure.sh index a32435d0e..a5dbc998e 100755 --- a/repo-config/configure.sh +++ b/repo-config/configure.sh @@ -195,9 +195,15 @@ registry="$script_dir/../registry/repos.json" # The script spec/validate.py refuses both when it is run. name="${repo##*/}" +# Call as `jqr FILTER...`: jq -r plus stripping a line's trailing \r that a native Windows jq (WinGet's jq-1.8.2) puts there. +# The \r bash expands here, a literal byte rather than sed's own backslash-escape. +# That is because sed's own escape is a GNU extension a BSD sed would not honor. +jqr() { jq -r "$@" | sed $'s/\r$//'; } + archived_status="" +# shellcheck disable=SC2016 # $n is a jq --arg variable, not a shell expansion if [ -f "$registry" ]; then - if ! archived_status="$(jq -r --arg n "$name" '(.repos[] | select(.name==$n) | .status) // empty' "$registry" | sed $'s/\r$//')"; then + if ! archived_status="$(jqr --arg n "$name" '(.repos[] | select(.name==$n) | .status) // empty' "$registry")"; then echo "Failed to read status from $registry (invalid JSON?)." >&2 exit 1 fi @@ -205,6 +211,19 @@ if [ -f "$registry" ]; then echo "$repo is archived in $registry. GitHub rejects a write to an archived repository, so $cmd makes none and stops here." exit 0 fi + if [ "$cmd" = apply ]; then + if ! entry_count="$(jqr --arg n "$name" '[.repos[] | select((.name|ascii_downcase)==($n|ascii_downcase))] | length' "$registry")"; then + echo "Failed to read the entry names from $registry." >&2 + exit 1 + fi + if [ "$entry_count" = 0 ]; then + echo "$repo has no entry in $registry, so apply makes no write. The entry may be on develop only. Run apply from a hub checkout at develop once the entry has merged there. Otherwise add the entry first." >&2 + exit 1 + fi + fi +elif [ "$cmd" = apply ]; then + echo "Registry $registry not found, so apply makes no write. Run it from a hub checkout." >&2 + exit 1 fi if [ -z "$model" ]; then @@ -823,11 +842,6 @@ jq_has() { jq -e "$@" >/dev/null 2>&1; } # The vulnerability-alerts endpoint is the example, returning 204 when enabled and 404 when disabled. gh_ok() { gh api "$@" >/dev/null 2>&1; } -# Call as `jqr FILTER...`: jq -r plus stripping a line's trailing \r that a native Windows jq (WinGet's jq-1.8.2) puts there. -# The \r bash expands here, a literal byte rather than sed's own backslash-escape. -# That is because sed's own escape is a GNU extension a BSD sed would not honor. -jqr() { jq -r "$@" | sed $'s/\r$//'; } - check_ruleset() { # payload-file - the live ruleset must match the committed policy, driven by the payload local file="$1" rname id live t want got want_enf if [ ! -e "$file" ]; then diff --git a/scripts/README.md b/scripts/README.md index a54c2616c..785460569 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -74,7 +74,7 @@ The reusable prose gate reads optional exclusions from `.github/prose-gate-exclu The file set is what git tracks plus what it is not ignoring. The diff scope counts an untracked file as added in full, so a new file is read before it is staged rather than after. That is the file set where git can describe the tree. Where it cannot, the run warns and walks the filesystem instead, which applies no ignore rules and skips the generated roots by name. Everything a verdict rests on is read from the repository named on the command line. That means the rule set, the file set, the diff, and the repository-relative keys that join the last two. Reading any of them from the directory the process happens to stand in is what produced every false clean on record. Those false cleans include an absolute path argument that reported clean over a tree it had read in full. Each run states its scope on stderr, because a gate that read nothing prints what a gate with nothing to report prints. -That same line names the copy that produced the verdict, so a finding is attributable to a commit rather than to the gate in general. A repository reaches this gate at whatever hub commit its own workflow pins. A rule that changed after that pin is therefore a rule no local run has. A finding raised by the older copy then reproduces nowhere. The composite action passes its own `owner/repo@ref` through `--provenance`. It is the only source that knows the pin, since a checked-out action carries no history to read it from. `PROSE_GATE_PROVENANCE` plays the same role for a caller invoking the script directly. The extraction recipe in [`GOVERNANCE.md`][governance] "Running the Linters Locally (Known-Working Invocations)" sets it. `hub_fetch_run.py` also sets it, to `ptr727/ProjectTemplate@ (hub-fetch-run main)`, naming the `main` commit it fetched. When it cannot resolve that commit, `hub_fetch_run.py` sets `ptr727/ProjectTemplate@main (hub-fetch-run, commit unresolved)` instead. Failing both `--provenance` and that variable, the script's own checkout answers, and only where that checkout tracks the script. An untracked copy and a copy under no repository each report `unknown` rather than a plausible commit. A tracked copy edited since its commit is named `-dirty`. Both the `unknown` and `-dirty` outcomes exist because a well-formed wrong attribution sends the next investigation at a copy nobody ran. +That same line names the copy that produced the verdict, so a finding is attributable to a commit rather than to the gate in general. A repository reaches this gate at whatever hub commit its own workflow pins. A rule that changed after that pin is therefore a rule no local run has. A finding raised by the older copy then reproduces nowhere. The composite action passes its own `owner/repo@ref` through `--provenance`. It is the only source that knows the pin, since a checked-out action carries no history to read it from. `PROSE_GATE_PROVENANCE` plays the same role for a caller invoking the script directly. The extraction recipe in [`GOVERNANCE.md`][governance] "Running the Linters Locally (Known-Working Invocations)" sets it. `hub_fetch_run.py` also sets it, to `ptr727/ProjectTemplate@ (hub_fetch_run.py main)`, naming the `main` commit it fetched. When it cannot resolve that commit, `hub_fetch_run.py` sets `ptr727/ProjectTemplate@main (hub_fetch_run.py, commit unresolved)` instead. Failing both `--provenance` and that variable, the script's own checkout answers, and only where that checkout tracks the script. An untracked copy and a copy under no repository each report `unknown` rather than a plausible commit. A tracked copy edited since its commit is named `-dirty`. Both the `unknown` and `-dirty` outcomes exist because a well-formed wrong attribution sends the next investigation at a copy nobody ran. In Markdown an HTML comment carrying no sentence punctuation is treated as a structural marker rather than commentary. It therefore takes neither a capital nor a sentence split. The reference-link group headers, the ToC-omit directive, and the `agent-safety` install markers are each matched verbatim by a tool. Rewriting one to satisfy the rule therefore breaks whatever reads it. A Markdown comment that does punctuate a sentence is prose and is judged as prose. diff --git a/scripts/build_dist.py b/scripts/build_dist.py index 54cc09d05..1e512f0b2 100755 --- a/scripts/build_dist.py +++ b/scripts/build_dist.py @@ -386,6 +386,33 @@ def include_source(rel): return path +def _trailing_definitions(lines, start, reader): + """The line where the file's trailing link-reference definitions begin, or `len(lines)` where none trail it. + + Only a body running to the end of the file reaches them, and they belong to the whole document rather than to its last section. + Copied into a skill, each one is a definition nothing there uses. + The parser decides which lines a definition spans, so a line it ends a definition before is content. + The HTML comments that group them by type belong to the block too. + The walk goes back from the end and stops at the first line that is none of these, or at `start`. + """ + text = "\n".join(lines) + owner = {index: d.line for d in reader.link_definitions(text) for index in range(d.line, d.end)} + cut = len(lines) + found = False + index = len(lines) - 1 + while index > start: + stripped = lines[index].strip() + if index in owner: + cut = index = owner[index] + found = True + elif stripped.startswith(""): + cut = index + elif stripped: + break + index -= 1 + return cut if found else len(lines) + + def heading_body(lines, heading, key): """The lines under the one heading whose text case-folds to `heading`, up to the next heading at its level or above. @@ -395,7 +422,8 @@ def heading_body(lines, heading, key): a blockquote, or a list item is content to both, and so is a setext heading. They match on the parsed text case-folded, so a re-cased heading still resolves. Two matches are two answers to one question, refused rather than resolved to the first. A body ends at any - heading of its level or above, level one included. A fidelity region ends only at the next + heading of its level or above, level one included. One that runs to the end of the file ends + before the file's trailing link-reference definitions instead, which belong to the whole document. A fidelity region ends only at the next level-two heading. """ reader = _fidelity_text() @@ -415,6 +443,8 @@ def heading_body(lines, heading, key): end = next( (index for index, level, _ in headings if index > start and level <= depth), len(lines) ) + if end == len(lines): + end = _trailing_definitions(lines, start, reader) blocks = [b for b in reader.code_blocks(text) if start < b.start < end] if any(b.fenced and not b.closed for b in blocks): # A fence the body leaves open would swallow the end marker on the next scan and blame the skill for a defect in its source. diff --git a/scripts/docker_lint.py b/scripts/docker_lint.py index ce6374c03..296015af4 100755 --- a/scripts/docker_lint.py +++ b/scripts/docker_lint.py @@ -18,13 +18,29 @@ from pathlib import Path from typing import IO -import local_review - PSSCRIPTANALYZER_VERSION = "1.23.0" PSSCRIPTANALYZER_VOLUME = f"projecttemplate-psscriptanalyzer-{PSSCRIPTANALYZER_VERSION}" MAX_FILE_ARGUMENT_BYTES = 16 * 1024 SNAPSHOT_PREFIX = "docker-lint-snapshot-" OWNER_SUFFIX = ".owner" +GIT_TIMEOUT = 300 +GIT_LOCATION_VARS = ( + "GIT_ALTERNATE_OBJECT_DIRECTORIES", + "GIT_CONFIG", + "GIT_CONFIG_PARAMETERS", + "GIT_CONFIG_COUNT", + "GIT_OBJECT_DIRECTORY", + "GIT_DIR", + "GIT_WORK_TREE", + "GIT_IMPLICIT_WORK_TREE", + "GIT_GRAFT_FILE", + "GIT_INDEX_FILE", + "GIT_NO_REPLACE_OBJECTS", + "GIT_REPLACE_REF_BASE", + "GIT_PREFIX", + "GIT_SHALLOW_FILE", + "GIT_COMMON_DIR", +) @dataclass(frozen=True) @@ -139,6 +155,15 @@ def run_command( raise CommandFailed(f"could not start command: {error}") from error +def git_environment() -> dict[str, str]: + """Return this process's environment without the variables a git hook sets. + + One of them would name the hook's repository or index rather than the root this run lints. + The list is `spec/git_env.py`'s, copied so the fetched wrapper runs with no hub file beside it. + """ + return {k: v for k, v in os.environ.items() if k not in GIT_LOCATION_VARS} + + def ls_files( root: Path, patterns: Sequence[str] = (), *, include_untracked: bool = True ) -> list[str]: @@ -162,7 +187,7 @@ def ls_files( command.extend(["--others", "--exclude-standard"]) command.extend(["--", *patterns, NODE_MODULES_EXCLUDE]) try: - result = subprocess.run(command, check=True, capture_output=True) + result = subprocess.run(command, env=git_environment(), check=True, capture_output=True) except FileNotFoundError as error: raise CommandFailed("target discovery failed: git was not found") from error except subprocess.CalledProcessError as error: @@ -281,11 +306,26 @@ def snapshot_parent(root: Path) -> Path: Any Docker setup that can mount the checkout reaches it, and git never lists it. The system temporary directory is outside Docker Desktop for Linux's default file sharing. + `--absolute-git-dir` resolves per worktree, so two worktrees of one repository never share it. """ + command = ["git", "rev-parse", "--absolute-git-dir"] try: - return local_review.git_dir(root) - except local_review.CannotRun as error: - raise CommandFailed(f"snapshot failed: {error}") from error + result = subprocess.run( + command, + cwd=root, + env=git_environment(), + capture_output=True, + check=False, + timeout=GIT_TIMEOUT, + ) + except (OSError, subprocess.SubprocessError) as error: + raise CommandFailed( + f"snapshot failed: {shlex.join(command)} could not be run ({error})" + ) from error + if result.returncode != 0: + detail = os.fsdecode(result.stderr).strip() + raise CommandFailed(f"snapshot failed: {shlex.join(command)} failed: {detail}") + return Path(os.fsdecode(result.stdout).rstrip("\n")) def exit_on_sigterm(signum: int, _frame: object) -> None: @@ -328,10 +368,25 @@ def remove_snapshot(snapshot: Path) -> bool: """Remove a snapshot, whose top directory takes the checkout's mode and so may be read-only.""" with contextlib.suppress(OSError): snapshot.chmod(stat.S_IRWXU) - shutil.rmtree(snapshot, onexc=local_review.unlink_read_only) + shutil.rmtree(snapshot, onexc=unlink_read_only) return not os.path.lexists(snapshot) +def unlink_read_only(func: object, path: str, exc: BaseException) -> None: + """An rmtree error handler that removes a read-only file, and swallows anything else. + + POSIX unlinks a read-only file, since that needs write access to its directory, but Windows refuses. + Any other failure is left for `remove_snapshot`'s own existence check to report. + """ + if func is not os.unlink or not isinstance(exc, PermissionError): + return + try: + os.chmod(path, stat.S_IWRITE) + os.unlink(path) + except OSError: + pass + + def remove_stale_snapshots(parent: Path) -> int: """Remove each snapshot whose run ended without removing it, a killed task's for one. diff --git a/spec/audit.py b/spec/audit.py index 5af4563f7..fbb5015da 100755 --- a/spec/audit.py +++ b/spec/audit.py @@ -1221,6 +1221,13 @@ def check_interface(path, contract, text): and events - {"pull_request"} and (matches[key][2] if key in matches else value) == name ] + if name and events and "pull_request" not in events: + findings.append( + ( + "DRIFT", + f"interface: {path} has no pull_request trigger, so no pull request run posts the ruleset-bound check '{name}' with that run's gates. Add a pull_request trigger (WORKFLOW.md D1.5)", + ) + ) # An expression naming the check on every event is already its job's off-PR finding where another event triggers the workflow. every_event = any(m[1] == m[2] == name for m in matches.values()) if name and name not in gated and name not in names.values() and not (off_pr and every_event): @@ -1691,13 +1698,6 @@ def intent_ref(item, path): return path, None -def declared_alternatives(baseline): - """Map each baseline path to the `alternatives` its entry declares, the other paths it may sit at.""" - return { - item["path"]: list(item["alternatives"]) for item in baseline if item.get("alternatives") - } - - def contents_text(content): """The decoded text of a contents API response, or None where it holds no inline file content. @@ -1708,54 +1708,41 @@ def contents_text(content): return base64.b64decode(content["content"]).decode("utf-8", "replace") -def read_baseline_file(slug, ref, path, alternatives=()): - """The path a baseline file was found at and its contents response at `ref`, a branch or a commit, or `(path, None)`.""" - for candidate in (path, *alternatives): - content = gh(f"repos/{slug}/contents/{candidate}?ref={ref}", ok404=True) - if content is not None: - return candidate, content - return path, None +def read_baseline_file(slug, ref, path): + """A baseline file's contents response at `ref`, a branch or a commit, or None where it is absent.""" + return gh(f"repos/{slug}/contents/{path}?ref={ref}", ok404=True) -def baseline_file_findings(slug, ground, path, alternatives, item, ref=None): - """Read one baseline file, returning `(found, content, text, findings)` for what reading it alone owes. +def baseline_file_findings(slug, ground, path, item, ref=None): + """Read one baseline file, returning `(content, text, findings)` for what reading it alone owes. - `found` is the path it was read at, a declared alternative included. `text` is None where the - API returned no inline content, and an empty file is an empty string. It is read at `ref`, the - audited head commit, where one is given, and a finding still names the `ground` branch. + `text` is None where the API returned no inline content, and an empty file is an empty string. + It is read at `ref`, the audited head commit, where one is given, and a finding still names the + `ground` branch. """ - found, content = read_baseline_file(slug, ref or ground, path, alternatives) + content = read_baseline_file(slug, ref or ground, path) fid = item.get("fidelity") if item else "presence" if content is None: if fid == "interface": return ( - found, None, None, [("DRIFT", f"interface: {path} absent on {ground}, cannot verify its contract")], ) - named = " or ".join((path, *alternatives)) return ( - found, None, None, - [ - ( - "LETTER", - f"file: {named} absent on {ground} (verify intent per AUDIT.md section 7)", - ) - ], + [("LETTER", f"file: {path} absent on {ground} (verify intent per AUDIT.md section 7)")], ) - return found, content, contents_text(content), [] + return content, contents_text(content), [] -def intent_trail(slug, ref, path, item, down_text, found): +def intent_trail(slug, ref, path, item, down_text): """`(canonical, (repo_date, hub_date, hub_sha))` where a copy possibly trails its intent canonical, else None. A last-modified comparison, since intent has no content check. A copy content-identical to the canonical, or to the hub's own file at `path` where the unit names no `reference`, is current. - `found` is the path the copy was read at, a declared alternative included. `ref` is the branch - or commit its last change is looked up from. + `ref` is the branch or commit its last change is looked up from. """ canonical_rel, anchor = intent_ref(item, path) hub_change = hub_last_change(canonical_rel, anchor) @@ -1766,7 +1753,7 @@ def intent_trail(slug, ref, path, item, down_text, found): canon_text = canonical_current_text(rel) if rel else None if canon_text is not None and content_hash(down_text) == content_hash(canon_text): return None - commits = gh(f"repos/{slug}/commits?path={found}&sha={ref}&per_page=1") + commits = gh(f"repos/{slug}/commits?path={path}&sha={ref}&per_page=1") if not commits: return None repo_date = commits[0]["commit"]["committer"]["date"] @@ -1781,7 +1768,7 @@ def intent_trail(slug, ref, path, item, down_text, found): def intent_findings(entry, ground, trails): - """The intent advisory over `trails`, `{found path: (canonical, (repo_date, hub_date, hub_sha))}`. + """The intent advisory over `trails`, `{path: (canonical, (repo_date, hub_date, hub_sha))}`. A driftNote naming (files.intent) acknowledges a copy verified against the canonical change the advisory cites, as `` `@` ``. It clears that copy until the canonical changes again. @@ -1894,7 +1881,6 @@ class Run: head: Any = None findings: list = field(default_factory=list) content: dict = field(default_factory=dict) - found: dict = field(default_factory=dict) @functools.cached_property def hub(self): @@ -1928,7 +1914,7 @@ def baseline(self): path = item["path"] if not applies(item.get("appliesTo", "*"), self.sel): continue - if path == "codecov.yml" and not self.coverage_types: + if path == ".codecov.yml" and not self.coverage_types: continue prior, needed, verbatim = out.get(path, (None, set(), set())) needed |= set(required_sections(item, self.sel)) @@ -1937,10 +1923,6 @@ def baseline(self): out[path] = (item if fidelity else prior, needed, verbatim) return out - @functools.cached_property - def alternatives(self): - return declared_alternatives(self.spec["files"]["baseline"]) - @property def docs(self): """README.md and HISTORY.md as read, for the checks that compare them.""" @@ -2191,17 +2173,11 @@ def check_dependabot_ecosystems(run): def check_files_presence(run, path): - found, content, text, findings = baseline_file_findings( - run.slug, - run.ground, - path, - run.alternatives.get(path, []), - run.baseline[path][0], - run.ref, + content, text, findings = baseline_file_findings( + run.slug, run.ground, path, run.baseline[path][0], run.ref ) if content is not None: run.content[path] = text - run.found[path] = found return findings @@ -2210,10 +2186,9 @@ def check_files_intent(run): for path, (item, _, _) in run.baseline.items(): if path not in run.content or (item or {}).get("fidelity") != "intent": continue - found = run.found[path] - trail = intent_trail(run.slug, run.ref, path, item, run.content[path], found) + trail = intent_trail(run.slug, run.ref, path, item, run.content[path]) if trail is not None: - trails[found] = trail + trails[path] = trail return intent_findings(run.entry, run.ground, trails) diff --git a/spec/checks.json b/spec/checks.json index fbc3bd647..2e4e96781 100644 --- a/spec/checks.json +++ b/spec/checks.json @@ -12,7 +12,7 @@ { "id": "secrets.stems", "family": "secrets", "description": "Each tracked env and secret file name takes the form the env and secret file rule sets.", "spec": "CODESTYLE.md", "hub": true, "scope": "repo" }, { "id": "secrets.names", "family": "secrets", "description": "The secret names each store holds against those the applicable mechanisms require and forbid.", "spec": "spec/secrets.json", "hub": true, "scope": "repo" }, { "id": "dependabot.ecosystems", "family": "dependabot", "description": "dependabot.yml declares each ecosystem the tree implies.", "spec": "AUDIT.md", "hub": true, "scope": "repo" }, - { "id": "files.presence", "family": "files", "description": "Each baseline file, or a declared alternative, is present.", "spec": "spec/files.json", "hub": true, "scope": "baseline" }, + { "id": "files.presence", "family": "files", "description": "Each baseline file is present.", "spec": "spec/files.json", "hub": true, "scope": "baseline" }, { "id": "interface.contract", "family": "interface", "description": "An interface workflow keeps its contract's job keys, check name, and tokens.", "spec": "spec/files.json", "hub": true, "scope": "file" }, { "id": "interface.python-directories", "family": "interface", "description": "A caller's python-directories input matches the registry's pythonDirectories.", "spec": "registry/repos.json", "hub": true, "scope": "file" }, { "id": "interface.workflow-model", "family": "interface", "description": "The pull request caller's workflow-model input matches the registry's workflowModel.", "spec": "registry/repos.json", "hub": true, "scope": "file" }, diff --git a/spec/fidelity-model.md b/spec/fidelity-model.md index 70ca1004a..eb1a679a8 100644 --- a/spec/fidelity-model.md +++ b/spec/fidelity-model.md @@ -17,8 +17,6 @@ Each [`spec/files.json`][files] entry declares one `fidelity`, defaulting to `pr A declaration in `trees[]` uses **verbatim-tree**. Each included source file exists at the corresponding target path with identical bytes. A pruned target contains no extra path. The tree root exists even when the included source inventory is empty. Tree target roots never overlap because two declarations cannot own the same path safely, regardless of whether either declaration prunes extras. -A whole-file `presence` or `intent` entry may also declare `alternatives`, other paths its tool accepts the file at. The `codecov.yml` entry names `.codecov.yml` this way. The audit reads the declared path first and an alternative only while nothing is found. The file is absent only where no path holds it. `spec/validate.py` refuses `alternatives` on any other entry, on a path a second entry also names, and where an alternative is itself a declared path. - Fidelity is a declared field defaulting to `presence`, never inferred from `whole`/`placeholders`. `.editorconfig` and `.markdownlint-cli2.jsonc` are both whole with no placeholders yet sit at opposite fidelity, because the discriminator is governance, not field shape. ## Why Each Unit Sits Where It Does diff --git a/spec/fidelity_honesty.py b/spec/fidelity_honesty.py index 84869055f..2a3bcdc07 100755 --- a/spec/fidelity_honesty.py +++ b/spec/fidelity_honesty.py @@ -36,18 +36,16 @@ SECTION_SEP = " > " # joins a file path and a verbatim section name into one unit label (path > section), ASCII -def fetch(slug, path, ref, alternatives=()): - """Decoded downstream file content at path or its first alternative present, or None if absent / not inline.""" - _, content = audit.read_baseline_file(slug, ref, path, alternatives) - return audit.contents_text(content) +def fetch(slug, path, ref): + """Decoded downstream file content at path, or None if absent / not inline.""" + return audit.contents_text(audit.read_baseline_file(slug, ref, path)) def check_units(spec): """Yield the fleet's check units - whole intent/verbatim files, plus each verbatim section of any file. Each is (label, fidelity, entry_appliesTo, section_appliesTo, downstream_path, canonical_path, extract). - downstream_path is the entry's `path`. The repo's copy lives there unless it sits at one of the entry's - `alternatives`, which fetch reads in order where `path` is absent. canonical_path is the hub's + downstream_path is the entry's `path`, where the repo's copy lives. canonical_path is the hub's canonical (the `reference` snippet for a reference-backed unit, else the same path). extract is None for a whole file, or a section extractor for a verbatim section (the region is compared, not the whole file). """ @@ -92,7 +90,6 @@ def fidelity_pass(spec): spreads = [] # (unit dict, spread dict) for the full table promote = [] # intent units that are uniform fleet-wide mislabel = [] # verbatim units that diverge non-stale - alternatives = audit.declared_alternatives(spec["files"]["baseline"]) for label, fid, ent_ap, sec_ap, down_path, canon_path, extract in check_units(spec): unit = {"path": label, "fidelity": fid} @@ -122,7 +119,6 @@ def fidelity_pass(spec): audit.repo_slug(r), down_path, audit.ground_branch_of(r, defaults=defaults), - alternatives.get(down_path, []), ) if ( text is None diff --git a/spec/fidelity_text.py b/spec/fidelity_text.py index 5c7c37383..ceda88981 100644 --- a/spec/fidelity_text.py +++ b/spec/fidelity_text.py @@ -61,11 +61,12 @@ class CodeBlock(NamedTuple): class LinkDefinition(NamedTuple): - """A reference definition: its label and destination as written, and its zero-based line.""" + """A reference definition: its label and destination as written, its zero-based line, and the line after its last.""" label: str url: str line: int + end: int def normalize(text): @@ -151,7 +152,7 @@ def link_definitions(text): start, end = t.map m = _DESTINATION.search("\n".join(lines[start:end])) url = m.group(2) if m.group(1) is None else m.group(1) - found.append(LinkDefinition(t.meta["label"], url, start)) + found.append(LinkDefinition(t.meta["label"], url, start, end)) return found diff --git a/spec/files.json b/spec/files.json index ed58115f4..b0bfb46d8 100644 --- a/spec/files.json +++ b/spec/files.json @@ -35,7 +35,7 @@ { "path": ".github/workflows/deploy-site.yml", "fidelity": "interface", "contract": { "requiredJobKeys": ["assert-ref", "validate", "deploy"], "requireTokensInJob": { "deploy": ["deploy-site-task.yml", "with:\n environment:", "contents: read", "DEPLOY_SSH_PRIVATE_KEY"] }, "forbidTokensInJob": { "deploy": ["\n environment:"] } }, "intentRef": "docs/reusable-workflows.md#adopting-the-type-specific-tasks", "appliesTo": ["hugo"] }, { "path": ".vscode/tasks.json", "sections": ["clean-compile task group"], "reference": "catalog/snippets/configs/vscode-tasks.json", "appliesTo": ["csharp"] }, { "path": ".vscode/tasks.json", "sections": ["clean-compile task group"], "reference": "catalog/snippets/configs/vscode-tasks-python.json", "appliesTo": ["python"] }, - { "path": "codecov.yml", "alternatives": [".codecov.yml"], "fidelity": "intent", "reference": "catalog/snippets/configs/codecov.yml", "intentRef": "WORKFLOW.md", "appliesTo": ["csharp", "python"] }, + { "path": ".codecov.yml", "fidelity": "intent", "reference": "catalog/snippets/configs/.codecov.yml", "intentRef": "WORKFLOW.md", "appliesTo": ["csharp", "python"] }, { "path": ".dockerignore", "appliesTo": ["docker"] }, { "path": "Docker/README.md", "reference": "catalog/snippets/configs/docker-hub-readme.md", "appliesTo": ["docker"] } ] diff --git a/spec/files.schema.json b/spec/files.schema.json index 34142d733..e28179c44 100644 --- a/spec/files.schema.json +++ b/spec/files.schema.json @@ -45,7 +45,6 @@ "additionalProperties": false, "properties": { "path": { "type": "string" }, - "alternatives": { "type": "array", "items": { "type": "string", "minLength": 1 }, "minItems": 1, "uniqueItems": true }, "whole": { "type": "boolean" }, "sections": { "type": "array", diff --git a/spec/project-types.json b/spec/project-types.json index 4d62fa3e8..d73153064 100644 --- a/spec/project-types.json +++ b/spec/project-types.json @@ -41,7 +41,7 @@ { "id": "python.pyright.config", "verdict": "intent", "assert": "Build profile: first-party code (src or the integration package) is type-checked in CI by pyright strict, by mypy, or by both. Each CI checker runs strict (pyright strict mode, mypy's strict flags), the strong typing baseline. Third-party strictness is relaxed only where a dependency has no usable types. N/A for the lint-only profile, whose type checker is mypy over stdlib-only code (python.mypy.allowed).", "intentRef": "CODESTYLE.md", "minProfile": "build" }, { "id": "python.config.placement", "verdict": "letter", "assert": "ruff and the type-checker config live in pyproject.toml (canonical); standalone .ruff.toml / pyrightconfig.json / mypy.ini / .mypy.ini, or a setup.cfg [mypy] section, is a drift finding. A Home Assistant integration is the exception - it follows home-assistant/core standalone-config conventions and is scored by ha.python.conventions instead.", "intentRef": "CODESTYLE.md" }, { "id": "python.mypy.allowed", "verdict": "intent", "assert": "mypy is permitted as an additional type checker or as the only one, not banned. It is required for a Home Assistant integration (platinum strict-typing), is the lint-only profile's type checker, and may be a build directory's only CI checker. When used it runs in CI and the editor.", "intentRef": "CODESTYLE.md" }, - { "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 (or .codecov.yml) file-presence is still required by any co-present type that has tests, e.g. csharp.", "intentRef": "WORKFLOW.md" }, + { "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.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/spec/secret_names.py b/spec/secret_names.py index 9afb4152c..ab6c5cb4c 100644 --- a/spec/secret_names.py +++ b/spec/secret_names.py @@ -97,7 +97,7 @@ def coverage_candidate_types(types: list[str], repo_profiles: Any) -> list[str]: def coverage_claiming_types( types: list[str], type_mechanisms: dict[str, Any], tree: set[str] | None ) -> list[str]: - """The declared types that owe Codecov coverage, meaning the CODECOV_TOKEN secret and codecov.yml. + """The declared types that owe Codecov coverage, meaning the CODECOV_TOKEN secret and .codecov.yml. `tree` is the blob path set, or None when unread, and then every candidate keeps its claim. """ @@ -122,7 +122,7 @@ def coverage_types( ) -> list[str]: """The declared types of ENTRY that owe Codecov coverage, the one composition the audit and provisioning share. - So the audit's codecov.yml check and the CODECOV_TOKEN it owes cannot disagree. + So the audit's .codecov.yml check and the CODECOV_TOKEN it owes cannot disagree. """ candidates = coverage_candidate_types(declared_types(entry), entry.get("profiles", {})) return coverage_claiming_types(candidates, secrets.get("typeMechanisms", {}), tree) diff --git a/spec/type-model.md b/spec/type-model.md index 52692984d..8689b8ba0 100644 --- a/spec/type-model.md +++ b/spec/type-model.md @@ -36,13 +36,13 @@ A language type is present at one of two **depths**, declared as its `profile`: Python's profile belongs to each declared Python directory rather than to the repository, per [CODESTYLE.md][codestyle] "Python", so one repository may hold both depths. The registry therefore declares no `python` profile. The registry's `pythonDirectories` lists the directories, and each one's `pyproject.toml` shape states its profile. -Each check may declare the **minimum profile** it needs via a `minProfile` field. A check without one applies at every profile. A check with `minProfile: build` applies only at `build`. So lint/style/type-check checks omit it, while build and package checks set `build`. A coverage check for a language other than Python sets it too. The coverage requirement (the CODECOV_TOKEN secret and the codecov.yml file, or its .codecov.yml alternative) is N/A for a lint-only language other than Python. Otherwise it follows tests: the audit reads the repo's tree for tests and holds the requirement N/A where it finds none. +Each check may declare the **minimum profile** it needs via a `minProfile` field. A check without one applies at every profile. A check with `minProfile: build` applies only at `build`. So lint/style/type-check checks omit it, while build and package checks set `build`. A coverage check for a language other than Python sets it too. The coverage requirement (the CODECOV_TOKEN secret and the .codecov.yml file) is N/A for a lint-only language other than Python. Otherwise it follows tests: the audit reads the repo's tree for tests and holds the requirement N/A where it finds none. A registry profile is **declared and validated**, not merely detected. Python is the exception, because its structural read of each directory's `pyproject.toml` already is the profile. A repository-wide value could not describe a repository holding both depths. It would also be a second classification of a shape that already states one. So [validate.py][validate] refuses a `python` entry in `profiles`. ### Consequence for cross-cutting checks -A cross-cutting check that presumes a built, tested language must respect the profile. In particular the coverage checks (the `CODECOV_TOKEN` secret and the `codecov.yml` or `.codecov.yml` file presence) are **tests-aware**. They are N/A for a lint-only language other than Python, and for any language the repo carries no tests for. A language with no tests here must never manufacture a coverage finding. That holds whether the language is lint-only or a package-only build language whose tests live elsewhere or are not yet written. +A cross-cutting check that presumes a built, tested language must respect the profile. In particular the coverage checks (the `CODECOV_TOKEN` secret and the `.codecov.yml` file presence) are **tests-aware**. They are N/A for a lint-only language other than Python, and for any language the repo carries no tests for. A language with no tests here must never manufacture a coverage finding. That holds whether the language is lint-only or a package-only build language whose tests live elsewhere or are not yet written. ## Languages diff --git a/spec/validate.py b/spec/validate.py index bc16f99d9..e3fb6bd9a 100755 --- a/spec/validate.py +++ b/spec/validate.py @@ -300,40 +300,6 @@ def escapes_repo_root(value): ) -def alternatives_errors(baseline): - """The errors in each baseline entry's `alternatives`, the other paths its file may sit at instead. - - Only a whole-file presence or intent entry may declare them, as the one entry naming its path. - No alternative may be a declared path. CI runs no schema validation, so the list's shape is - checked here as files.schema.json states it. - """ - entries = [i for i in baseline if isinstance(i, dict) and isinstance(i.get("path"), str)] - declared = {i["path"] for i in entries} - errors = [] - for item in entries: - if "alternatives" not in item: - continue - alts = item["alternatives"] - path = item["path"] - if not (is_str_list(alts) and alts and all(alts) and len(set(alts)) == len(alts)): - errors.append( - f"files.json: {path} alternatives must be a non-empty array of distinct, non-empty strings" - ) - elif declared.intersection(alts): - errors.append( - f"files.json: {path} alternative(s) {', '.join(sorted(declared.intersection(alts)))} already declared as a baseline path" - ) - if item.get("fidelity", "presence") not in ("presence", "intent") or "sections" in item: - errors.append( - f"files.json: {path} declares alternatives, which only a whole-file presence or intent unit may carry" - ) - if sum(1 for other in entries if other["path"] == path) > 1: - errors.append( - f"files.json: {path} declares alternatives, so no other baseline entry may name it" - ) - return errors - - def reduces_to_repo_root(value): """Whether `value` reduces to the repository root under POSIX path rules. @@ -1861,7 +1827,6 @@ def check_selector(where, applies_to): errors.append( f"files.json: Copilot instructions reference skill path {path} outside every carried tree include" ) - errors.extend(alternatives_errors(baseline)) for item in baseline: if not isinstance(item, dict): errors.append(f"files.json: baseline entry {item!r} is not an object") diff --git a/tests/test_audit.py b/tests/test_audit.py index fd158035d..2d04cc81c 100755 --- a/tests/test_audit.py +++ b/tests/test_audit.py @@ -25,8 +25,7 @@ HEAD_SHA = "c0ffee" HEAD = {"commit": {"sha": HEAD_SHA, "commit": {"tree": {"sha": "feed"}}}} CODECOV = { - "path": "codecov.yml", - "alternatives": [".codecov.yml"], + "path": ".codecov.yml", "appliesTo": ["python"], } @@ -93,7 +92,7 @@ def run_audit( texts: dict[str, str] | None = None, moved: frozenset[str] = frozenset(), ) -> tuple[list[tuple[str, str]], FakeGh]: - """Audit a Python repository carrying `tree`, where a test module makes codecov.yml owed. + """Audit a Python repository carrying `tree`, where a test module makes .codecov.yml owed. The hub's tracked paths come from a fetch of its origin. Answering them with `hub` keeps the run offline and leaves the checkout the suite runs in untouched. The repo-owned trees and the @@ -118,35 +117,23 @@ def run_audit( return findings, fake -class AuditRepoAlternativesCase(unittest.TestCase): - """audit_repo's baseline loop passes each path's declared alternatives into the shared reader. +class AuditRepoCodecovNameCase(unittest.TestCase): + """audit_repo reads the Codecov configuration at `.codecov.yml`, the one name the fleet accepts.""" - The reader's own handling of alternatives is covered by tests/test_audit_helpers.py, so what this - adds is the call site. Were it to stop passing them, a repository holding only an alternative - would read as missing the declared path while that self-test still passed. - """ + ABSENT = ("LETTER", "file: .codecov.yml absent on main (verify intent per AUDIT.md section 7)") - def test_a_repository_holding_only_the_alternative_carries_the_file(self) -> None: + def test_a_repository_holding_the_dotfile_carries_the_file(self) -> None: findings, fake = run_audit(CARRIED | {".codecov.yml"}) self.assertIn(f"repos/{SLUG}/contents/.codecov.yml?ref={HEAD_SHA}", fake.paths) - absent = [text for _, text in findings if text.startswith("file: codecov.yml")] - self.assertEqual(absent, []) + self.assertNotIn(self.ABSENT, findings) - def test_a_repository_holding_neither_is_reported_under_both_names(self) -> None: - """The control, showing the loop under test ran and reports an absence it sees.""" - findings, _ = run_audit(CARRIED) + def test_a_repository_holding_only_the_bare_name_is_reported(self) -> None: + """Codecov would read the bare name, but the fleet accepts only the dotfile.""" + findings, fake = run_audit(CARRIED | {"codecov.yml"}) - self.assertIn( - ( - "LETTER", - ( - "file: codecov.yml or .codecov.yml absent on main " - "(verify intent per AUDIT.md section 7)" - ), - ), - findings, - ) + self.assertIn(self.ABSENT, findings) + self.assertFalse([p for p in fake.paths if "/contents/codecov.yml" in p]) class AuditRepoNamingCase(unittest.TestCase): @@ -259,7 +246,9 @@ def test_a_path_deleted_after_the_tree_was_listed_is_still_judged(self) -> None: any("bin/Run_Backup (an executable with no shebang)" in text for _, text in findings), findings, ) - self.assertEqual([text for _, text in findings if text.startswith("file: codecov.yml")], []) + self.assertEqual( + [text for _, text in findings if text.startswith("file: .codecov.yml")], [] + ) def test_every_content_read_names_the_head_commit(self) -> None: _, fake = run_audit(CARRIED | {".codecov.yml", "cspell.json", ".github/dependabot.yml"}) diff --git a/tests/test_audit_helpers.py b/tests/test_audit_helpers.py index e9fa8dd4f..c562bb088 100755 --- a/tests/test_audit_helpers.py +++ b/tests/test_audit_helpers.py @@ -721,6 +721,21 @@ def test_an_every_event_expression_on_a_dispatch_workflow_is_its_job_finding(sel self.assertIn("job 'check-workflow-status'", message) self.assertIn("on a run other than pull_request", message) + def test_a_gate_without_a_pull_request_trigger_gets_the_trigger_finding(self) -> None: + on = "on:\n push:\n branches: ['**']\n workflow_dispatch:\n" + for label, check, others in ( + ("literal name", PR_CHECK, ["on a run other than pull_request"]), + ("pull_request-only name", PR_CHECK.replace(PR_CHECK_NAME, PR_ONLY_EXPRESSION), []), + ): + with self.subTest(label): + text = PR_HEAD.replace("on: pull_request\n", on) + check + trigger, *rest = audit.check_interface("wf", PR_CONTRACT, text) + self.assertEqual(trigger[0], "DRIFT") + self.assertIn("has no pull_request trigger", trigger[1]) + self.assertEqual(len(rest), len(others)) + for (_, message), want in zip(rest, others, strict=True): + self.assertIn(want, message) + class ShippedPullRequestStubCase(unittest.TestCase): """Every pull request stub the hub ships passes the contract spec/files.json gives a carried one.""" @@ -2676,13 +2691,7 @@ def fake(path: str, ok404: bool = False) -> Any: return fake -ALT_CASES = [ - (("codecov.yml",), ("codecov.yml", "codecov.yml"), "only the declared path"), - ((".codecov.yml",), (".codecov.yml", ".codecov.yml"), "only the alternative"), - (("codecov.yml", ".codecov.yml"), ("codecov.yml", "codecov.yml"), "both, declared wins"), - ((), ("codecov.yml", None), "neither"), -] -BASELINE_UNIT = {"path": "codecov.yml", "fidelity": "intent", "intentRef": "WORKFLOW.md"} +BASELINE_UNIT = {"path": ".codecov.yml", "fidelity": "intent", "intentRef": "WORKFLOW.md"} class DriftnoteCase(unittest.TestCase): @@ -2932,42 +2941,38 @@ def test_repo_tree_returns_none_unless_whole(self) -> None: f"repo_tree -> truncated={truncated}, whole={whole}", ) - def test_read_baseline_file_alternatives(self) -> None: - for held, (want_path, want_name), label in ALT_CASES: + def test_read_baseline_file(self) -> None: + for held, want, label in ( + ((".codecov.yml",), ".codecov.yml", "the declared path"), + (("codecov.yml",), None, "only another name Codecov reads"), + ((), None, "neither"), + ): with self.subTest(label): with mock.patch.object(audit, "gh", holding(*held)): - got_path, got = audit.read_baseline_file( - "o/r", "main", "codecov.yml", [".codecov.yml"] - ) - got_name = got["name"] if got is not None else None - self.assertEqual( - (got_path, got_name), - (want_path, want_name), - f"read_baseline_file, {label} -> {got_path}, {got_name}", - ) + got = audit.read_baseline_file("o/r", "main", ".codecov.yml") + self.assertEqual(got["name"] if got is not None else None, want, label) - def test_baseline_file_findings_only_the_alternative(self) -> None: + def test_baseline_file_findings_present(self) -> None: with mock.patch.object(audit, "gh", holding(".codecov.yml")): - found, alt_content, _, alt_findings = audit.baseline_file_findings( - "o/r", "main", "codecov.yml", [".codecov.yml"], BASELINE_UNIT - ) - self.assertEqual(found, ".codecov.yml") - self.assertIsNotNone(alt_content) - self.assertEqual(alt_findings, []) - - def test_baseline_file_findings_neither(self) -> None: - with mock.patch.object(audit, "gh", holding()): - _, _, _, none_findings = audit.baseline_file_findings( - "o/r", "main", "codecov.yml", [".codecov.yml"], BASELINE_UNIT + content, text, findings = audit.baseline_file_findings( + "o/r", "main", ".codecov.yml", BASELINE_UNIT ) - want_none = [ - ( - "LETTER", - "file: codecov.yml or .codecov.yml absent on main (verify intent per AUDIT.md section 7)", + self.assertIsNotNone(content) + self.assertEqual((text, findings), ("x", [])) + + def test_baseline_file_findings_absent(self) -> None: + with mock.patch.object(audit, "gh", holding("codecov.yml")): + _, _, findings = audit.baseline_file_findings( + "o/r", "main", ".codecov.yml", BASELINE_UNIT ) - ] self.assertEqual( - none_findings, want_none, f"baseline_file_findings, neither -> {none_findings}" + findings, + [ + ( + "LETTER", + "file: .codecov.yml absent on main (verify intent per AUDIT.md section 7)", + ) + ], ) @@ -2981,7 +2986,6 @@ def intent_run(baseline: dict[str, Any], content: dict[str, str], notes: list[st run.head = {"commit": {"sha": "c0ffee"}} run.__dict__["baseline"] = {p: (item, set(), set()) for p, item in baseline.items()} run.content.update(content) - run.found.update({p: p for p in content}) return run @@ -3003,7 +3007,7 @@ def test_a_copy_matching_the_hub_file_at_path_is_current(self) -> None: trailing = ("DOC.md", ("2019-01-01T00:00:00+00:00", *HUB_CHANGE)) for down, want in (("same", None), ("x", trailing)): with self.subTest(down=down), self.patched(texts): - got = audit.intent_trail("o/r", "main", "widget.json", unit, down, "widget.json") + got = audit.intent_trail("o/r", "main", "widget.json", unit, down) self.assertEqual(got, want) def test_the_trail_dates_by_the_intent_ref_anchor(self) -> None: @@ -3018,30 +3022,19 @@ def change(rel: str, anchor: str | None = None) -> tuple[str, str]: self.patched({"DOC.md": "the doc"}), mock.patch.object(audit, "hub_last_change", change), ): - audit.intent_trail("o/r", "main", "widget.json", unit, "x", "widget.json") + audit.intent_trail("o/r", "main", "widget.json", unit, "x") self.assertEqual(asked, [("DOC.md", "widget")]) def test_a_reference_unit_ignores_the_hub_file_at_path(self) -> None: unit = {"path": "w.yml", "fidelity": "intent", "reference": "snip/w.yml"} with self.patched({"snip/w.yml": "snippet", "w.yml": "same"}): - self.assertIsNotNone(audit.intent_trail("o/r", "main", "w.yml", unit, "same", "w.yml")) + self.assertIsNotNone(audit.intent_trail("o/r", "main", "w.yml", unit, "same")) def test_a_copy_newer_than_the_canonical_is_current(self) -> None: unit = {"path": "w.json", "fidelity": "intent", "intentRef": "DOC.md"} newer = [{"commit": {"committer": {"date": "2021-01-01T00:00:00+00:00"}}}] with self.patched({"DOC.md": "canonical"}, newer): - self.assertIsNone(audit.intent_trail("o/r", "main", "w.json", unit, "x", "w.json")) - - def test_the_trail_reads_the_alternative_it_was_found_at(self) -> None: - asked: list[str] = [] - - def fake(ep: str, ok404: bool = False) -> Any: - asked.append(ep) - return OLD_COMMIT - - with self.patched({"WORKFLOW.md": "canonical"}), mock.patch.object(audit, "gh", fake): - audit.intent_trail("o/r", "main", "codecov.yml", BASELINE_UNIT, "x", ".codecov.yml") - self.assertEqual(asked, ["repos/o/r/commits?path=.codecov.yml&sha=main&per_page=1"]) + self.assertIsNone(audit.intent_trail("o/r", "main", "w.json", unit, "x")) def test_the_finding_names_the_intent_canonical(self) -> None: trails = {"w.json": ("DOC.md", ("2019-01-01T00:00:00+00:00", *HUB_CHANGE))} @@ -3084,7 +3077,7 @@ def test_check_files_intent_reads_only_intent_units_it_read(self) -> None: findings = audit.check_files_intent(run) self.assertEqual([t.split(" ", 2)[1] for _, t in findings], ["w.json"]) - def test_check_files_intent_keys_a_copy_by_the_alternative_it_was_read_at(self) -> None: + def test_check_files_intent_keys_a_copy_by_its_dotfile_path(self) -> None: asked: list[str] = [] def fake(ep: str, ok404: bool = False) -> Any: @@ -3095,8 +3088,7 @@ def fake(ep: str, ok404: bool = False) -> Any: ([], [".codecov.yml"]), (["`.codecov.yml@abc1234` (files.intent)"], []), ): - run = intent_run({"codecov.yml": BASELINE_UNIT}, {"codecov.yml": "x"}, notes) - run.found["codecov.yml"] = ".codecov.yml" + run = intent_run({".codecov.yml": BASELINE_UNIT}, {".codecov.yml": "x"}, notes) asked.clear() with ( self.subTest(notes=notes), @@ -3166,18 +3158,6 @@ def test_every_anchored_intent_ref_resolves_in_the_hub(self) -> None: self.assertIsNotNone(audit.extract_anchored(text, anchor)) -class AlternativesManifestCase(unittest.TestCase): - """declared_alternatives against the live manifest.""" - - def test_declared_alternatives_on_the_live_manifest(self) -> None: - live_alts = audit.declared_alternatives(audit.load("spec/files.json")["baseline"]) - self.assertEqual( - live_alts.get("codecov.yml"), - [".codecov.yml"], - f"declared_alternatives on the live manifest -> {live_alts}", - ) - - class CoverageTypesCase(unittest.TestCase): """Holds the coverage-candidate and coverage-claiming type helpers.""" @@ -5380,9 +5360,9 @@ def test_intent_ref_canonical(self) -> None: ), ( "reference wins over intentRef when the manifest sets both", - {"reference": "catalog/snippets/configs/codecov.yml", "intentRef": "WORKFLOW.md"}, - "codecov.yml", - "catalog/snippets/configs/codecov.yml", + {"reference": "catalog/snippets/configs/.codecov.yml", "intentRef": "WORKFLOW.md"}, + ".codecov.yml", + "catalog/snippets/configs/.codecov.yml", ), ( "a literal '#' in reference is preserved rather than treated as an anchor", diff --git a/tests/test_build_dist.py b/tests/test_build_dist.py index 2a439ce12..358bc555c 100755 --- a/tests/test_build_dist.py +++ b/tests/test_build_dist.py @@ -945,6 +945,35 @@ def test_a_level_one_heading_ends_a_body_and_cannot_be_a_key(self) -> None: with self.assertRaisesRegex(ValueError, "no heading 'Title'"): build_dist.regenerate() + def test_a_body_running_to_the_end_stops_before_the_trailing_definitions(self) -> None: + (self.tmp / "RULES.md").write_text( + "## A\n\nSee [b].\n\n## Last\n\nLast text.\n\n\n\n[b]: ./B.md\n\n" + "\n\n[c]: https://example.com/c\n 'C title'\n", + encoding="utf-8", + ) + self.make_skill("foo", self.region("RULES.md > Last")) + build_dist.regenerate() + self.assertEqual( + self.skill_text(), + "\n\nLast text.\n\n\n", + ) + + def test_a_line_the_parser_ends_a_definition_before_is_kept(self) -> None: + (self.tmp / "RULES.md").write_text( + "## Last\n\nLast text.\n\n[b]: ./B.md\nKeep the backups.\n", encoding="utf-8" + ) + self.make_skill("foo", self.region("RULES.md > Last")) + build_dist.regenerate() + self.assertIn("Keep the backups.", self.skill_text()) + + def test_a_body_with_no_trailing_definitions_keeps_its_last_comment(self) -> None: + (self.tmp / "RULES.md").write_text( + "## Last\n\nLast text.\n\n\n", encoding="utf-8" + ) + self.make_skill("foo", self.region("RULES.md > Last")) + build_dist.regenerate() + self.assertIn("Last text.\n\n\n\n", self.skill_text()) + def test_an_indented_heading_splits_as_it_does_for_the_audit(self) -> None: """spec/audit.py and canonical_review.py split where the shared reader does, so the generator does too. diff --git a/tests/test_configure_archived.py b/tests/test_configure_archived.py index 6d0110f4a..26e3b2712 100755 --- a/tests/test_configure_archived.py +++ b/tests/test_configure_archived.py @@ -1,12 +1,13 @@ #!/usr/bin/env python3 -"""Exercise repo-config/configure.sh's archived-repository exemption by running its own lines. +"""Exercise repo-config/configure.sh's registry region by running its own lines. The shell is lifted out of the file rather than restated here. An edit that removes the behavior therefore fails these tests instead of leaving a reimplementation to agree with itself. The region under test makes no `gh` call of its own, and the harness assigns every variable the region reads. So the cases running the lifted region need no `gh` stub. -A cataloged or absent registry falls through to a marker printed just after that region. -An archived one exits before reaching it. +Under check, a cataloged or unlisted entry and an absent registry fall through to a marker printed just after that region. +Under apply, only a listed one does, and an unlisted entry or an absent registry fails the run. +An archived entry exits before reaching the marker. """ from __future__ import annotations @@ -63,11 +64,13 @@ def run_bash(script: str, *tools: str) -> subprocess.CompletedProcess[str]: ) -ARCHIVED_EXEMPTION = lift(r'(if \[ -f "\$registry" \]; then\n if ! archived_status=.*?\n^fi\n)') +REGISTRY_REGION = lift(r"^(jqr\(\) \{.*?\}\n)") + lift( + r'(if \[ -f "\$registry" \]; then\n if ! archived_status=.*?\n^fi\n)' +) -class ArchivedRepositoryCase(unittest.TestCase): - """A repository the registry marks archived is out of scope, for apply and check alike.""" +class RegistryRegionCase(unittest.TestCase): + """The helpers that run the lifted registry region against a constructed registry.""" def registry(self, tmp: str, entries: list[dict[str, object]]) -> Path: path = Path(tmp) / "repos.json" @@ -78,10 +81,14 @@ def harness(self, registry: Path, name: str, cmd: str) -> subprocess.CompletedPr script = ( f"registry={shlex.quote(str(registry))}\nname={shlex.quote(name)}\n" f"cmd={shlex.quote(cmd)}\nrepo={shlex.quote('owner/' + name)}\n" - f"{ARCHIVED_EXEMPTION}echo REACHED_NEXT\n" + f"{REGISTRY_REGION}echo REACHED_NEXT\n" ) return run_bash(script, "jq") + +class ArchivedRepositoryCase(RegistryRegionCase): + """A repository the registry marks archived is out of scope, for apply and check alike.""" + def test_an_archived_entry_exits_before_the_next_line(self) -> None: for cmd in ("check", "apply"): with self.subTest(cmd=cmd), tempfile.TemporaryDirectory() as tmp: @@ -136,7 +143,7 @@ def test_a_trailing_carriage_return_from_jq_is_stripped(self) -> None: script = ( f'PATH="$(cd {shlex.quote(str(bin_dir))} && pwd):$PATH"\n' f"registry={shlex.quote(str(registry))}\nname=Fixture\ncmd=check\nrepo=owner/Fixture\n" - f"{ARCHIVED_EXEMPTION}echo REACHED_NEXT\n" + f"{REGISTRY_REGION}echo REACHED_NEXT\n" ) result = run_bash(script) self.assertEqual(result.returncode, 0, result.stderr) @@ -144,13 +151,63 @@ def test_a_trailing_carriage_return_from_jq_is_stripped(self) -> None: self.assertNotIn("REACHED_NEXT", result.stdout) +class UnregisteredApplyCase(RegistryRegionCase): + """An apply for a repository the registry does not list fails before any write, and check does not.""" + + def test_an_unlisted_name_fails_apply(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + registry = self.registry(tmp, [{"name": "Other", "status": "cataloged"}]) + result = self.harness(registry, "Fixture", "apply") + self.assertEqual(result.returncode, 1, result.stderr) + self.assertIn("owner/Fixture has no entry in", result.stderr) + self.assertIn("develop only", result.stderr) + self.assertNotIn("REACHED_NEXT", result.stdout) + + def test_no_registry_file_fails_apply(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + missing = Path(tmp) / "does-not-exist.json" + result = self.harness(missing, "Fixture", "apply") + self.assertEqual(result.returncode, 1, result.stderr) + self.assertIn("not found, so apply makes no write", result.stderr) + self.assertNotIn("REACHED_NEXT", result.stdout) + + def test_a_listed_name_falls_through_apply_whatever_its_letter_case(self) -> None: + for listed in ("Fixture", "fixture"): + with self.subTest(listed=listed), tempfile.TemporaryDirectory() as tmp: + registry = self.registry(tmp, [{"name": listed, "status": "cataloged"}]) + result = self.harness(registry, "Fixture", "apply") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout, "REACHED_NEXT\n") + + def test_a_trailing_carriage_return_on_the_entry_count_is_stripped(self) -> None: + """A count read as `0\\r` would not equal 0, so an unlisted apply would fall through.""" + with tempfile.TemporaryDirectory() as tmp: + bin_dir = Path(tmp) / "bin" + bin_dir.mkdir() + stub = bin_dir / "jq" + stub.write_text("#!/bin/sh\nprintf '0\\r\\n'\n", encoding="utf-8") + stub.chmod(0o755) + registry = self.registry(tmp, [{"name": "Other", "status": "cataloged"}]) + script = ( + f'PATH="$(cd {shlex.quote(str(bin_dir))} && pwd):$PATH"\n' + f"registry={shlex.quote(str(registry))}\nname=Fixture\ncmd=apply\nrepo=owner/Fixture\n" + f"{REGISTRY_REGION}echo REACHED_NEXT\n" + ) + result = run_bash(script) + self.assertEqual(result.returncode, 1, result.stderr) + self.assertIn("owner/Fixture has no entry in", result.stderr) + self.assertNotIn("REACHED_NEXT", result.stdout) + + class EndToEndCase(unittest.TestCase): - """Run on an archived repository given by name, the real script exits before any `gh` call. + """Run the real script, copied whole, with a `gh` stub that records every call. - The script is copied whole, and both apply and check are covered. + An archived target and an unregistered apply each exit before any `gh` call. """ - def run_configure(self, status: str, cmd: str) -> subprocess.CompletedProcess[str]: + def run_configure( + self, entries: list[dict[str, object]], args: list[str] + ) -> tuple[subprocess.CompletedProcess[str], str]: bash = require("bash", "jq") with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) @@ -159,19 +216,19 @@ def run_configure(self, status: str, cmd: str) -> subprocess.CompletedProcess[st (root / "bin").mkdir() shutil.copy(CONFIGURE, root / "repo-config" / "configure.sh") (root / "registry" / "repos.json").write_text( - json.dumps({"repos": [{"name": "Fixture", "status": status}]}), encoding="utf-8" + json.dumps({"repos": entries}), encoding="utf-8" ) + calls = root / "gh-calls.txt" gh_stub = root / "bin" / "gh" gh_stub.write_text( - "#!/bin/sh\necho 'gh should never run for an archived repo' >&2\nexit 1\n", - encoding="utf-8", + f'#!/bin/sh\necho "$*" >> {shlex.quote(str(calls))}\nexit 1\n', encoding="utf-8" ) gh_stub.chmod(0o755) env = dict( os.environ, PATH=f"{root / 'bin'}{os.pathsep}{os.environ.get('PATH', os.defpath)}" ) - return subprocess.run( - [bash, str(root / "repo-config" / "configure.sh"), cmd, "owner/Fixture"], + result = subprocess.run( + [bash, str(root / "repo-config" / "configure.sh"), *args], capture_output=True, text=True, encoding="utf-8", @@ -179,13 +236,27 @@ def run_configure(self, status: str, cmd: str) -> subprocess.CompletedProcess[st check=False, env=env, ) + return result, calls.read_text(encoding="utf-8") if calls.exists() else "" def test_an_archived_target_never_calls_gh(self) -> None: for cmd in ("check", "apply"): with self.subTest(cmd=cmd): - result = self.run_configure("archived", cmd) + result, calls = self.run_configure( + [{"name": "Fixture", "status": "archived"}], [cmd, "owner/Fixture"] + ) self.assertEqual(result.returncode, 0, result.stderr) - self.assertNotIn("gh should never run", result.stderr) + self.assertEqual(calls, "") + + def test_an_unregistered_apply_with_a_checkout_writes_nothing(self) -> None: + with tempfile.TemporaryDirectory() as checkout: + result, calls = self.run_configure( + [{"name": "Other", "status": "cataloged"}], + ["apply", "owner/Fixture", "release", "--checkout", checkout], + ) + self.assertEqual(result.returncode, 1, result.stdout + result.stderr) + self.assertIn("owner/Fixture has no entry in", result.stderr) + self.assertEqual(calls, "") + self.assertEqual(list(Path(checkout).iterdir()), []) if __name__ == "__main__": diff --git a/tests/test_docker_lint.py b/tests/test_docker_lint.py index 884ebfc51..15e2746db 100755 --- a/tests/test_docker_lint.py +++ b/tests/test_docker_lint.py @@ -3,6 +3,7 @@ from __future__ import annotations +import ast import contextlib import io import os @@ -18,8 +19,11 @@ from host_capability import requires_symlink -sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts")) +REPO = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(REPO / "scripts")) +sys.path.insert(0, str(REPO / "spec")) import docker_lint +import git_env MOUNT_SOURCE = re.compile(r'^type=bind,"src=(.*)",dst=') @@ -73,6 +77,7 @@ class DockerLintCase(unittest.TestCase): """Build a small tracked tree for each runner scenario.""" def setUp(self) -> None: + self.enterContext(git_env.git_location_cleared()) self.root = Path(self.enterContext(tempfile.TemporaryDirectory())) subprocess.run(["git", "init", "-q", str(self.root)], check=True) # A separate temp dir, not self.root's own parent, which is the shared system temp root. @@ -583,5 +588,67 @@ def test_cleanup_start_failure_remains_a_timeout_result(self) -> None: docker_lint.run_command(command, 90) +class StandaloneTests(unittest.TestCase): + """The Lint tasks fetch the wrapper alone, so it runs with no hub file beside it.""" + + def setUp(self) -> None: + self.enterContext(git_env.git_location_cleared()) + self.root = Path(self.enterContext(tempfile.TemporaryDirectory())) + subprocess.run(["git", "init", "-q", str(self.root)], check=True) + self.outside = Path(self.enterContext(tempfile.TemporaryDirectory())) + + def test_the_wrapper_imports_only_the_standard_library(self) -> None: + tree = ast.parse((REPO / "scripts" / "docker_lint.py").read_text(encoding="utf-8")) + imported: set[str] = set() + for node in ast.walk(tree): + if isinstance(node, ast.Import): + imported.update(alias.name.split(".")[0] for alias in node.names) + elif isinstance(node, ast.ImportFrom): + imported.add("." if node.level else (node.module or "").split(".")[0]) + self.assertEqual(sorted(imported - sys.stdlib_module_names - {"__future__"}), []) + + def test_its_git_location_list_is_the_hub_s(self) -> None: + self.assertEqual(sorted(docker_lint.GIT_LOCATION_VARS), sorted(git_env.GIT_LOCATION_VARS)) + + def test_an_inherited_git_dir_does_not_move_the_snapshot(self) -> None: + """A git hook's GIT_DIR names the hook's repository, never the root this run lints.""" + other = Path(self.enterContext(tempfile.TemporaryDirectory())) + subprocess.run(["git", "init", "-q", str(other)], check=True) + with mock.patch.dict(os.environ, {"GIT_DIR": str(other / ".git")}): + parent = docker_lint.snapshot_parent(self.root) + self.assertEqual((self.root / ".git").resolve(), parent.resolve()) + + def test_an_inherited_git_dir_does_not_move_the_targets(self) -> None: + """The snapshot's file list comes from the root too, never from a hook's repository.""" + (self.root / "here.md").write_text("content\n", encoding="utf-8") + subprocess.run(["git", "-C", str(self.root), "add", "--", "here.md"], check=True) + other = Path(self.enterContext(tempfile.TemporaryDirectory())) + subprocess.run(["git", "init", "-q", str(other)], check=True) + (other / "there.md").write_text("content\n", encoding="utf-8") + subprocess.run(["git", "-C", str(other), "add", "--", "there.md"], check=True) + with mock.patch.dict(os.environ, {"GIT_DIR": str(other / ".git")}): + self.assertEqual(["here.md"], docker_lint.ls_files(self.root, include_untracked=False)) + + def test_its_rmtree_handler_is_local_review_s(self) -> None: + """Copied rather than imported, so the two bodies are held equal here instead.""" + + def body(name: str) -> str: + source = (REPO / "scripts" / f"{name}.py").read_text(encoding="utf-8") + for node in ast.parse(source).body: + if isinstance(node, ast.FunctionDef) and node.name == "unlink_read_only": + return ast.dump(ast.Module(body=node.body[1:], type_ignores=[])) + raise AssertionError(f"{name}.py has no unlink_read_only") + + self.assertEqual(body("local_review"), body("docker_lint")) + + def test_a_root_outside_any_repository_is_a_snapshot_failure(self) -> None: + ceiling = {"GIT_CEILING_DIRECTORIES": str(self.outside.parent)} + with ( + mock.patch.dict(os.environ, ceiling), + self.assertRaisesRegex(docker_lint.CommandFailed, "snapshot failed: git rev-parse"), + ): + docker_lint.snapshot_parent(self.outside) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_fidelity_honesty.py b/tests/test_fidelity_honesty.py index ae5c655af..781a51837 100755 --- a/tests/test_fidelity_honesty.py +++ b/tests/test_fidelity_honesty.py @@ -21,28 +21,23 @@ "status": "cataloged", "types": ["python"], } -CANONICAL = "catalog/snippets/configs/codecov.yml" +CANONICAL = "catalog/snippets/configs/.codecov.yml" CODECOV = { - "path": "codecov.yml", - "alternatives": [".codecov.yml"], + "path": ".codecov.yml", "fidelity": "intent", "reference": CANONICAL, "appliesTo": ["python"], } -class FidelityPassAlternativesCase(unittest.TestCase): - """fidelity_pass passes each unit's declared alternatives into the shared reader. - - The reader's own handling of alternatives is covered by tests/test_audit_helpers.py, so what - this adds is the call site. Were it to stop passing them, a repository holding only an - alternative would land in the unavailable bucket while that self-test still passed. +class FidelityPassReadCase(unittest.TestCase): + """fidelity_pass reads each repository's copy at the unit's declared path and nowhere else. The canonical's history is a git walk that refuses a shallow clone and fetches the hub's origin, so it is answered as empty. The copy then matches on the current canonical alone. """ - def test_a_copy_held_only_at_the_alternative_is_read_and_compared(self) -> None: + def test_a_copy_at_the_declared_path_is_read_and_compared(self) -> None: canonical = (audit.ROOT / CANONICAL).read_bytes() reads: list[str] = [] @@ -50,8 +45,6 @@ def fake_gh(path: str, ok404: bool = False) -> Any: reads.append(path) if path == f"repos/{SLUG}/contents/.codecov.yml?ref=main": return {"encoding": "base64", "content": base64.b64encode(canonical).decode()} - if path == f"repos/{SLUG}/contents/codecov.yml?ref=main" and ok404: - return None raise AssertionError(f"unexpected gh read: {path}") spec = { @@ -66,7 +59,8 @@ def fake_gh(path: str, ok404: bool = False) -> Any: self.assertIn(f"repos/{SLUG}/contents/.codecov.yml?ref=main", reads) [(unit, spread)] = spreads - self.assertEqual(unit["path"], "codecov.yml") + self.assertEqual(reads, [f"repos/{SLUG}/contents/.codecov.yml?ref=main"]) + self.assertEqual(unit["path"], ".codecov.yml") self.assertIsNotNone(spread) self.assertEqual(spread["match"], ["Fixture"]) self.assertEqual(spread["unavailable"], []) diff --git a/tests/test_fidelity_text.py b/tests/test_fidelity_text.py index e5eeab0fe..8b6324995 100755 --- a/tests/test_fidelity_text.py +++ b/tests/test_fidelity_text.py @@ -103,7 +103,7 @@ def test_the_first_of_definitions_folding_together_wins(self) -> None: ) self.assertEqual( fidelity_text.link_definitions(text), - [fidelity_text.LinkDefinition("docs", "https://example.com/a", 0)], + [fidelity_text.LinkDefinition("docs", "https://example.com/a", 0, 1)], ) self.assertEqual(fidelity_text.reference_key("Docs"), fidelity_text.reference_key("docs")) @@ -117,6 +117,13 @@ def test_a_definition_is_read_only_where_the_parser_reads_one(self) -> None: [("spaced", "a b.md", 7), ("split", "s.md", 8), ("quoted", "q.md", 11)], ) + def test_a_definition_ends_where_the_parser_ends_it(self) -> None: + text = "[titled]: t.md\n 'Title'\n[bare]: b.md\nProse after it.\n" + self.assertEqual( + [(d.label, d.line, d.end) for d in fidelity_text.link_definitions(text)], + [("titled", 0, 2), ("bare", 2, 3)], + ) + def test_an_escape_in_a_label_or_an_angle_destination_is_read_through(self) -> None: text = "[a\\\\]: one.md\n\n[b]: b>\n\n[c\\\nd]: two.md\n" self.assertEqual( diff --git a/tests/test_hub_fetch_run.py b/tests/test_hub_fetch_run.py index 2266489e5..f7003e688 100755 --- a/tests/test_hub_fetch_run.py +++ b/tests/test_hub_fetch_run.py @@ -188,8 +188,8 @@ def read(self) -> bytes: SHA_BODY = SHA.encode() PROSE_PATH = hub.PROSE_GATE_PATH -RESOLVED = f"ptr727/ProjectTemplate@{SHA} (hub-fetch-run main)" -UNRESOLVED = "ptr727/ProjectTemplate@main (hub-fetch-run, commit unresolved)" +RESOLVED = f"ptr727/ProjectTemplate@{SHA} (hub_fetch_run.py main)" +UNRESOLVED = "ptr727/ProjectTemplate@main (hub_fetch_run.py, commit unresolved)" RECORD = ( b"import os, sys\n" b"with open(sys.argv[1], 'w') as out:\n" @@ -319,7 +319,7 @@ def test_git_fallback_pins_the_script_and_its_data_to_one_commit(self) -> None: """A rate-limited API lookup still fetches both files at one commit, so they pair.""" self.git.return_value = (GIT_SHA, "") seen = self.run_main(RATE_LIMITED) - self.assertEqual(seen, f"ptr727/ProjectTemplate@{GIT_SHA} (hub-fetch-run main)") + self.assertEqual(seen, f"ptr727/ProjectTemplate@{GIT_SHA} (hub_fetch_run.py main)") fetched = [u for u in self.urls() if u != hub.HUB_MAIN_SHA_URL] self.assertEqual( fetched, @@ -483,10 +483,9 @@ def test_every_other_shape_names_its_cause(self) -> None: "Lint: Markdown": "markdownlint", "Lint: Spelling": "cspell", } -TASK_SNIPPETS = { - "vscode-tasks.json": ".husky/hub_fetch_run.py", - "vscode-tasks-python.json": "hub_fetch_run.py", -} +HELPER = "${workspaceFolder}/hub_fetch_run.py" +TASK_SNIPPETS = ("vscode-tasks.json", "vscode-tasks-python.json") +HUSKY_HOOK = ROOT / "catalog" / "snippets" / "husky" / "pre-commit" def snippet_tasks(name: str) -> dict[str, dict]: @@ -505,14 +504,54 @@ def forms(self, task: dict) -> list[list[str]]: return forms def test_each_docker_lint_task_runs_the_wrapper_through_the_helper(self) -> None: - for name, helper in TASK_SNIPPETS.items(): + for name in TASK_SNIPPETS: tasks = snippet_tasks(name) for label, linter in LINT_TASKS.items(): for form in self.forms(tasks[label]): with self.subTest(snippet=name, task=label, command=form[0]): - self.assertIn(f"${{workspaceFolder}}/{helper}", form) + self.assertIn(HELPER, form) self.assertEqual(form[-3:], [DOCKER_LINT, "--linter", linter]) + def test_every_helper_reference_names_the_root_copy(self) -> None: + """A task naming the helper anywhere but the root fails in a repo that keeps it there.""" + for name in TASK_SNIPPETS: + for label, task in snippet_tasks(name).items(): + for form in self.forms(task) if "command" in task else []: + for arg in form: + if arg.endswith("hub_fetch_run.py"): + with self.subTest(snippet=name, task=label, arg=arg): + self.assertEqual(arg, HELPER) + + def test_husky_hook_calls_the_root_copy_after_moving_to_the_top_level(self) -> None: + """The hook resolves the helper from the repo root, so the move to the top level comes first.""" + lines = HUSKY_HOOK.read_text(encoding="utf-8").splitlines() + cd = lines.index('cd "$(git rev-parse --show-toplevel)" || exit 1') + helper = lines.index('hub_fetch_run="$PWD/hub_fetch_run.py"') + self.assertLess(cd, helper) + + def test_ruff_tasks_take_the_tool_s_own_casing(self) -> None: + """A carrying repository copies these labels, so a capitalized one is a finding there.""" + hub_tasks = json.loads((ROOT / ".vscode" / "tasks.json").read_text(encoding="utf-8"))[ + "tasks" + ] + sources = { + "vscode-tasks-python.json": list(snippet_tasks("vscode-tasks-python.json").values()), + ".vscode/tasks.json": hub_tasks, + } + for source, tasks in sources.items(): + names = [task["label"] for task in tasks] + names += [name for task in tasks for name in task.get("dependsOn", [])] + with self.subTest(source=source): + self.assertLessEqual({"ruff format", "ruff check"}, set(names)) + self.assertEqual( + [ + name + for name in names + if name.lower().startswith("ruff") and not name.startswith("ruff") + ], + [], + ) + def test_no_task_binds_the_live_tree_into_a_container(self) -> None: """The wrapper's snapshot is the only mount, so no task may call Docker itself.""" for name in TASK_SNIPPETS: @@ -566,7 +605,7 @@ def run_wrapper(self) -> int: ): return hub.main([DOCKER_LINT, "--help"]) - def test_the_wrapper_imports_from_its_fetched_companions(self) -> None: + def test_the_wrapper_runs_with_no_other_hub_file_beside_it(self) -> None: self.assertEqual(self.run_wrapper(), 0, self.stdout) def test_the_wrapper_offers_every_linter_a_task_names(self) -> None: @@ -575,19 +614,10 @@ def test_the_wrapper_offers_every_linter_a_task_names(self) -> None: assert choices is not None, self.stdout self.assertLessEqual(set(LINT_TASKS.values()), set(choices.group(1).split(","))) - def test_a_planted_module_beside_the_scratch_directory_is_not_imported(self) -> None: - """A shared temporary root is writable by others, so nothing may be read from above it.""" - planted = self.tmp / "spec" - planted.mkdir() - (planted / "git_env.py").write_text("raise SystemExit(99)\n", encoding="utf-8") - with mock.patch.object(tempfile, "tempdir", str(self.tmp)): - self.assertEqual(self.run_wrapper(), 0, self.stdout) - def fetched(self, ref: str) -> list[str]: - paths = ("scripts/local_review.py", "spec/git_env.py", DOCKER_LINT) - return [f"{hub.HUB_RAW_BASE}/{ref}/{path}" for path in paths] + return [f"{hub.HUB_RAW_BASE}/{ref}/{DOCKER_LINT}"] - def test_every_file_comes_from_the_one_resolved_commit(self) -> None: + def test_the_wrapper_alone_comes_from_the_resolved_commit(self) -> None: self.assertEqual(self.run_wrapper(), 0, self.stdout) self.assertEqual(self.urls, self.fetched(SHA)) @@ -596,11 +626,11 @@ def test_the_run_names_the_hub_commit_it_ran_from(self) -> None: self.assertEqual(self.run_wrapper(), 0, self.stdout) self.assertIn(f"ptr727/ProjectTemplate@{SHA}", self.stderr.getvalue()) - def test_an_unresolved_commit_reads_main_twice_and_says_so(self) -> None: - """With no commit to pin to, the double read is what refuses a mixed set.""" + def test_an_unresolved_commit_reads_main_once_and_says_so(self) -> None: + """A lone file cannot form a mixed set, so no double read guards it.""" self.commit = None self.assertEqual(self.run_wrapper(), 0, self.stdout) - self.assertEqual(self.urls, self.fetched("main") * 2) + self.assertEqual(self.urls, self.fetched("main")) self.assertIn("ptr727/ProjectTemplate@main", self.stderr.getvalue()) diff --git a/tests/test_spec_validate.py b/tests/test_spec_validate.py index 2f2e21bc4..4218e2560 100755 --- a/tests/test_spec_validate.py +++ b/tests/test_spec_validate.py @@ -388,68 +388,15 @@ def test_importing_validate_loads_no_markdown_reader(self) -> None: self.assertEqual(after, [], f"importing {module} pulled in a Markdown reader") -class BaselineAlternativesCase(unittest.TestCase): - """A baseline entry's `alternatives`, the other paths its file may sit at instead.""" +class CodecovEntryCase(unittest.TestCase): + """The live manifest names the Codecov configuration once, as `.codecov.yml`.""" - def test_an_intent_file_with_an_alternative_is_clean(self) -> None: - baseline = [{"path": "tool.yml", "fidelity": "intent", "alternatives": [".tool.yml"]}] - - self.assertEqual(validate.alternatives_errors(baseline), []) - - def test_an_entry_without_alternatives_is_clean(self) -> None: - baseline = [{"path": "tool.yml"}, {"path": "tool.yml", "fidelity": "intent"}] - - self.assertEqual(validate.alternatives_errors(baseline), []) - - def test_a_list_off_the_schema_shape_is_rejected(self) -> None: - for alts in (None, [], [1], ".tool.yml", [""], [".tool.yml", ".tool.yml"]): - with self.subTest(alts=alts): - baseline = [{"path": "tool.yml", "alternatives": alts}] - self.assertEqual( - validate.alternatives_errors(baseline), - [ - "files.json: tool.yml alternatives must be a non-empty array of distinct, non-empty strings" - ], - ) - - def test_an_alternative_that_is_a_declared_path_is_rejected(self) -> None: - for baseline in ( - [{"path": "tool.yml", "alternatives": ["tool.yml"]}], - [{"path": "tool.yml", "alternatives": [".tool.yml"]}, {"path": ".tool.yml"}], - ): - with self.subTest(baseline=baseline): - errors = validate.alternatives_errors(baseline) - self.assertEqual(len(errors), 1) - self.assertIn("already declared as a baseline path", errors[0]) - - def test_a_unit_checked_beyond_presence_may_not_carry_one(self) -> None: - for extra in ({"fidelity": "verbatim"}, {"fidelity": "interface"}, {"sections": ["A"]}): - with self.subTest(extra=extra): - baseline = [{"path": "tool.md", "alternatives": [".tool.md"], **extra}] - self.assertEqual( - validate.alternatives_errors(baseline), - [ - "files.json: tool.md declares alternatives, which only a whole-file presence or intent unit may carry" - ], - ) - - def test_a_second_entry_naming_the_same_path_is_rejected(self) -> None: - baseline = [ - {"path": "tool.md", "alternatives": [".tool.md"]}, - {"path": "tool.md", "sections": [{"name": "A", "fidelity": "verbatim"}]}, - ] - - self.assertEqual( - validate.alternatives_errors(baseline), - ["files.json: tool.md declares alternatives, so no other baseline entry may name it"], - ) - - def test_the_live_codecov_entry_accepts_the_dotfile_name(self) -> None: + def test_the_live_codecov_entry_names_only_the_dotfile(self) -> None: baseline = validate.load("spec/files.json")["baseline"] - codecov = next(item for item in baseline if item["path"] == "codecov.yml") + paths = [item["path"] for item in baseline if "codecov" in item["path"]] - self.assertEqual(codecov.get("alternatives"), [".codecov.yml"]) - self.assertEqual(validate.alternatives_errors(baseline), []) + self.assertEqual(paths, [".codecov.yml"]) + self.assertEqual([item["path"] for item in baseline if "alternatives" in item], []) class VersionLiteralCase(unittest.TestCase):