diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 55db570..ea0a6b6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -86,9 +86,12 @@ jobs: # The node's image, not ubuntu-latest (#81, as broker#88): tests/test_ci.py. runs-on: ubuntu-24.04 timeout-minutes: 15 + # statuses: read for the attest step (#147). Job-level permissions replace the + # workflow's, so it sits here, not above. permissions: contents: read id-token: write + statuses: read # The broker's exact Redis, 7.0.15 (broker deploy/redis-acl.conf), as on # co-processor's scratch server. Not a newer 7.x: from 7.2 redis-py's CLIENT # SETINFO is an ACL denial the broker's grant cannot cover until it upgrades @@ -149,7 +152,56 @@ jobs: UV_INDEX_CO_PYPI_PASSWORD: ${{ steps.auth.outputs.access_token }} run: uv sync --locked + # The local-gate attestation (#147; skills/shipping-work/references/ + # attestation.md). push.sh posts gate/local = success on a commit whose tree + # pre-ship.sh passed. Read on pull requests only. A fast-forward merge puts the + # PR's head on main, status and all, so a read on main's push run (the one + # deploy.sh reads) would skip the suite there. Unread, it runs the whole suite, + # and a refused read can't fail it. Unset reads as not attested. + # + # HEAD is the PR's head: on pull_request, github.sha is the merge commit, + # which nobody gated. The combined status keeps each context's latest state + # (/statuses lists every one ever posted, so a later failure would still + # count). A page is 30 contexts unless more are asked for. A refused read + # fails this step: loud, never a silent skip. + - name: Attested by the local gate? + id: attest + if: github.event_name == 'pull_request' + env: + GH_TOKEN: ${{ github.token }} + HEAD: ${{ github.event.pull_request.head.sha || github.sha }} + run: | + n=$(gh api "repos/${{ github.repository }}/commits/$HEAD/status?per_page=100" \ + --jq '[.statuses[] | select(.context == "gate/local" and .state == "success")] | length') + echo "attested=$([ "$n" -gt 0 ] && echo yes || echo no)" | tee -a "$GITHUB_OUTPUT" + # No marker filter: the integration tests are the bus contract. Host-bound # tests (live tailscaled, installed drop-ins) skip off co-processor. + # + # Skipped only for an attested commit, and never for a bot's PR (Dependabot) + # or a fork's: neither came from a local gate. The reference's `if:`, + # verbatim. Step-level, not job-level: a skipped job reads `skipped`, which + # deploy.sh refuses; a skipped step leaves `test` success. No schedule: under + # merge_mode pr, every commit reaches main through a full push run. - name: pytest + if: >- + steps.attest.outputs.attested != 'yes' + || (github.event_name != 'push' && github.event_name != 'pull_request') + || startsWith(github.ref, 'refs/tags/') + || (github.event_name == 'pull_request' + && (github.event.pull_request.user.type == 'Bot' + || github.event.pull_request.head.repo.full_name != github.repository)) run: uv run pytest + + # Exactly when the step above skips. pre-ship.sh deselects every integration + # test, so the gate never ran this tier: an attested PR still checks the bus + # contract against the broker's Redis here (tests/test_ci.py). + - name: pytest (integration) + if: >- + !(steps.attest.outputs.attested != 'yes' + || (github.event_name != 'push' && github.event_name != 'pull_request') + || startsWith(github.ref, 'refs/tags/') + || (github.event_name == 'pull_request' + && (github.event.pull_request.user.type == 'Bot' + || github.event.pull_request.head.repo.full_name != github.repository))) + run: uv run pytest -m integration diff --git a/.skills/attest-local-gate b/.skills/attest-local-gate new file mode 100644 index 0000000..d07e4cd --- /dev/null +++ b/.skills/attest-local-gate @@ -0,0 +1,6 @@ +# push.sh runs the gate on the exact tree, pushes only what passes, then posts the +# commit status gate/local = success on the pushed SHA (#147, skills#688). CI's +# `test` job reads it on a PR only and skips the suite the gate ran, never the +# integration tier (docs/DEPENDENCIES.md § Local-gate attestation). Trust, not +# proof: never a required status. Read from the commit, not the work tree. +on diff --git a/.skills/doc-sections b/.skills/doc-sections index aefa97a..af2d2ac 100644 --- a/.skills/doc-sections +++ b/.skills/doc-sections @@ -9,6 +9,6 @@ AGENTS.md: the co-core pin and the co-pypi index under Environment & Tooling (py docs/DEPENDENCIES.md "Bumping co-core", docs/DEPENDENCIES.md "Extraction dependencies": pyproject.toml, uv.lock, the co-pypi index and scripts/co-pypi.sh, LOCAL_GENERATION docs/DEPLOYMENT.md "Deploy a change: `scripts/deploy.sh`", docs/MONITORING.md "The drift check", docs/MONITORING.md "Liveness": deploy/ units, scripts/deploy.sh, processor.drift.RUNTIME_* docs/PATCHING.md "Patching", docs/PATCHING.md "The patch-due check", docs/PATCHING.md "Node.js (agent tooling only)": .skills/patching-hosts, deploy/apt/, the apt timers' drop-ins, deploy/needrestart.conf.d/, deploy/nodesource.sh, src/processor/patching.py -docs/DEPENDENCIES.md "CI pins and Dependabot", docs/DEPENDENCIES.md "Shell lint", docs/DEPENDENCIES.md "The lock audit": .github/, scripts/shellcheck.sh, scripts/audit_lock.sh, .githooks/ +docs/DEPENDENCIES.md "CI pins and Dependabot", docs/DEPENDENCIES.md "Local-gate attestation", docs/DEPENDENCIES.md "Shell lint", docs/DEPENDENCIES.md "The lock audit": .github/, scripts/shellcheck.sh, scripts/audit_lock.sh, .githooks/ docs/SKILLS.md: the inventory, the refresh hook, Merging under pr and the doc-check lists (skills/, .claude/, .gitmodules, the .skills/ knobs) docs/SOCRATICODE.md: the store, the index scope and the context manifest (.socraticode.json, .socraticodecontextartifacts.json, .socraticodeignore, .claude/settings.json's env block) diff --git a/.skills/doc-sensitive-paths b/.skills/doc-sensitive-paths index 6c7fedb..28059cc 100644 --- a/.skills/doc-sensitive-paths +++ b/.skills/doc-sensitive-paths @@ -34,6 +34,7 @@ deploy_command doc-sensitive-paths doc-sections gate-stamp-inputs +attest-local-gate # Semantic search (docs/SOCRATICODE.md). .socraticode.json diff --git a/AGENTS.md b/AGENTS.md index 807dc01..29a8678 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -38,7 +38,7 @@ Python 3.12, uv, hatchling src layout, pytest, ruff. | Input | `gs://co-gcs-blobs` (Replicator's raw blobs), read-only | | Output | `gs://co-gcs-processor/blobs/.bin`, write-if-absent, **never deleted** | | Service | systemd unit `processor` ([deploy/processor.service](deploy/processor.service)), as user `processor` (no sudo, not in `docker`, no home), from `/srv/processor/live` → `releases/`, a read-only release `scripts/deploy.sh` builds from a commit on `origin/main` (#2). **Never from a checkout**. [docs/DEPLOYMENT.md](docs/DEPLOYMENT.md) | -| CI | [.github/workflows/ci.yml](.github/workflows/ci.yml): lint (ruff, shellcheck), then the full suite against `redis:7.0.15`, the broker's, pulled from `mirror.gcr.io`, never anonymously from Docker Hub (#43). Pins, keyless WIF to `co-pypi-reader`, Dependabot (`github-actions` only): [docs/DEPENDENCIES.md](docs/DEPENDENCIES.md#ci-pins-and-dependabot); shell lint: [§ Shell lint](docs/DEPENDENCIES.md#shell-lint) | +| CI | [.github/workflows/ci.yml](.github/workflows/ci.yml): lint (ruff, shellcheck), then the full suite (an attested PR: integration only, #147) against `redis:7.0.15`, the broker's, pulled from `mirror.gcr.io`, never anonymously from Docker Hub (#43). Pins, keyless WIF to `co-pypi-reader`, Dependabot (`github-actions` only): [docs/DEPENDENCIES.md](docs/DEPENDENCIES.md#ci-pins-and-dependabot); shell lint: [§ Shell lint](docs/DEPENDENCIES.md#shell-lint) | | Lock audit | [.github/workflows/audit.yml](.github/workflows/audit.yml), report-only, outside the deploy gate: [docs/DEPENDENCIES.md](docs/DEPENDENCIES.md#the-lock-audit) | | Status | Check-ins: drift (`processor-drift.timer`, hourly), liveness (`processor run`, 5 min), disk headroom ([deploy/disk-gc/disk-gc.conf](deploy/disk-gc/disk-gc.conf)): [docs/MONITORING.md](docs/MONITORING.md) | | Patching | `automatic` (knob `.skills/patching-hosts`, #113): `-security` daily by unattended-upgrades; the rest in one approved run a week, `Tue 05:00–10:00` UTC. Never a bare `apt-get upgrade`. [docs/PATCHING.md](docs/PATCHING.md#patching) | diff --git a/docs/DEPENDENCIES.md b/docs/DEPENDENCIES.md index 7224d0a..6ef03d5 100644 --- a/docs/DEPENDENCIES.md +++ b/docs/DEPENDENCIES.md @@ -1,24 +1,24 @@ # Dependencies and CI -What Processor pins and how each pin moves: the CI workflow's actions and images, shellcheck, the lock audit, co-core, the extraction stack, certifi. The deploy's CI gate: [DEPLOYMENT.md](DEPLOYMENT.md#the-ci-gate). +What Processor pins and how each pin moves: the CI workflow's actions and images, the local-gate attestation, shellcheck, the lock audit, co-core, the extraction stack, certifi. The deploy's CI gate: [DEPLOYMENT.md](DEPLOYMENT.md#the-ci-gate). ## At a glance | Thing | Value | |---|---| -| CI | GitHub Actions [.github/workflows/ci.yml](../.github/workflows/ci.yml) on `ubuntu-24.04`, the node's image: lint (ruff, shellcheck), then the full suite against `redis:7.0.15` (the broker's, not 7.2: CLIENT SETINFO; upstream EOL, the next is broker#85's call), pulled from `mirror.gcr.io`, never anonymously from Docker Hub (#43). Keyless WIF to `co-pypi-reader`, whose token only `uv sync` gets (#121), needs the org variable `GCP_WIF_PROVIDER` shared with this repo and a `roles/iam.workloadIdentityUser` binding for `principalSet://…/attribute.repository/CannObserv/processor`. Actions SHA-pinned; Dependabot version updates `github-actions` only, `uv` security updates landed by hand ([§ below](#ci-pins-and-dependabot), #80). Shell lint, with an opt-in pre-commit hook: [§ below](#shell-lint) (#81) | +| CI | GitHub Actions [.github/workflows/ci.yml](../.github/workflows/ci.yml) on `ubuntu-24.04`, the node's image: lint (ruff, shellcheck), then the full suite against `redis:7.0.15` (the broker's, not 7.2: CLIENT SETINFO; upstream EOL, the next is broker#85's call), pulled from `mirror.gcr.io`, never anonymously from Docker Hub (#43). An attested PR runs only the integration tier ([§ below](#local-gate-attestation), #147). Keyless WIF to `co-pypi-reader`, whose token only `uv sync` gets (#121), needs the org variable `GCP_WIF_PROVIDER` shared with this repo and a `roles/iam.workloadIdentityUser` binding for `principalSet://…/attribute.repository/CannObserv/processor`. Actions SHA-pinned; Dependabot version updates `github-actions` only, `uv` security updates landed by hand ([§ below](#ci-pins-and-dependabot), #80). Shell lint, with an opt-in pre-commit hook: [§ below](#shell-lint) (#81) | | Lock audit | [.github/workflows/audit.yml](../.github/workflows/audit.yml): `uv audit --frozen`, report-only, outside the deploy gate (#73). The weekly patch window reads the live lock (#75): [§ below](#the-lock-audit) | ## CI pins and Dependabot Ported from broker#88 and broker#90 (#80). -**Pins.** Every `uses:` in `ci.yml` and `audit.yml` takes the form `owner/action@<40-hex sha> # vX.Y.Z`. A tag can be moved, and setup-uv publishes no floating major since v8. As of #80, with setup-uv moved by #110 (Dependabot's first PR here): +**Pins.** Every `uses:` in `ci.yml` and `audit.yml` takes the form `owner/action@<40-hex sha> # vX.Y.Z`. A tag can be moved, and setup-uv publishes no floating major since v8. As of #80, with setup-uv moved by #110 (Dependabot's first PR here) and #148: | Action | Pin | |---|---| | `actions/checkout` | v7.0.1 | -| `astral-sh/setup-uv` | v10.3.3 | +| `astral-sh/setup-uv` | v10.4.0 | | `google-github-actions/auth` | v3.0.0 | These are broker's majors (operator, 2026-10-29). `tests/test_dependabot.py` holds the form. `tests/test_ci.py` holds each major to a floor, so a Dependabot major passes and a downgrade fails. `tests/test_lock_audit.py` holds `audit.yml`'s pins equal to `ci.yml`'s. @@ -79,6 +79,16 @@ git push origin main # GitHub marks the PR merged **The runner image.** Every job in `ci.yml` and `audit.yml` runs on `ubuntu-24.04`, co-processor's image, not `ubuntu-latest`. That is 26.04 now: main's run 41003391205 (2026-10-30) ran on `ubuntu-26.04` (#81, as broker#88). The shell lint and the suite then run on the node's userland, and `test`'s Redis fallback, 24.04's apt `redis-server`, is 7.0.15. `tests/test_ci.py` holds every `runs-on` to one image, and on co-processor holds that image to `/etc/os-release`. So a node upgrade fails the suite there until the pins move with it. +## Local-gate attestation + +Adopted in #147 from `shipping-work` (gregoryfoster/skills#688; the reference is `skills/shipping-work/references/attestation.md`). The repo is public, so it saves no billed minutes; it is the cohort's shape (CannObserv/status's). + +- **The push.** `.skills/attest-local-gate` is committed `on`, so `push.sh` runs `pre-ship.sh` on a clean tree, pushes only what passes, then posts the commit status `gate/local` = `success` on the pushed SHA. It needs `GH_TOKEN`'s **Commit statuses: Read and write**. +- **CI reads it on a PR only.** `test`'s `attest` step reads the head's combined status (`statuses: read` on the job, since a job's `permissions` replace the workflow's). When attested, the `pytest` step skips. A bot's PR, a fork's, a manual run and a tag never skip. +- **The integration tier always runs.** `pre-ship.sh` deselects `integration`, so an attested PR runs `pytest -m integration` instead: the bus contract against the broker's Redis. `tests/test_ci.py` evaluates both `if:`s over each trigger: exactly one runs. +- **Step-level, so the deploy gate is unchanged.** A push to `main` reads nothing and runs the whole suite, and a skipped step leaves `test` `success` ([DEPLOYMENT.md § The CI gate](DEPLOYMENT.md#the-ci-gate)). No schedule: every commit reaches `main` through that run. +- **Trust, not proof.** Anyone with push access can post `gate/local`. Never make it a required status. Never post it by hand. + ## Shell lint Ported from broker#112 (#81). `scripts/shellcheck.sh` lints this repo's own shell scripts: every tracked `*.sh` and `.githooks/*`. diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index fe3528b..90999f5 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -103,6 +103,7 @@ A stop mid-reclaim finishes the command in hand and leaves the rest pending. A c **A deploy needs the commit's CI to have passed** (#34, ported from status#11). Before anything is built, `deploy.sh` asks GitHub's Actions API about the commit. It refuses unless `lint`, `test` and any other job in the run all succeeded. The refusal names each job that didn't, with its conclusion, and links the run. A refused deploy changes nothing. - **Which run.** The newest `push` run of `ci.yml` on `main` for exactly that commit. Every FF merge also has a `pull_request` run on the same SHA, and that one doesn't count, nor does a `workflow_dispatch` run. A re-run counts, since GitHub reports a run's latest attempt. + - That run always runs the full suite. The local-gate attestation skips the suite only on a PR's run ([DEPENDENCIES.md § Local-gate attestation](DEPENDENCIES.md#local-gate-attestation), #147). - **The run and every job in it must be `success`.** A `skipped` job leaves the run's own conclusion `success`, so the gate reads the jobs too. - `CI_JOBS` in `deploy.sh` (`lint test`) is a floor, and `tests/test_deploy.py` holds `ci.yml` to it. Any other job counts without being named there. - A job renamed in `ci.yml` must be renamed in `CI_JOBS`. A build from before the rename then lacks the new name, so rolling back to it needs `--skip-ci`. diff --git a/docs/SKILLS.md b/docs/SKILLS.md index 074e66a..27d64a1 100644 --- a/docs/SKILLS.md +++ b/docs/SKILLS.md @@ -11,7 +11,7 @@ Vendored by [`managing-skills`](../skills/managing-skills/SKILL.md): one git sub | `skills/` | agentskills.io discovery: a symlink `../skills-vendor/-/skills/`, or a committed override | | `.claude/skills/` | Claude Code discovery: always `../../skills/`, so an override shadows the vendor copy in both systems | | `.skills/doctor.sh` | A real file, not a symlink (it would dangle exactly when needed). Re-links dangling vendor symlinks by initialising the submodules; `reviewing-*` / `shipping-*` run it as preflight | -| `.skills/merge_mode`, `deploy_command`, `doc-sensitive-paths`, `doc-sections`, `gate-stamp-inputs` | `shipping-work`'s knobs (#115): [§ Shipping](#shipping-shipping-work). [tests/test_shipping_knobs.py](../tests/test_shipping_knobs.py) reads the first two through the skill's own readers | +| `.skills/merge_mode`, `deploy_command`, `doc-sensitive-paths`, `doc-sections`, `gate-stamp-inputs`, `attest-local-gate` | `shipping-work`'s knobs (#115, #147): [§ Shipping](#shipping-shipping-work). [tests/test_shipping_knobs.py](../tests/test_shipping_knobs.py) reads `merge_mode`, `deploy_command` and `attest-local-gate` through the skill's own readers | | `.claude/hooks/gh-env.sh`, `scripts/env-value.sh` | Ours, not vendored: `GH_TOKEN` from `.env`, as data, for the session's `gh` calls (the refresh hook finds its own: [§ Refresh](#refresh)). A replica of [gregoryfoster/skills#334](https://github.com/gregoryfoster/skills/issues/334)'s `using-github-cli`; adopt that once it ships, and the hook becomes its vendor symlink | | `.claude/hooks/context-budget-guard.sh`, `.github/workflows/context-cadence.yml`, `.gitattributes`, `.skills/context-*` | `curating-context`'s write guard, weekly measurement and ledger (#126): [§ Context budget](#context-budget) | | `.skills/worktree_venv` | `none`: each worktree provisions its own `.venv` (`using-git-worktrees` → *Venv linking*). Set when this checkout was the unit's `WorkingDirectory=`; since #2 the unit runs a release, and the knob stays only so worktrees never share the checkout's venv | @@ -81,6 +81,7 @@ One skill since #115, which detects the stack: `Detected: toolchain uv`, with no | `deploy_command` | `setsid -w scripts/deploy.sh` | The release deploy (#2). `-w` keeps the deploy's exit code (broker#123). The skill appends the pushed SHA | | `doc-sensitive-paths`, `doc-sections` | tailored | Committed together, or every hit says which half is the default. A dead entry, a missing doc or a missing heading fails `tests/test_shipping_knobs.py` | | `gate-stamp-inputs` | `.env` | Replaces the default, so `.env` is named again (`tests/test_child.py` probes it). `.wheelhouse/*` left with #121: no untracked file decides which co-core installs | +| `attest-local-gate` | `on` | `push.sh` gates the exact tree, then posts `gate/local` on the pushed SHA (#147). An attested PR's CI skips the suite but not the integration tier: [DEPENDENCIES.md § Local-gate attestation](DEPENDENCIES.md#local-gate-attestation). Ship from a clean tree, submodules included | | `import-targets`, `pre-ship-uv-args` | absent | The default `processor` is right, and CI's `uv run pytest` takes no group | ### Merging under `pr` diff --git a/docs/plans/2026-11-24-147-attest-local-gate.md b/docs/plans/2026-11-24-147-attest-local-gate.md new file mode 100644 index 0000000..6bb6014 --- /dev/null +++ b/docs/plans/2026-11-24-147-attest-local-gate.md @@ -0,0 +1,44 @@ +--- +title: Adopt shipping-work's local-gate attestation (#147) +date: 2026-11-24 +status: per #147's brief (comment 7141925251, epic #84; its three recommended decisions approved by the operator); corrections on the issue (comment 7142241797) +--- + +# Local-gate attestation + +## Problem + +Since gregoryfoster/skills#688, `shipping-work`'s `push.sh` can attest the local gate. With `.skills/attest-local-gate` committed as `on`, it posts the commit status `gate/local` = `success` on the SHA it pushed, and CI may then skip its heavy tier. The repo is public, so this saves no billed minutes. It is conformance with the cohort's adopters (status, broker, address-validator). The reference is `skills/shipping-work/references/attestation.md` at the vendored `9443df67`. + +Two of this repo's own constraints shape the CI side: +- **The deploy gate.** `scripts/deploy.sh` needs `lint` and `test` to be `success` on `main`'s push run. A skipped *job* reads `skipped` there and blocks the deploy. A skipped *step* leaves its job `success`. +- **The integration tier.** `pre-ship.sh` deselects every `integration` test (60 of 1,124), so the gate never ran them. The reference's skip of `uv run pytest` would drop them from an attested PR. + +## Approach + +The brief's decisions: +1. **CannObserv/status's shape.** The `attest` step runs on `pull_request` only, after `uv sync`. `pytest` takes the reference's `if:` verbatim, at step level. A push to `main` reads nothing and runs the full suite, so `deploy.sh`, `CI_JOBS` and the gate's meaning don't change. +2. **The integration tier still runs on an attested PR.** A step `uv run pytest -m integration` takes `!()`: exactly one of the two runs. +3. **No schedule.** `merge_mode` is `pr`, and every commit that reaches `main` gets a full push run. + +`statuses: read` goes on the `test` job's own `permissions`, since a job's `permissions` replace the workflow's. + +## Steps (TDD) + +1. `tests/test_ci.py`, red first: + - the exact permissions: `lint` unchanged, `test` adds `statuses: read`; + - the attest step: `if: github.event_name == 'pull_request'`, reads the combined status with `per_page=100`, keyed to the PR's head; + - both `if:`s, evaluated over an event matrix by a small evaluator for GitHub's expression syntax. The full suite never skips on a push, `workflow_dispatch`, a tag, a bot's PR, a fork's PR or an unattested PR, and skips on an attested PR. The integration step's `if:` is `!()`; + - the full suite still has no `-m`; the integration step is exactly `-m integration`. +2. `tests/test_shipping_knobs.py`: the knob reads `on` through the skill's own `attest_read_knob`, in the scratch repo. +3. `.github/workflows/ci.yml` and `.skills/attest-local-gate` (`on`); green. +4. `.skills/doc-sensitive-paths` gains `attest-local-gate`. +5. Docs: + - `docs/SKILLS.md`: the knob row at `:14`, and § Shipping's table; + - `docs/DEPENDENCIES.md`: the setup-uv pin row (v10.4.0, #148) and a short § Local-gate attestation; + - `docs/DEPLOYMENT.md` § The CI gate: one line; + - `AGENTS.md`'s CI row, within its budget. + +## Ship + +PR (`Refs #147`: the Dependabot case is the live check) via `shipping-work`'s `push.sh`, whose first push prints `Attestation: gate/local = success posted on `. On the PR's run: `attested=yes`, `pytest` skipped, the integration step ran 60 tests, `lint` ran in full. After the FF merge, `main`'s push run on the same SHA: `attest` skipped, `pytest` ran the full suite. No deploy: nothing in `processor.drift.RUNTIME_*` moves. diff --git a/tests/test_ci.py b/tests/test_ci.py index 23e56bb..7e2f398 100644 --- a/tests/test_ci.py +++ b/tests/test_ci.py @@ -56,9 +56,15 @@ def test_runs_on_pushes_and_prs_to_main(ci: dict) -> None: def test_cloud_access_is_job_scoped(ci: dict) -> None: + """A job's ``permissions`` replace the workflow's, so ``statuses: read`` sits on + ``test``, whose attest step reads the combined status (#147); at workflow level + it would be ignored.""" assert ci["permissions"] == {"contents": "read"} - for name, job in ci["jobs"].items(): - assert job["permissions"] == {"contents": "read", "id-token": "write"}, name + cloud = {"contents": "read", "id-token": "write"} + assert {name: job["permissions"] for name, job in ci["jobs"].items()} == { + "lint": cloud, + "test": {**cloud, "statuses": "read"}, + } PAIR = { @@ -214,8 +220,213 @@ def test_the_whole_suite_runs_against_the_brokers_redis(ci: dict) -> None: redis = job["services"]["redis"] assert redis["image"] == BROKER_REDIS assert "6379:6379" in redis["ports"] - (pytest_run,) = [line for line in _runs(job).splitlines() if "pytest" in line] - assert " -m " not in pytest_run, "a marker filter would drop the integration tests" + runs = [line for line in _runs(job).splitlines() if "pytest" in line] + assert runs == [FULL_SUITE, INTEGRATION], "a marker filter would drop the integration tests" + + +# The local-gate attestation (#147; shipping-work's references/attestation.md). +# CannObserv/status's shape: the attest step reads only on a PR, and the full suite +# skips at step level, so `test` stays `success` and every push to main runs it all: +# deploy.sh's gate is unchanged. The local gate deselects the integration tier, so an +# attested PR still runs that, on the inverse condition. +FULL_SUITE = "uv run pytest" +INTEGRATION = "uv run pytest -m integration" +REPO = "CannObserv/processor" + + +def _step_running(job: dict, command: str) -> dict: + (step,) = [s for s in _steps(job) if s.get("run", "").strip() == command] + return step + + +def _attest(ci: dict) -> dict: + (step,) = [s for s in _steps(ci["jobs"]["test"]) if s.get("id") == "attest"] + return step + + +def test_the_attest_step_reads_the_heads_combined_status_on_a_pr_only(ci: dict) -> None: + """Only on a PR. Processor merges by fast-forward, so main's push run is on the + PR's head SHA, which carries its ``gate/local``: a read there would skip the full + suite on the run deploy.sh reads. The combined status keeps each context's latest + state; a page is 30 contexts unless asked for more.""" + step = _attest(ci) + assert step["if"] == "github.event_name == 'pull_request'" + assert step["env"] == { + "GH_TOKEN": "${{ github.token }}", + "HEAD": "${{ github.event.pull_request.head.sha || github.sha }}", + } + run = step["run"] + assert "commits/$HEAD/status?per_page=100" in run + assert '.context == "gate/local" and .state == "success"' in run + assert '"attested=$(' in run and '"$GITHUB_OUTPUT"' in run + + +def test_the_attest_step_comes_between_the_sync_and_the_suite(ci: dict) -> None: + job = ci["jobs"]["test"] + steps = _steps(job) + order = [_sync_step(job), _attest(ci), _step_running(job, FULL_SUITE)] + assert [steps.index(s) for s in order] == sorted(steps.index(s) for s in order) + assert steps.index(_step_running(job, INTEGRATION)) > steps.index(_attest(ci)) + + +# A minimal evaluator for GitHub's expression syntax: enough for these `if:`s. +# Literals, dotted context paths (missing ones are null, read as ''), ==, !=, !(…), +# &&, ||, parentheses and startsWith. GitHub compares strings case-insensitively; the +# values below are written in one case, so plain equality agrees. A step's implicit +# `success() &&` is not modelled: every earlier step is taken to have passed. +_TOKEN = re.compile( + r"\s*(?:(?P'(?:[^']|'')*')|(?P\|\||&&|==|!=|!|\(|\)|,)|(?P[A-Za-z_][\w.-]*))" +) +_PY = { + "||": " or ", + "&&": " and ", + "!": " not ", + "==": "==", + "!=": "!=", + "(": "(", + ")": ")", + ",": ",", +} +_LITERALS = {"true": "True", "false": "False", "null": "''"} + + +def _evaluate(expression: str, context: dict) -> bool: + def lookup(path: str) -> object: + value: object = context + for key in path.split("."): + value = value.get(key, "") if isinstance(value, dict) else "" + return value + + def starts_with(text: object, prefix: object) -> bool: + return str(text).lower().startswith(str(prefix).lower()) + + out, pos, text = [], 0, expression.strip() + while pos < len(text): + found = _TOKEN.match(text, pos) + assert found and found.end() > pos, f"cannot read {text[pos:]!r}" + pos = found.end() + if found["str"] is not None: + out.append(repr(found["str"][1:-1].replace("''", "'"))) + elif found["op"] is not None: + # Python's `not` binds looser than `==`, GitHub's `!` tighter: they agree + # only on a parenthesised operand. + bare = found["op"] == "!" and not text[pos:].lstrip().startswith("(") + assert not bare, f"`!` is read only before `(`: {text!r}" + out.append(_PY[found["op"]]) + elif found["name"] in _LITERALS: + out.append(_LITERALS[found["name"]]) + elif found["name"] == "startsWith": + out.append("_starts_with") + else: + out.append(f"_lookup({found['name']!r})") + names = {"__builtins__": {}, "_lookup": lookup, "_starts_with": starts_with} + return bool(eval("".join(out), names)) # noqa: S307 - our own workflow's text + + +@pytest.mark.parametrize(("expression", "expected"), [ + ("github.event_name == 'push'", True), + ("github.event_name != 'push' || startsWith(github.ref, 'refs/tags/')", False), + ("!(github.event_name == 'push') || steps.none.outputs.x != 'yes'", True), + ("github.event.pull_request.user.type == 'Bot'", False), + ("'it''s' == 'it''s' && true", True), +]) # fmt: skip +def test_the_evaluator_reads_githubs_syntax(expression: str, expected: bool) -> None: + # Guard the guard: a missing path reads as null, never as an error. + context = {"github": {"event_name": "push", "ref": "refs/heads/main"}, "steps": {}} + assert _evaluate(expression, context) is expected + + +def test_the_evaluator_refuses_a_bare_not() -> None: + """GitHub's ``!`` binds tighter than ``==``; Python's ``not`` looser. Only ``!(`` is + read, so ``!a == b`` is refused rather than misread.""" + with pytest.raises(AssertionError, match="only before"): + _evaluate("!github.event_name == 'push'", {"github": {"event_name": "push"}}) + + +def _job_run( + ci: dict, + event: str, + *, + status: bool, + ref: str = "refs/heads/main", + bot: bool = False, + fork: bool = False, +) -> tuple[bool, bool]: + """Whether the full suite and the integration step run, for one trigger. + + ``status`` is whether the head carries ``gate/local`` = ``success``. The attest + step's output exists only if that step ran, as on Actions.""" + github: dict = {"event_name": event, "ref": ref, "repository": REPO} + if event == "pull_request": + github["event"] = { + "pull_request": { + "user": {"type": "Bot" if bot else "User"}, + "head": {"repo": {"full_name": "someone/processor" if fork else REPO}}, + } + } + context = {"github": github, "steps": {}} + if _evaluate(_attest(ci)["if"], context): + attested = "yes" if status else "no" + context["steps"] = {"attest": {"outputs": {"attested": attested}}} + job = ci["jobs"]["test"] + return tuple( + _evaluate(_step_running(job, command).get("if", "true"), context) + for command in (FULL_SUITE, INTEGRATION) + ) + + +# A tag push never fires ci.yml today (push.branches is [main]). Its rows hold the +# reference's tag clause, should a tag trigger ever be added. +TRIGGERS = pytest.mark.parametrize(("event", "ref", "bot", "fork"), [ + ("push", "refs/heads/main", False, False), + ("push", "refs/tags/v1.0.0", False, False), + ("workflow_dispatch", "refs/heads/main", False, False), + ("pull_request", "refs/pull/1/merge", False, False), + ("pull_request", "refs/pull/1/merge", True, False), + ("pull_request", "refs/pull/1/merge", False, True), +]) # fmt: skip + + +@TRIGGERS +@pytest.mark.parametrize("status", [True, False]) +def test_exactly_one_of_the_suite_and_the_integration_tier_runs( + ci: dict, event: str, ref: str, bot: bool, fork: bool, status: bool +) -> None: + full, integration = _job_run(ci, event, status=status, ref=ref, bot=bot, fork=fork) + assert full != integration + + +@TRIGGERS +def test_the_full_suite_runs_on_every_unattested_trigger( + ci: dict, event: str, ref: str, bot: bool, fork: bool +) -> None: + assert _job_run(ci, event, status=False, ref=ref, bot=bot, fork=fork) == (True, False) + + +@pytest.mark.parametrize(("event", "ref", "bot", "fork"), [ + ("push", "refs/heads/main", False, False), # main's run, which deploy.sh reads + ("push", "refs/tags/v1.0.0", False, False), # unreachable today: see TRIGGERS + ("workflow_dispatch", "refs/heads/main", False, False), + ("pull_request", "refs/pull/1/merge", True, False), # Dependabot + ("pull_request", "refs/pull/1/merge", False, True), # a fork +]) # fmt: skip +def test_a_status_never_skips_the_suite_outside_a_humans_pr( + ci: dict, event: str, ref: str, bot: bool, fork: bool +) -> None: + """A bot's PR and a fork's never came from a local gate; a push to main reads no + status at all, so its run is always the whole suite.""" + assert _job_run(ci, event, status=True, ref=ref, bot=bot, fork=fork) == (True, False) + + +def test_an_attested_humans_pr_runs_only_the_integration_tier(ci: dict) -> None: + """The local gate ran the rest (pre-ship.sh deselects `integration`).""" + assert _job_run(ci, "pull_request", status=True) == (False, True) + + +def test_the_integration_steps_condition_is_the_suites_negated(ci: dict) -> None: + job = ci["jobs"]["test"] + full, integration = (_step_running(job, c)["if"] for c in (FULL_SUITE, INTEGRATION)) + assert " ".join(integration.split()) == f"!({' '.join(full.split())})" def _image(spec: object) -> str | None: diff --git a/tests/test_shipping_knobs.py b/tests/test_shipping_knobs.py index 0f0044c..0e83a8f 100644 --- a/tests/test_shipping_knobs.py +++ b/tests/test_shipping_knobs.py @@ -1,9 +1,10 @@ """The ``.skills/`` knobs the vendored ``shipping-work`` reads hold what #115 chose. -``merge_mode`` and ``deploy_command`` are read by the skill's own readers, never -re-parsed here: a knob that is present but unusable is exit 2 there, never the -default. Both read the *primary* checkout, so each runs in a scratch repo holding -only the knobs (a linked worktree would read the main checkout's). The doc-check +``merge_mode``, ``deploy_command`` and ``attest-local-gate`` are read by the skill's +own readers, never re-parsed here: a knob that is present but unusable is exit 2 +there, never the default. The first two read the *primary* checkout (a linked +worktree would read the main checkout's), and the third the commit at ``HEAD``, so +each runs in a scratch repo holding only the knobs, committed. The doc-check pair gets the dead-entry check upstream lacks for single entries: one entry that matches nothing is a hole the gate never reports, while the gate does fail a list that matches nothing at all. @@ -20,6 +21,7 @@ KNOBS = ROOT / ".skills" SHIP = ROOT / "skills" / "shipping-work" / "scripts" DOCTOR_HINT = "dangling: run `bash .skills/doctor.sh`" +KNOBS_READ = (".skills/merge_mode", ".skills/deploy_command", ".skills/attest-local-gate") def _lines(name: str) -> list[str]: @@ -41,7 +43,7 @@ def scratch(tmp_path: Path) -> Path: origin, repo = tmp_path / "origin.git", tmp_path / "repo" subprocess.run(["git", "init", "-q", "--bare", str(origin)], check=True) subprocess.run(["git", "init", "-q", "-b", "main", str(repo)], check=True) - for rel in (".skills/merge_mode", ".skills/deploy_command", "scripts/deploy.sh"): + for rel in (*KNOBS_READ, "scripts/deploy.sh"): (repo / rel).parent.mkdir(parents=True, exist_ok=True) shutil.copy2(ROOT / rel, repo / rel) _git(repo, "add", "-A") @@ -71,6 +73,20 @@ def test_deploy_command_is_the_release_deploy(scratch: Path) -> None: assert out.stdout.strip() == f"setsid -w scripts/deploy.sh {sha}" +def test_attest_local_gate_is_on(scratch: Path) -> None: + """#147: ``push.sh`` attests the gate (``gate/local``), and CI's ``test`` job reads + it (tests/test_ci.py). Read from the commit, by the skill's own reader: 0 is + ``on``, 3 ``off``, 2 unusable.""" + assert (SHIP / "_attest-gate.sh").is_file(), DOCTOR_HINT + out = subprocess.run( + ["bash", "-c", '. "$1" && attest_read_knob', "_", str(SHIP / "_attest-gate.sh")], + cwd=scratch, + capture_output=True, + text=True, + ) + assert out.returncode == 0, out.stderr + + def test_deploy_command_names_an_executable_repo_script() -> None: """The skill checks only the first word (``setsid``); the script is checked here.""" (line,) = _lines("deploy_command")