From 30c210ba32e63c260561aa5605e50332e879f2d9 Mon Sep 17 00:00:00 2001 From: naindev <193035803+Nain9Dev@users.noreply.github.com> Date: Thu, 12 Nov 2026 12:36:12 +0100 Subject: [PATCH 1/2] docs: keep private repository names and local paths out of this public repo Replace the real repository names in the README, the example train configuration and two comments with placeholders, point the README at the install directory instead of a local path, and stop tracking the compiled report module (add a .gitignore for __pycache__). standards/standards.json and the default install paths of the scripts are not touched here: they are functional and need a decision on where the organisation-specific parts live. --- .gitignore | 2 ++ README.md | 9 ++++----- report/__pycache__/ci_report.cpython-312.pyc | Bin 32459 -> 0 bytes train/automerge.py | 2 +- train/install.ps1 | 4 ++-- train/repos.example.json | 8 ++++---- 6 files changed, 13 insertions(+), 12 deletions(-) create mode 100644 .gitignore delete mode 100644 report/__pycache__/ci_report.cpython-312.pyc diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7a60b85 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +__pycache__/ +*.pyc diff --git a/README.md b/README.md index b092ed0..b87b2f3 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,7 @@ Reusable GitHub Actions workflows and a merge-train script shared by the Contrast3D repositories. -Status: in progress. The design is in `specs/next-ci-reliability` of -`naindev-contrast3d/contrast3d-platform`. Licensed under MIT. +Status: in progress. The design is kept in the maintainers' own repository. Licensed under MIT. ## Contents @@ -47,7 +46,7 @@ Status: in progress. The design is in `specs/next-ci-reliability` of Tests: `python3 -m unittest discover -s tests`. - `train/install.ps1` (available): installs the train as the scheduled task `CI train`, every two - minutes, from `D:\Development\Tools\ci-train` (a copy of `automerge.py`, a `repos.json` created from + minutes, from its install directory (`-Destination`; a copy of `automerge.py`, a `repos.json` created from the example only if missing, and `train.log`). Run it from a normal PowerShell window of the owner's session; `-Remove` retires the task. @@ -56,9 +55,9 @@ Status: in progress. The design is in `specs/next-ci-reliability` of never reached its steps, or the shared preflight) and not the code, the median duration and the median queue time, followed by a snapshot of today: runners online, offline and busy, queued runs and open pull requests. Use it to plan from the current state, not from memory: - `py -3 report/ci_report.py --config train/repos.json --repo naindev-contrast3d/contrast-hub --days 7`. + `py -3 report/ci_report.py --config train/repos.json --repo / --days 7`. For the repositories of `--config` (the shared train) the snapshot also counts the pull requests - merged outside the train since `--train-since`, and `--train-dir D:\Development\Tools\ci-train` + merged outside the train since `--train-since`, and `--train-dir ` adds a section on the installed train: age of its log (silent after 90 minutes) and whether its script differs from the one in `ci-shared` main. diff --git a/report/__pycache__/ci_report.cpython-312.pyc b/report/__pycache__/ci_report.cpython-312.pyc deleted file mode 100644 index 2d5d36100b13024ffedb8efe061e394ed3a33547..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 32459 zcmd7533OCfnkM*O?E9vDK?(r^1!!g8u@L(r3<$7gV-e_uLK&oKE|EyleoIN$~8UH6G6zSa1=d*r|NW%&zU(#wwzsQ&&)aV z{r4>qAwssh`kXoQK=<8u_vOF;{qO((_m6*Pw_7+oPtC;p{-lHB{*FGBM=yE!1&xN| zZgB$F$qBrm>E|zNIyF4`wf)*oEqm)a_3UlvG_bd^)5PB9PBVL3IxXyN?XHD3RU7fDW?oK!RHuQTg7jzcDZ|p1-Or1r7xwBZXbe0IUg7sxxXQ{AC zu;E>%;SO+u{bf#YyoYwu(^(#Hu}~*MT}tSCQY6<|A*>eM$XO}W2_C$c2|l3!?6T6uvRF-+bh%y#dy~UC4yEc)o_93N*RK-M{nkS$UmV$D0^Aoxk7GHIa*ZlM2l9M zIiWGPG@(hTM7~;~Sy+ZPtP)y;D!f+<>x62&>yTr8ZVvhqHV9ti@(DFBbDe91jly!I zT`Q~?HVG>bULR->R$i*(IFWi|>w8`vlB^fP>y=)<$4e1BH>w@g`ZoK=v>bOf5V+Jo z>TNsZy%_NKhc9}?z|f!=-sbJ`2m6P`fLHW~1Ktax-fsVJC{XVeh7k}P90=8WuM7u< z1Kx1(a=_~!5WIeGXuv-dx;Pm24)%D%gMxpw(PHu985;FAtoL>YyQH!k>AQja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wJtx1)x!2kbTU;)Ff82RSQz^0t% zP|VkrxV|)5i|Wg6mrb=z56@aR!qOYY=|?a9C}pxu8s4mYr~g+Q?(2Tz_|TDDf8Z0( zC#RCDP9)1tCR`^Irjr;bB#yik!Hd44Ht+K8z;8C_jn`xasM-KTAN(Y;WS^b%UoVe|j?s;;ubNo{T05#w@3Z!5= zRxk>Bi_)pZe`^)OjkITx`~$K7T~1MvlDrnq&(V(_{5euatSp|HJwGS@it=`n!BSeoE&-up%Iq~K+5Q`k)UF6L)ecO{mMkoF#Ac$E)l362E?hjH^}$LDTW$8KMxb-4BsUSw50ZQ3ERW_O7{MMC`NLjMUa#7R8= zrN++depkiuEB=mi{w-JZx158y*1zT4?7!tda4Y{;uI@i@rH}2s%!~W7Yv&7?w~+I!lqvv< zH#iqcSm+B<7mWOxc@B=;0s5@u+)eZ5a^3*t<#{dMXbvhil22+4`7E5ly8LF8f|WwQ>eLu{&qAS| uul(9|jOXq1=QX&YJP~=QElcTa<841X_>+UzJ6<{Ssjd)ojINxqyZ>L`6~m4I diff --git a/train/automerge.py b/train/automerge.py index 186bd33..15b1cc8 100644 --- a/train/automerge.py +++ b/train/automerge.py @@ -59,7 +59,7 @@ class RepoConfig: gate_check: str = "Gate / Gate" require_seal: bool = False base: str = "main" - # How `gh pr merge` merges; a repository may allow only some methods (contrast-viewer: squash). + # How `gh pr merge` merges; a repository may allow only some methods (for example only squash). merge_method: str = "merge" diff --git a/train/install.ps1 b/train/install.ps1 index 2240da0..df25723 100644 --- a/train/install.ps1 +++ b/train/install.ps1 @@ -6,7 +6,7 @@ # powershell -NoProfile -ExecutionPolicy Bypass -File train\install.ps1 -Remove # # The script is copied to $Destination, so the task does not depend on which branch a checkout is -# on (the crm-platform train learned this the hard way). Run this again after automerge.py changes. +# on (learned the hard way). Run this again after automerge.py changes. # repos.json is created from repos.example.json only when it does not exist; it is never overwritten. # The task uses the owner's `gh` login; nothing else is stored. param( @@ -28,7 +28,7 @@ gh auth status *> $null if ($LASTEXITCODE -ne 0) { throw 'gh is not signed in: run gh auth login' } # The real pythonw.exe, not the `pyw` launcher: under the task scheduler the launcher exited with -# code 2 and wrote nothing (crm-platform, 30/09/2026), while the interpreter itself runs fine. +# code 2 and wrote nothing, while the interpreter itself runs fine. $python = (py -3 -c "import sys;print(sys.executable)") $pythonw = Join-Path (Split-Path $python) 'pythonw.exe' if (-not (Test-Path $pythonw)) { throw "pythonw.exe not found at $pythonw" } diff --git a/train/repos.example.json b/train/repos.example.json index be14e09..0093808 100644 --- a/train/repos.example.json +++ b/train/repos.example.json @@ -2,9 +2,9 @@ "label": "automerge", "needs_human_label": "needs-human", "repos": [ - { "repo": "naindev-contrast3d/contrast3d-platform" }, - { "repo": "naindev-contrast3d/contrast3d-bot" }, - { "repo": "naindev-contrast3d/contrast-viewer", "merge_method": "squash" }, - { "repo": "naindev-contrast3d/gha-local-runners" } + { "repo": "your-org/service-a" }, + { "repo": "your-org/service-b" }, + { "repo": "your-org/web-app", "merge_method": "squash" }, + { "repo": "your-org/tooling" } ] } From 308f8469e6fad8755a5b69829fe8caf0e3205151 Mon Sep 17 00:00:00 2001 From: naindev <193035803+Nain9Dev@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:15:10 +0100 Subject: [PATCH 2/2] refactor: move the organisation-specific tooling out of this public repository Remove the CI report, the runner watchdog, the standards audit and the merge train, with their tests and the step that ran them. They work on one organisation's own repositories and one of their files names them, which does not belong in a public repository. They are kept elsewhere, unchanged. The README keeps the four reusable workflows. The zizmor ignore keys follow the lines that moved in ci.yml. --- .github/workflows/ci.yml | 3 - .github/zizmor.yml | 4 +- README.md | 80 +--- report/ci_report.py | 619 ------------------------------- report/install-runner-watch.ps1 | 78 ---- report/install-weekly-report.ps1 | 69 ---- report/runner_watch.py | 257 ------------- report/weekly_report.py | 171 --------- standards/audit.py | 483 ------------------------ standards/bootstrap.py | 226 ----------- standards/standards.json | 43 --- tests/test_audit.py | 526 -------------------------- tests/test_automerge.py | 612 ------------------------------ tests/test_bootstrap.py | 203 ---------- tests/test_ci_report.py | 549 --------------------------- tests/test_runner_watch.py | 239 ------------ tests/test_weekly_report.py | 191 ---------- train/automerge.py | 565 ---------------------------- train/install.ps1 | 78 ---- train/repos.example.json | 10 - 20 files changed, 6 insertions(+), 5000 deletions(-) delete mode 100644 report/ci_report.py delete mode 100644 report/install-runner-watch.ps1 delete mode 100644 report/install-weekly-report.ps1 delete mode 100644 report/runner_watch.py delete mode 100644 report/weekly_report.py delete mode 100644 standards/audit.py delete mode 100644 standards/bootstrap.py delete mode 100644 standards/standards.json delete mode 100644 tests/test_audit.py delete mode 100644 tests/test_automerge.py delete mode 100644 tests/test_bootstrap.py delete mode 100644 tests/test_ci_report.py delete mode 100644 tests/test_runner_watch.py delete mode 100644 tests/test_weekly_report.py delete mode 100644 train/automerge.py delete mode 100644 train/install.ps1 delete mode 100644 train/repos.example.json diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f712d78..83cb5d8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -62,9 +62,6 @@ jobs: - name: Supply-chain workflow tests run: bash tests/supply-chain.test.sh - - name: Merge train tests - run: python3 -m unittest discover -s tests -p "test_*.py" - # Fixture caller of the reusable supply-chain scan, on the real event: this repository scans itself # with the same file its consumers call. supply-chain: diff --git a/.github/zizmor.yml b/.github/zizmor.yml index 84a62d3..f50cb2f 100644 --- a/.github/zizmor.yml +++ b/.github/zizmor.yml @@ -6,5 +6,5 @@ rules: # Keyed by line number: update these when lines are added above them in ci.yml. - ci.yml:22 - ci.yml:31 - - ci.yml:74 - - ci.yml:81 + - ci.yml:71 + - ci.yml:78 diff --git a/README.md b/README.md index b87b2f3..776dbab 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,12 @@ # ci-shared -Reusable GitHub Actions workflows and a merge-train script shared by the Contrast3D repositories. +Reusable GitHub Actions workflows shared by the maintainers' repositories. Status: in progress. The design is kept in the maintainers' own repository. Licensed under MIT. +Tooling that is specific to one organisation (CI reports, a standards audit, a merge train) is not +here: it lives in a private repository, because it works on that organisation's own repositories. + ## Contents - `preflight` (available): checks required tools, a reachable Docker daemon, memory and disk on the @@ -29,81 +32,6 @@ Status: in progress. The design is kept in the maintainers' own repository. Lice (no base commit, base not fetchable, empty diff, global pattern matched) every area is reported as changed. Skipped jobs must be declared in the gate's `allowed-skipped`. -- `train/automerge.py` (available): the merge train. It is not a workflow: a scheduled task on the - owner's desktop runs it with `gh`. One cycle goes over every repository of a JSON list - (`train/repos.example.json`), and per repository merges at most one pull request labelled - `automerge` whose gate check is green (plus the `ci-ok/` seal when `require_seal` is set) and - whose head contains the base branch. A stale head gets the base merged in through the API, without - force-push; a conflict gets `needs-human` and loses `automerge`. `merge_method` (`merge`, - `squash` or `rebase`, default `merge`) follows what each repository allows. Each cycle it also - logs once any workflow run that has been queued longer than `queue_alert_minutes` (default 30): - a runner that is offline or saturated otherwise holds jobs for up to 24 hours before they fail. - The runs already reported are remembered in `queue-alerts.json` beside the configuration. - After every merge it comments `` on the pull request, so a merge made - around the train can be counted, and it writes a `heartbeat:` line (repositories, labelled pull - requests, version of the script) at most once an hour as proof of life. - `--dry-run` changes nothing. - Tests: `python3 -m unittest discover -s tests`. - -- `train/install.ps1` (available): installs the train as the scheduled task `CI train`, every two - minutes, from its install directory (`-Destination`; a copy of `automerge.py`, a `repos.json` created from - the example only if missing, and `train.log`). Run it from a normal PowerShell window of the owner's - session; `-Remove` retires the task. - -- `report/ci_report.py` (available): the CI health report. Per repository and period it prints the - failure rate of conclusive runs, the share of failures caused by the infrastructure (a job that - never reached its steps, or the shared preflight) and not the code, the median duration and the - median queue time, followed by a snapshot of today: runners online, offline and busy, queued runs - and open pull requests. Use it to plan from the current state, not from memory: - `py -3 report/ci_report.py --config train/repos.json --repo / --days 7`. - For the repositories of `--config` (the shared train) the snapshot also counts the pull requests - merged outside the train since `--train-since`, and `--train-dir ` - adds a section on the installed train: age of its log (silent after 90 minutes) and whether its - script differs from the one in `ci-shared` main. - -- `report/weekly_report.py` (available): the weekly report to a file. It runs `ci_report.py` over every - private repository of the organisation that is not archived and writes `ci-report-.md` (and - `latest.md`) to `--out-dir`. When the week deviates, with a failure rate above 25 % over at least - five runs, a p90 wait for a runner above five minutes, or more than a fifth of the failures caused by - the infrastructure, the deviations go at the top of the report and one toast is raised through - `--notify`; a healthy week raises nothing. The thresholds are options. `report/install-weekly-report.ps1` - registers it as the task `CI weekly report` (Mondays 08:00), from a normal PowerShell window of the - owner's session. - -- `report/runner_watch.py` (available): the runner watchdog. The report says how the queue behaved - over a period; this says that it is wrong now. Run from a scheduled task every few minutes - (`py -3 report/runner_watch.py --org naindev-contrast3d --notify `), it reads - the runners of the organisation and of each private repository, plus the queued runs, and raises one - toast per finding: a runner offline for `--offline-min` minutes (default 10; GitHub does not say - since when, so the first sighting is remembered in a state file) or a run queued for `--queue-min` - (default 15). A finding is reported once and again only after it has cleared; `--ignore NAME` mutes - a runner that is offline on purpose; an unreadable answer is skipped, never reported. Exit code 1 - when it reported something. `report/install-runner-watch.ps1` registers it as the scheduled task - `CI runner watch` (every five minutes, hidden, the owner's `gh` login, toasts through - `workstation-maintenance\notify.ps1`); run it from a normal PowerShell window of the owner's - session, with `-Ignore ` for a runner that is offline on purpose, and `-Remove` to retire it. - `--until 2026-10-14T11:00` ends the period in the past, so a baseline can be reproduced after later - changes; `--limit` raises the number of runs read per repository (default 300). - -- `standards/audit.py` (available): audits every repository of the organisation against - `standards/standards.json` and prints each deviation as `error`, `warning` or `info`: branch - deletion after merge, Dependabot, CODEOWNERS, secret scanning and a recognised license on public - repositories, a CI that calls the shared gate pinned by a full SHA with a `# vX.Y.Z` comment, too - many leftover branches, the organisation's two-factor requirement, Dependabot alerts that are off - or open past their deadline (critical 7, high 30, medium 90 days, only when a fix exists), - writable deploy keys, webhooks without a secret, an unprotected default branch on public - repositories, and an organisation that does not restrict actions to a list pinned by SHA. The - audit only reports; the owner changes keys, webhooks and two-factor. An exception names a - repository and a rule, gives a reason and expires; an expired one is itself an error. - `py -3 standards/audit.py [--fail-on error]`, or `report/ci_report.py --audit` to append it to the - weekly report. - -- `standards/bootstrap.py` (available): applies the organisation's repository settings to a new - repository: branch deletion after merge, secret scanning and push protection where they are free, - Dependabot alerts and security updates, and the `automerge` and `needs-human` labels the merge - train uses. A dry run by default; `--apply` makes the changes. - `py -3 standards/bootstrap.py owner/name [--apply]`. - ## Rules - No secrets, no business logic and no repository-specific values: everything comes in as an input. diff --git a/report/ci_report.py b/report/ci_report.py deleted file mode 100644 index 25838dc..0000000 --- a/report/ci_report.py +++ /dev/null @@ -1,619 +0,0 @@ -"""Weekly CI health report: failure rate by cause, durations, queue time and a snapshot of today. - - py -3 ci_report.py --repo owner/name --repo owner/other --days 7 - py -3 ci_report.py --config ..\\train\\repos.json --days 30 --output report.md - -Per repository, over the period: conclusive runs (success or failure) of one workflow, how many -failed, which share of those failures was the infrastructure and not the code, the median duration -and the median time a run waited for its first job to start. Cancelled runs are counted apart, never -as failures. The snapshot reports what is true now (runners, queue, open pull requests), because a -plan made from remembered state is how stale diagnoses happen. - -A failed run counts as infrastructure only when every failed job never reached its own steps -(`Set up job`, a job with no steps) or is the shared runner preflight. Anything else is code. -""" - -from __future__ import annotations - -import argparse -import datetime as dt -import hashlib -import importlib.util -import json -import statistics -import subprocess -import sys -from collections.abc import Callable -from dataclasses import dataclass, field -from pathlib import Path - -RUN_FIELDS = "databaseId,conclusion,status,workflowName,createdAt,startedAt,updatedAt,event,headBranch" -INFRA_STEPS = ("Set up job", "Complete job") -# The comment the merge train writes on every pull request it merges (train/automerge.py). -TRAIN_MARK = "" -TRAIN_SILENT_AFTER_MIN = 90 # the train writes a heartbeat every 60 minutes - - -def text_version(text: str) -> str: - """A short fingerprint of a script, the same for LF and CRLF copies (as in the train).""" - return hashlib.sha256(text.replace("\r\n", "\n").encode("utf-8")).hexdigest()[:12] - - -def run_gh(command: list[str]) -> str: - # Every command is built in this file from fixed words and GitHub's own numbers. - no_window = getattr(subprocess, "CREATE_NO_WINDOW", 0) - return subprocess.run( - command, check=True, capture_output=True, text=True, creationflags=no_window - ).stdout - - -class Github: - """The few GitHub reads the report needs, over the `gh` command line.""" - - def __init__(self, run: Callable[[list[str]], str] = run_gh): - self._run = run - - def runs(self, repo: str, limit: int) -> list[dict]: - out = self._run( - [ - "gh", - "run", - "list", - "--repo", - repo, - "--limit", - str(limit), - "--json", - RUN_FIELDS, - ] - ) - return json.loads(out or "[]") - - def jobs(self, repo: str, run_id: int) -> list[dict]: - out = self._run( - ["gh", "run", "view", str(run_id), "--repo", repo, "--json", "jobs"] - ) - return json.loads(out or "{}").get("jobs", []) - - def job_timings(self, repo: str, run_id: int) -> list[dict]: - """The jobs of a run with `created_at` (when each became ready) and `started_at`: the - difference is the time it waited for a runner. `gh run view` does not give the former.""" - try: - out = self._run( - ["gh", "api", f"repos/{repo}/actions/runs/{run_id}/jobs?per_page=100"] - ) - except subprocess.CalledProcessError: - return [] # the run is gone or unreadable: no figure is better than a wrong one - return json.loads(out or "{}").get("jobs", []) - - def runners(self, repo: str) -> list[dict]: - try: - out = self._run(["gh", "api", f"repos/{repo}/actions/runners"]) - except subprocess.CalledProcessError: - return [] # no permission to list runners, or none registered - return json.loads(out or "{}").get("runners", []) - - def queued_runs(self, repo: str) -> list[dict]: - out = self._run( - [ - "gh", - "run", - "list", - "--repo", - repo, - "--status", - "queued", - "--json", - "databaseId,createdAt", - "--limit", - "50", - ] - ) - return json.loads(out or "[]") - - def merged_prs(self, repo: str, limit: int) -> list[dict]: - out = self._run( - [ - "gh", - "pr", - "list", - "--repo", - repo, - "--state", - "merged", - "--limit", - str(limit), - "--json", - "number,mergedAt,comments", - ] - ) - return json.loads(out or "[]") - - def file_text(self, repo: str, path: str) -> str | None: - try: - return self._run( - [ - "gh", - "api", - "-H", - "Accept: application/vnd.github.raw+json", - f"repos/{repo}/contents/{path}", - ] - ) - except subprocess.CalledProcessError: - return None - - def open_prs(self, repo: str) -> list[dict]: - out = self._run( - [ - "gh", - "pr", - "list", - "--repo", - repo, - "--state", - "open", - "--json", - "number,labels,createdAt", - "--limit", - "100", - ] - ) - return json.loads(out or "[]") - - -@dataclass -class RepoStats: - repo: str - conclusive: int = 0 - failed: int = 0 - cancelled: int = 0 - infra_failures: int = 0 - median_duration_s: float | None = None - median_queue_s: float | None = None - runners_online: int = 0 - runners_busy: int = 0 - runners_offline: int = 0 - queued_now: int = 0 - oldest_queued_min: int | None = None - open_prs: int = 0 - automerge_prs: int = 0 - # Only for repositories served by the shared merge train; None elsewhere. - merged_total: int | None = None - merged_by_hand: int | None = None - # Time each job of the sampled runs waited for a runner (created_at to started_at). - jobs_sampled: int = 0 - job_wait_median_s: float | None = None - job_wait_p90_s: float | None = None - job_wait_max_s: float | None = None - # (job name, median wait in seconds, jobs seen), the three that waited longest. - slowest_jobs: list[tuple[str, float, int]] = field(default_factory=list) - - @property - def fail_rate(self) -> float | None: - return self.failed / self.conclusive if self.conclusive else None - - @property - def infra_share(self) -> float | None: - return self.infra_failures / self.failed if self.failed else None - - -def classify_failure(jobs: list[dict]) -> str: - """'infra' when every failed job never reached its own steps, otherwise 'code'.""" - failed = [j for j in jobs if j.get("conclusion") == "failure"] - if not failed: - return "code" - return "infra" if all(_is_infra(j) for j in failed) else "code" - - -def _is_infra(job: dict) -> bool: - if "preflight" in (job.get("name") or "").lower(): - return True - failed_steps = [ - s["name"] for s in job.get("steps", []) if s.get("conclusion") == "failure" - ] - return not failed_steps or failed_steps[0] in INFRA_STEPS - - -def _parse(moment: str) -> dt.datetime: - return dt.datetime.fromisoformat(moment) - - -def job_waits(timings: list[dict]) -> list[tuple[str, float]]: - """(job name, seconds it waited for a runner) for the jobs that actually started.""" - waits = [] - for item in timings: - if item.get("conclusion") == "skipped": - continue - created, started = item.get("created_at"), item.get("started_at") - if not created or not started: - continue - seconds = (_parse(started) - _parse(created)).total_seconds() - waits.append((item.get("name") or "unnamed job", max(seconds, 0))) - return waits - - -def percentile(values: list[float], pct: int) -> float | None: - """Nearest-rank percentile; None for no values.""" - if not values: - return None - ordered = sorted(values) - rank = max(1, -(-len(ordered) * pct // 100)) # ceil without floats - return ordered[min(rank, len(ordered)) - 1] - - -def parse_moment(text: str) -> dt.datetime: - """A date, or a date and time, read as UTC.""" - moment = dt.datetime.fromisoformat(text) - return moment if moment.tzinfo else moment.replace(tzinfo=dt.UTC) - - -def collect( - gh, - repo: str, - workflow: str, - days: int, - now: dt.datetime, - sample: int = 30, - until: dt.datetime | None = None, - limit: int = 300, - train_repos: frozenset[str] | set[str] = frozenset(), - train_since: dt.datetime | None = None, -) -> RepoStats: - """Metrics for runs created in the `days` before `until` (default `now`). - - The snapshot (runners, queue, pull requests) is always about `now`. - """ - end = until or now - since = end - dt.timedelta(days=days) - runs = [ - r - for r in gh.runs(repo, limit) - if r.get("workflowName") == workflow and since <= _parse(r["createdAt"]) <= end - ] - conclusive = [r for r in runs if r.get("conclusion") in ("success", "failure")] - stats = RepoStats(repo=repo) - stats.conclusive = len(conclusive) - stats.cancelled = sum(1 for r in runs if r.get("conclusion") == "cancelled") - - for r in conclusive: - if r["conclusion"] != "failure": - continue - stats.failed += 1 - if classify_failure(gh.jobs(repo, r["databaseId"])) == "infra": - stats.infra_failures += 1 - - durations = [ - (_parse(r["updatedAt"]) - _parse(r["startedAt"])).total_seconds() - for r in conclusive - ] - if durations: - stats.median_duration_s = statistics.median(durations) - - waits = [] - for r in sorted(conclusive, key=lambda item: item["createdAt"], reverse=True)[ - :sample - ]: - starts = [ - j["startedAt"] for j in gh.jobs(repo, r["databaseId"]) if j.get("startedAt") - ] - if starts: - first = min(_parse(s) for s in starts) - waits.append((first - _parse(r["createdAt"])).total_seconds()) - if waits: - stats.median_queue_s = statistics.median(waits) - - by_job: dict[str, list[float]] = {} - for r in sorted(conclusive, key=lambda item: item["createdAt"], reverse=True)[ - :sample - ]: - for name, seconds in job_waits(gh.job_timings(repo, r["databaseId"])): - by_job.setdefault(name, []).append(seconds) - every = [seconds for group in by_job.values() for seconds in group] - if every: - stats.jobs_sampled = len(every) - stats.job_wait_median_s = statistics.median(every) - stats.job_wait_p90_s = percentile(every, 90) - stats.job_wait_max_s = max(every) - ranked = sorted( - ((n, statistics.median(g), len(g)) for n, g in by_job.items()), - key=lambda item: (-item[1], item[0]), - ) - stats.slowest_jobs = ranked[:3] - - for runner in gh.runners(repo): - if runner.get("status") == "online": - stats.runners_online += 1 - stats.runners_busy += 1 if runner.get("busy") else 0 - else: - stats.runners_offline += 1 - - queue = gh.queued_runs(repo) - stats.queued_now = len(queue) - if queue: - stats.oldest_queued_min = int( - max((now - _parse(q["createdAt"])).total_seconds() for q in queue) // 60 - ) - - prs = gh.open_prs(repo) - stats.open_prs = len(prs) - stats.automerge_prs = sum( - 1 - for p in prs - if "automerge" in {label["name"] for label in p.get("labels", [])} - ) - - if repo in train_repos: - floor = max(since, train_since) if train_since else since - merged = [ - m for m in gh.merged_prs(repo, 200) if floor <= _parse(m["mergedAt"]) <= end - ] - stats.merged_total = len(merged) - stats.merged_by_hand = sum( - 1 - for m in merged - if not any( - TRAIN_MARK in (c.get("body") or "") for c in m.get("comments", []) - ) - ) - return stats - - -@dataclass -class TrainHealth: - log_age_min: ( - int | None - ) # minutes since the log was last written; None without a log - silent: bool # no log line for too long - copy: str # current, stale, missing or unknown - installed_version: str | None = None - repository_version: str | None = None - - -def train_health( - train_dir: Path, - gh, - now: dt.datetime, - repo: str = "naindev-contrast3d/ci-shared", -) -> TrainHealth: - """Is the installed train alive and is it the script of `ci-shared` main?""" - train_dir = Path(train_dir) - script = train_dir / "automerge.py" - log = train_dir / "train.log" - - age = None - if log.exists(): - modified = dt.datetime.fromtimestamp(log.stat().st_mtime, dt.UTC) - age = int((now - modified).total_seconds() // 60) - silent = age is not None and age > TRAIN_SILENT_AFTER_MIN - - if not script.exists(): - return TrainHealth(age, silent, "missing") - installed = text_version(script.read_text(encoding="utf-8")) - published = gh.file_text(repo, "train/automerge.py") - if published is None: - return TrainHealth(age, silent, "unknown", installed_version=installed) - current = text_version(published) - return TrainHealth( - age, silent, "current" if installed == current else "stale", installed, current - ) - - -def render_train(health: TrainHealth) -> str: - lines = ["## Merge train", ""] - if health.copy == "missing": - lines.append("- Installed copy not found (the train is not installed here).") - return "\n".join(lines) - if health.log_age_min is None: - lines.append("- No log yet.") - elif health.silent: - lines.append( - f"- Warning: no log line for {health.log_age_min} min " - f"(the train writes a heartbeat every 60 minutes)." - ) - else: - lines.append(f"- Last log activity {health.log_age_min} min ago.") - if health.copy == "current": - lines.append("- The installed script matches ci-shared main.") - elif health.copy == "stale": - lines.append( - f"- Warning: the installed script differs from ci-shared main " - f"(installed {health.installed_version}, repository {health.repository_version})." - ) - else: - lines.append("- Could not read the script of ci-shared main to compare.") - return "\n".join(lines) - - -def fmt_duration(seconds: float | None) -> str: - if seconds is None: - return "-" - total = round(seconds) - if total < 60: - return f"{total}s" - if total < 3600: - return f"{total // 60}m{total % 60:02d}s" - return f"{total // 3600}h{(total % 3600) // 60:02d}m" - - -def _pct(value: float | None) -> str: - return "-" if value is None else f"{round(value * 100)}%" - - -def render( - stats: list[RepoStats], - days: int, - now: dt.datetime, - until: dt.datetime | None = None, -) -> str: - end = until or now - since = (end - dt.timedelta(days=days)).strftime("%Y-%m-%d") - lines = [ - "# CI health report", - "", - ( - f"Period: {since} to {end.strftime('%Y-%m-%d')} ({days} days). " - "Conclusive runs only; cancelled runs are not failures." - + ( - f" The snapshot is about now ({now.strftime('%Y-%m-%d %H:%M')} UTC)." - if until - else "" - ) - ), - "", - "| Repository | Runs | Failed | Fail rate | Infra share | Median duration | Median queue |", - "| --- | ---: | ---: | ---: | ---: | ---: | ---: |", - ] - for s in stats: - lines.append( - f"| {s.repo} | {s.conclusive} | {s.failed} | {_pct(s.fail_rate)} | {_pct(s.infra_share)}" - f" | {fmt_duration(s.median_duration_s)} | {fmt_duration(s.median_queue_s)} |" - ) - if any(s.jobs_sampled for s in stats): - lines += [ - "", - "## Queue time per job", - "", - "Time each job of the most recent runs waited for a runner, from the moment it was " - "ready to the moment it started. A job waits when every runner slot is taken, so a " - "high figure with few runners online asks for more slots; one with plenty of idle " - "runners points at the runner service instead.", - "", - "| Repository | Jobs | Median wait | p90 | Max | Slowest to start | Runners online |", - "| --- | ---: | ---: | ---: | ---: | --- | ---: |", - ] - for s in stats: - slowest = ", ".join( - f"{name} ({fmt_duration(wait)})" for name, wait, _ in s.slowest_jobs[:1] - ) - lines.append( - f"| {s.repo} | {s.jobs_sampled} | {fmt_duration(s.job_wait_median_s)}" - f" | {fmt_duration(s.job_wait_p90_s)} | {fmt_duration(s.job_wait_max_s)}" - f" | {slowest or '-'} | {s.runners_online} |" - ) - lines += ["", "## Snapshot", ""] - for s in stats: - lines.append(f"### {s.repo}") - if s.runners_online or s.runners_offline: - lines.append( - f"- Runners: {s.runners_online} online ({s.runners_busy} busy), {s.runners_offline} offline" - ) - else: - lines.append("- Runners: none registered (GitHub-hosted)") - oldest = ( - f" (oldest {s.oldest_queued_min} min)" - if s.oldest_queued_min is not None - else "" - ) - lines.append(f"- Queued now: {s.queued_now}{oldest}") - lines.append( - f"- Open pull requests: {s.open_prs} ({s.automerge_prs} labelled automerge)" - ) - if s.merged_by_hand is not None: - lines.append( - f"- Merged outside the train: {s.merged_by_hand} of {s.merged_total}" - ) - lines.append("") - return "\n".join(lines) - - -def load_audit(): - """The standards audit module, found beside this report (`../standards/audit.py`).""" - path = Path(__file__).resolve().parent.parent / "standards" / "audit.py" - spec = importlib.util.spec_from_file_location("standards_audit", path) - module = importlib.util.module_from_spec(spec) - sys.modules["standards_audit"] = module # dataclasses look the module up by name - spec.loader.exec_module(module) - return module - - -def audit_section(audit_text: str) -> str: - """The audit report as a section of this one: its title becomes a second-level heading.""" - lines = audit_text.split("\n") - if lines and lines[0] == "# Standards audit": - lines[0] = "## Standards audit" - return "\n".join(lines) - - -def main(argv: list[str] | None = None) -> int: - parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - parser.add_argument( - "--repo", action="append", default=[], help="owner/name; repeatable" - ) - parser.add_argument("--config", help="train repos.json: its repositories are added") - parser.add_argument("--days", type=int, default=7) - parser.add_argument("--workflow", default="CI") - parser.add_argument( - "--until", - help="end of the period, UTC (2026-10-14 or 2026-10-14T11:00); default now. " - "Use it to reproduce a baseline after later changes.", - ) - parser.add_argument( - "--limit", - type=int, - default=300, - help="runs read per repository (gh allows up to 1000)", - ) - parser.add_argument( - "--audit", - action="store_true", - help="append the standards audit of the organisation", - ) - parser.add_argument( - "--train-dir", - help="folder of the installed merge train (automerge.py and train.log): adds its health", - ) - parser.add_argument( - "--train-since", - help="UTC date the shared train started serving the repositories of --config; " - "earlier merges are not counted as made around it", - ) - parser.add_argument("--output", help="write the report here instead of printing it") - args = parser.parse_args(argv) - - repos = list(args.repo) - train_repos: set[str] = set() - if args.config: - data = json.loads(Path(args.config).read_text(encoding="utf-8")) - train_repos = {entry["repo"] for entry in data.get("repos", [])} - repos += sorted(train_repos) - if not repos: - print("give at least one --repo or a --config", file=sys.stderr) - return 2 - - now = dt.datetime.now(dt.UTC) - gh = Github() - until = parse_moment(args.until) if args.until else None - train_since = parse_moment(args.train_since) if args.train_since else None - stats = [ - collect( - gh, - repo, - args.workflow, - args.days, - now, - until=until, - limit=args.limit, - train_repos=train_repos, - train_since=train_since, - ) - for repo in repos - ] - text = render(stats, args.days, now, until=until) - if args.train_dir: - text += "\n\n" + render_train(train_health(Path(args.train_dir), gh, now)) - if args.audit: - audit = load_audit() - standard_path = Path(audit.__file__).with_name("standards.json") - text += "\n\n" + audit_section( - audit.render(audit.run(standard_path, now=now), now) - ) - if args.output: - Path(args.output).write_text(text + "\n", encoding="utf-8") - else: - print(text) - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/report/install-runner-watch.ps1 b/report/install-runner-watch.ps1 deleted file mode 100644 index 9a3c4e8..0000000 --- a/report/install-runner-watch.ps1 +++ /dev/null @@ -1,78 +0,0 @@ -# Installs the runner watchdog on the desktop: every five minutes, one cycle of runner_watch.py, and a -# Windows toast when a runner of the organisation is offline or a run waits too long for one. Run it -# from a normal PowerShell window of the owner's session: scheduled tasks created from a sandboxed -# or elevated shell can be private to that shell. -# -# powershell -NoProfile -ExecutionPolicy Bypass -File report\install-runner-watch.ps1 -# powershell -NoProfile -ExecutionPolicy Bypass -File report\install-runner-watch.ps1 -Remove -# -# The scripts are copied to $Destination, so the task does not depend on which branch a checkout is -# on; run this again after runner_watch.py changes. The task uses the owner's `gh` login; nothing -# else is stored. State lives in $Destination\runner-watch.json. -param( - [string]$Organisation = 'naindev-contrast3d', - [string]$Destination = 'D:\Development\Tools\ci-train\watch', - [string]$Notify = 'D:\Development\Tools\workstation-maintenance\notify.ps1', - # Runners that are offline on purpose and must never raise a toast. - [string[]]$Ignore = @(), - [int]$OfflineMinutes = 10, - [int]$QueueMinutes = 15, - [switch]$Remove -) - -$ErrorActionPreference = 'Stop' -$taskName = 'CI runner watch' - -if ($Remove) { - Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue - Write-Host "Task '$taskName' removed. Files in $Destination are left in place." - exit 0 -} - -if (-not (Get-Command gh -ErrorAction SilentlyContinue)) { throw 'gh is not installed' } -gh auth status *> $null -if ($LASTEXITCODE -ne 0) { throw 'gh is not signed in: run gh auth login' } -if (-not (Test-Path $Notify)) { throw "notify.ps1 not found at $Notify (pass -Notify)" } - -# The real pythonw.exe, not the `pyw` launcher (see train\install.ps1 for why). -$python = (py -3 -c "import sys;print(sys.executable)") -$pythonw = Join-Path (Split-Path $python) 'pythonw.exe' -if (-not (Test-Path $pythonw)) { throw "pythonw.exe not found at $pythonw" } - -New-Item -ItemType Directory -Force -Path $Destination | Out-Null -foreach ($file in 'runner_watch.py', 'ci_report.py') { - Copy-Item -Force (Join-Path $PSScriptRoot $file) (Join-Path $Destination $file) -} -$script = Join-Path $Destination 'runner_watch.py' -$state = Join-Path $Destination 'runner-watch.json' - -$arguments = "`"$script`" --org $Organisation --notify `"$Notify`" --state `"$state`"" + - " --offline-min $OfflineMinutes --queue-min $QueueMinutes" -foreach ($name in $Ignore) { $arguments += " --ignore `"$name`"" } - -# pythonw: no console window flashing every five minutes. No -WorkingDirectory (see the train). -$action = New-ScheduledTaskAction -Execute $pythonw -Argument $arguments -$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes(1) ` - -RepetitionInterval (New-TimeSpan -Minutes 5) -$settings = New-ScheduledTaskSettingsSet ` - -MultipleInstances IgnoreNew ` - -ExecutionTimeLimit (New-TimeSpan -Minutes 3) ` - -AllowStartIfOnBatteries ` - -DontStopIfGoingOnBatteries ` - -StartWhenAvailable -$principal = New-ScheduledTaskPrincipal -UserId "$env:USERDOMAIN\$env:USERNAME" ` - -LogonType Interactive -RunLevel Limited - -Register-ScheduledTask ` - -TaskName $taskName ` - -Action $action ` - -Trigger $trigger ` - -Settings $settings ` - -Principal $principal ` - -Description "Toast when a runner of $Organisation is offline for $OfflineMinutes min or a run is queued for $QueueMinutes min." ` - -Force | Out-Null - -Write-Host "Task '$taskName' installed: every 5 minutes." -Write-Host " State: $state" -Write-Host " Try now: py -3 `"$script`" --org $Organisation --state `"$state`"" -Write-Host " Remove: report\install-runner-watch.ps1 -Remove" diff --git a/report/install-weekly-report.ps1 b/report/install-weekly-report.ps1 deleted file mode 100644 index 363c043..0000000 --- a/report/install-weekly-report.ps1 +++ /dev/null @@ -1,69 +0,0 @@ -# Installs the weekly CI report on the desktop: every Monday at 08:00 it writes the report of the -# organisation to a file and raises a Windows toast only when the week deviates. Run it from a normal -# PowerShell window of the owner's session: scheduled tasks created from a sandboxed or elevated shell -# can be private to that shell. -# -# powershell -NoProfile -ExecutionPolicy Bypass -File report\install-weekly-report.ps1 -# powershell -NoProfile -ExecutionPolicy Bypass -File report\install-weekly-report.ps1 -Remove -# -# The scripts are copied to $Destination, so the task does not depend on which branch a checkout is on; -# run this again after weekly_report.py changes. The task uses the owner's `gh` login; nothing else is -# stored. Reports land in $Destination\reports as ci-report-.md, with a copy as latest.md. -param( - [string]$Organisation = 'naindev-contrast3d', - [string]$Destination = 'D:\Development\Tools\ci-train\weekly', - [string]$Notify = 'D:\Development\Tools\workstation-maintenance\notify.ps1', - [switch]$Remove -) - -$ErrorActionPreference = 'Stop' -$taskName = 'CI weekly report' - -if ($Remove) { - Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue - Write-Host "Task '$taskName' removed. Files in $Destination are left in place." - exit 0 -} - -if (-not (Get-Command gh -ErrorAction SilentlyContinue)) { throw 'gh is not installed' } -gh auth status *> $null -if ($LASTEXITCODE -ne 0) { throw 'gh is not signed in: run gh auth login' } -if (-not (Test-Path $Notify)) { throw "notify.ps1 not found at $Notify (pass -Notify)" } - -# The real pythonw.exe, not the `pyw` launcher (see train\install.ps1 for why). -$python = (py -3 -c "import sys;print(sys.executable)") -$pythonw = Join-Path (Split-Path $python) 'pythonw.exe' -if (-not (Test-Path $pythonw)) { throw "pythonw.exe not found at $pythonw" } - -New-Item -ItemType Directory -Force -Path $Destination | Out-Null -foreach ($file in 'weekly_report.py', 'runner_watch.py', 'ci_report.py') { - Copy-Item -Force (Join-Path $PSScriptRoot $file) (Join-Path $Destination $file) -} -$script = Join-Path $Destination 'weekly_report.py' -$reports = Join-Path $Destination 'reports' - -$arguments = "`"$script`" --org $Organisation --out-dir `"$reports`" --notify `"$Notify`"" -$action = New-ScheduledTaskAction -Execute $pythonw -Argument $arguments -$trigger = New-ScheduledTaskTrigger -Weekly -DaysOfWeek Monday -At 8:00 -$settings = New-ScheduledTaskSettingsSet ` - -MultipleInstances IgnoreNew ` - -ExecutionTimeLimit (New-TimeSpan -Minutes 15) ` - -AllowStartIfOnBatteries ` - -DontStopIfGoingOnBatteries ` - -StartWhenAvailable -$principal = New-ScheduledTaskPrincipal -UserId "$env:USERDOMAIN\$env:USERNAME" ` - -LogonType Interactive -RunLevel Limited - -Register-ScheduledTask ` - -TaskName $taskName ` - -Action $action ` - -Trigger $trigger ` - -Settings $settings ` - -Principal $principal ` - -Description "Writes the CI report of $Organisation to a file every Monday and toasts when the week deviates." ` - -Force | Out-Null - -Write-Host "Task '$taskName' installed: every Monday at 08:00 (or at the next start if the desktop was off)." -Write-Host " Reports: $reports" -Write-Host " Try now: py -3 `"$script`" --org $Organisation --out-dir `"$reports`"" -Write-Host " Remove: report\install-weekly-report.ps1 -Remove" diff --git a/report/runner_watch.py b/report/runner_watch.py deleted file mode 100644 index eafcc28..0000000 --- a/report/runner_watch.py +++ /dev/null @@ -1,257 +0,0 @@ -"""Runner watchdog: a toast when a self-hosted runner is offline or a run waits too long in the queue. - - py -3 runner_watch.py --org naindev-contrast3d --notify D:\\...\\notify.ps1 - -Run it from a scheduled task every few minutes. Each cycle reads, over `gh`, the runners of the -organisation and of every private repository in it, plus the runs still queued. It reports a runner -that has been seen offline for `--offline-min` minutes (GitHub does not say since when, so the first -sighting is remembered in the state file) and a run queued for `--queue-min` minutes. Every finding -is reported once, and again only after it has gone away and come back. An unreadable answer is -skipped, never reported: a watchdog that cries wolf on a network blip gets muted. - -The report in this folder (`ci_report.py`) says how the queue behaved over a period; this says that -it is wrong now. -""" - -from __future__ import annotations - -import argparse -import datetime as dt -import json -import subprocess -import sys -from collections.abc import Callable -from dataclasses import dataclass -from pathlib import Path - -sys.path.insert(0, str(Path(__file__).resolve().parent)) -import ci_report # same folder; its Github class does the `gh` reads - -STAMP = "%Y-%m-%dT%H:%M:%SZ" -OFFLINE_MIN = 10 -QUEUE_MIN = 15 - - -@dataclass -class Alert: - key: str - title: str - body: str - - -class Github(ci_report.Github): - """The reads of the report plus the two the watchdog needs at organisation scope.""" - - def org_runners(self, org: str) -> list[dict]: - out = self._run(["gh", "api", f"orgs/{org}/actions/runners?per_page=100"]) - return json.loads(out or "{}").get("runners", []) - - def org_repos(self, org: str) -> list[dict]: - out = self._run( - [ - "gh", - "repo", - "list", - org, - "--limit", - "100", - "--json", - "name,visibility,isArchived", - ] - ) - return json.loads(out or "[]") - - -def collect(gh, org: str) -> dict: - """What GitHub says now: (scope, runner name, status) and (repository, run id, created at).""" - runners: list[tuple[str, str, str]] = [] - queued: list[tuple[str, int, str]] = [] - try: - for runner in gh.org_runners(org): - runners.append((org, runner["name"], runner["status"])) - except subprocess.CalledProcessError: - pass - try: - repos = gh.org_repos(org) - except subprocess.CalledProcessError: - repos = [] - for repo in repos: - if repo.get("isArchived") or repo.get("visibility") != "PRIVATE": - continue - scope = f"{org}/{repo['name']}" - try: - for runner in gh.runners(scope): - runners.append((scope, runner["name"], runner["status"])) - except subprocess.CalledProcessError: - pass - try: - for item in gh.queued_runs(scope): - queued.append((scope, item["databaseId"], item["createdAt"])) - except subprocess.CalledProcessError: - pass - return {"runners": runners, "queued": queued} - - -def _moment(text: str) -> dt.datetime: - return dt.datetime.fromisoformat(text.replace("Z", "+00:00")) - - -def evaluate( - snapshot: dict, - state: dict, - now: dt.datetime, - offline_min: int = OFFLINE_MIN, - queue_min: int = QUEUE_MIN, - ignore=frozenset(), -) -> tuple[list[Alert], dict]: - """The alerts that are new now, and the state to keep for the next cycle.""" - alerted = set(state.get("alerted", [])) - seen_offline = dict(state.get("offline_since", {})) - new_offline: dict[str, str] = {} - active: set[str] = set() - alerts: list[Alert] = [] - - for scope, name, status in snapshot["runners"]: - if name in ignore or status == "online": - continue - key = f"{scope}/{name}" - since = seen_offline.get(key) or now.strftime(STAMP) - new_offline[key] = since - minutes = int((now - _moment(since)).total_seconds() // 60) - if minutes < offline_min: - continue - alert_key = f"offline:{key}" - active.add(alert_key) - if alert_key not in alerted: - alerts.append( - Alert( - alert_key, - "Runner offline", - f"{name} ({scope}) has been offline for {minutes} min.", - ) - ) - - for scope, run_id, created in snapshot["queued"]: - minutes = int((now - _moment(created)).total_seconds() // 60) - if minutes < queue_min: - continue - alert_key = f"queue:{scope}/{run_id}" - active.add(alert_key) - if alert_key not in alerted: - alerts.append( - Alert( - alert_key, - "CI run waiting for a runner", - f"A run of {scope} has been queued for {minutes} min.", - ) - ) - - kept = sorted((alerted & active) | {a.key for a in alerts}) - return alerts, {"offline_since": new_offline, "alerted": kept} - - -def notify( - alerts: list[Alert], notify_path: str, runner: Callable[[list[str]], object] -) -> None: - """One toast per alert through the desktop's own `notify.ps1`; a failing toast never raises.""" - for alert in alerts: - command = [ - "powershell.exe", - "-NoProfile", - "-ExecutionPolicy", - "Bypass", - "-File", - notify_path, - "-Title", - alert.title, - "-Body", - alert.body, - ] - try: - runner(command) - except (OSError, subprocess.SubprocessError): - pass - - -def load_state(path: Path) -> dict: - try: - data = json.loads(path.read_text(encoding="utf-8")) - except (OSError, ValueError): - return {} - return data if isinstance(data, dict) else {} - - -def save_state(path: Path, state: dict) -> None: - scratch = path.with_name(path.name + ".tmp") - scratch.write_text( - json.dumps(state, indent=1, sort_keys=True), encoding="utf-8", newline="\n" - ) - scratch.replace(path) - - -def _run_hidden(command: list[str]) -> None: - no_window = getattr(subprocess, "CREATE_NO_WINDOW", 0) - subprocess.run(command, check=False, capture_output=True, creationflags=no_window) - - -def run( - gh, - org: str, - state_path: Path, - now: dt.datetime, - *, - notify_path: str | None, - offline_min: int = OFFLINE_MIN, - queue_min: int = QUEUE_MIN, - ignore=frozenset(), - runner: Callable[[list[str]], object] = _run_hidden, -) -> list[Alert]: - alerts, state = evaluate( - collect(gh, org), load_state(state_path), now, offline_min, queue_min, ignore - ) - if notify_path: - notify(alerts, notify_path, runner) - save_state(state_path, state) - return alerts - - -def main(argv: list[str] | None = None) -> int: - parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - parser.add_argument("--org", required=True, help="the organisation to watch") - parser.add_argument( - "--state", help="JSON remembered between cycles (default: beside this file)" - ) - parser.add_argument( - "--notify", help="path of notify.ps1: one toast per new finding" - ) - parser.add_argument("--offline-min", type=int, default=OFFLINE_MIN) - parser.add_argument("--queue-min", type=int, default=QUEUE_MIN) - parser.add_argument( - "--ignore", - action="append", - default=[], - help="a runner name never reported; repeatable", - ) - args = parser.parse_args(argv) - state = ( - Path(args.state) - if args.state - else Path(__file__).resolve().with_name("runner-watch.json") - ) - alerts = run( - Github(), - args.org, - state, - dt.datetime.now(dt.UTC), - notify_path=args.notify, - offline_min=args.offline_min, - queue_min=args.queue_min, - ignore=frozenset(args.ignore), - ) - for alert in alerts: - print(f"{alert.title}: {alert.body}") - return 1 if alerts else 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/report/weekly_report.py b/report/weekly_report.py deleted file mode 100644 index 021bce4..0000000 --- a/report/weekly_report.py +++ /dev/null @@ -1,171 +0,0 @@ -"""Weekly CI report to a file, with a toast only when the week deviates. - - py -3 weekly_report.py --org naindev-contrast3d --out-dir D:\\...\\reports --notify D:\\...\\notify.ps1 - -Run it from a scheduled task once a week. It reads, over `gh`, every private repository of the -organisation that is not archived and writes `ci-report-.md` (and a copy as `latest.md`) in the -format of `ci_report.py`: failure rate by cause, durations, queue time per job and a snapshot of today. -A week that deviates (a failure rate, a queue or an infrastructure share above its threshold) puts the -deviations at the top of the report and raises one toast; a healthy week raises nothing, because a -notification that always fires is one nobody reads. An unreadable repository is skipped and said in the -report, never fatal. -""" - -from __future__ import annotations - -import argparse -import datetime as dt -import subprocess -import sys -from collections.abc import Callable -from pathlib import Path -from typing import NamedTuple - -sys.path.insert(0, str(Path(__file__).resolve().parent)) -import ci_report -import runner_watch - -FAIL_RATE_MAX = 0.25 -WAIT_P90_MAX_S = 300 -INFRA_SHARE_MAX = 0.2 -MIN_RUNS = 5 # below this, a rate is noise -MIN_FAILURES = 3 # below this, an infrastructure share is noise - - -class Result(NamedTuple): - path: Path - deviations: list[str] - - -def find_deviations( - stats: list[ci_report.RepoStats], - fail_rate_max: float = FAIL_RATE_MAX, - wait_p90_max: float = WAIT_P90_MAX_S, - infra_share_max: float = INFRA_SHARE_MAX, - min_runs: int = MIN_RUNS, -) -> list[str]: - """One sentence per repository and finding that is over its threshold.""" - found: list[str] = [] - for s in stats: - rate = s.fail_rate - if rate is not None and s.conclusive >= min_runs and rate > fail_rate_max: - found.append( - f"{s.repo}: {ci_report._pct(rate)} of the runs failed ({s.failed} of {s.conclusive})" - ) - if s.job_wait_p90_s is not None and s.job_wait_p90_s > wait_p90_max: - found.append( - f"{s.repo}: the p90 wait for a runner was {ci_report.fmt_duration(s.job_wait_p90_s)}" - ) - share = s.infra_share - if share is not None and s.failed >= MIN_FAILURES and share > infra_share_max: - found.append( - f"{s.repo}: {s.infra_failures} of {s.failed} failures were the infrastructure" - ) - return found - - -def collect_all(gh, org: str, days: int, now: dt.datetime, limit: int): - """Stats of every private, non-archived repository; the unreadable ones are named apart.""" - stats: list[ci_report.RepoStats] = [] - skipped: list[str] = [] - for repo in gh.org_repos(org): - if repo.get("isArchived") or repo.get("visibility") != "PRIVATE": - continue - scope = f"{org}/{repo['name']}" - try: - stats.append(ci_report.collect(gh, scope, "CI", days, now, limit=limit)) - except (subprocess.CalledProcessError, ValueError, KeyError) as exc: - skipped.append(f"{scope}: {type(exc).__name__}") - return stats, skipped - - -def run( - gh, - org: str, - out_dir: Path, - now: dt.datetime, - *, - days: int = 7, - limit: int = 300, - notify_path: str | None = None, - fail_rate_max: float = FAIL_RATE_MAX, - wait_p90_max: float = WAIT_P90_MAX_S, - infra_share_max: float = INFRA_SHARE_MAX, - runner: Callable[[list[str]], object] = runner_watch._run_hidden, -) -> Result: - stats, skipped = collect_all(gh, org, days, now, limit) - deviations = find_deviations(stats, fail_rate_max, wait_p90_max, infra_share_max) - text = ci_report.render(stats, days, now) - head = "" - if deviations: - head = "## Deviations\n\n" + "\n".join(f"- {d}" for d in deviations) + "\n\n" - if skipped: - head += "## Not read\n\n" + "\n".join(f"- {s}" for s in skipped) + "\n\n" - if head: - first, _, rest = text.partition("\n\n") - text = first + "\n\n" + head + rest - out_dir.mkdir(parents=True, exist_ok=True) - path = out_dir / f"ci-report-{now.strftime('%Y-%m-%d')}.md" - path.write_text(text, encoding="utf-8", newline="\n") - (out_dir / "latest.md").write_text(text, encoding="utf-8", newline="\n") - if deviations and notify_path: - shown = "; ".join(deviations[:3]) + (" ..." if len(deviations) > 3 else "") - runner_watch.notify( - [ - runner_watch.Alert( - f"weekly:{now.strftime('%Y-%m-%d')}", - f"CI weekly report: {len(deviations)} deviation(s)", - shown, - ) - ], - notify_path, - runner, - ) - return Result(path, deviations) - - -def main(argv: list[str] | None = None) -> int: - parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - parser.add_argument("--org", required=True) - parser.add_argument( - "--out-dir", - help="where the reports go (default: a reports folder beside this file)", - ) - parser.add_argument("--days", type=int, default=7) - parser.add_argument( - "--limit", type=int, default=300, help="runs read per repository" - ) - parser.add_argument( - "--notify", help="path of notify.ps1: one toast when the week deviates" - ) - parser.add_argument("--fail-rate-max", type=float, default=FAIL_RATE_MAX) - parser.add_argument( - "--wait-p90-max", type=float, default=WAIT_P90_MAX_S, help="seconds" - ) - parser.add_argument("--infra-share-max", type=float, default=INFRA_SHARE_MAX) - args = parser.parse_args(argv) - out_dir = ( - Path(args.out_dir) - if args.out_dir - else Path(__file__).resolve().with_name("reports") - ) - result = run( - runner_watch.Github(), - args.org, - out_dir, - dt.datetime.now(dt.UTC), - days=args.days, - limit=args.limit, - notify_path=args.notify, - fail_rate_max=args.fail_rate_max, - wait_p90_max=args.wait_p90_max, - infra_share_max=args.infra_share_max, - ) - print(f"report: {result.path}") - for deviation in result.deviations: - print(f"deviation: {deviation}") - return 1 if result.deviations else 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/standards/audit.py b/standards/audit.py deleted file mode 100644 index d43f966..0000000 --- a/standards/audit.py +++ /dev/null @@ -1,483 +0,0 @@ -"""Audit the repositories of an organisation against a written standard. - - py -3 audit.py # print the deviations - py -3 audit.py --fail-on error # exit 1 when there is an error (for a CI step) - -The standard is `standards.json` beside this script: thresholds, the severity of each rule and the -exceptions. An exception names a repository and a rule, says why, and expires; an expired exception -stops silencing the rule and is itself an error, so "on purpose" cannot turn into "forgotten". -Severities: `error` breaks a guarantee, `warning` is hygiene, `info` is an observation. - -Rules (per repository unless noted): delete-branch-on-merge, dependabot-config, codeowners, -secret-scanning (public repositories, where it is free), license (public repositories), -has-ci, shared-gate, gate-pin (the shared gate is pinned by a full commit SHA with a vX.Y.Z comment, -which is what online zizmor verifies), topic-branches, dependabot-alerts (off) and -dependabot-overdue (an open alert with a patched version past its deadline, 7/30/90 days for -critical/high/medium, `dependency_deadline_days` overrides), deploy-key-write, webhook-secret, -branch-protection (public repositories, where it is free), and for the organisation org-2fa, -org-2fa-method and actions-allowlist (actions restricted to a list and pinned by SHA). The audit -only reports: deploy keys, webhooks and two-factor are the owner's to change. Archived -repositories are skipped. -""" - -from __future__ import annotations - -import argparse -import datetime as dt -import json -import re -import subprocess -import sys -from collections.abc import Callable -from dataclasses import dataclass -from pathlib import Path - -SEVERITIES = ("error", "warning", "info") -GATE_REFERENCE = "naindev-contrast3d/ci-shared/.github/workflows/" -GOOD_PIN = re.compile(r"@[0-9a-f]{40}\s+#\s+v\d+\.\d+\.\d+\b") - -DEFAULT_SEVERITY = { - "delete-branch-on-merge": "error", - "dependabot-config": "error", - "license": "error", - "gate-pin": "error", - "org-2fa": "error", - "exception-expired": "error", - "codeowners": "warning", - "secret-scanning": "warning", - "has-ci": "warning", - "shared-gate": "warning", - "topic-branches": "warning", - "org-2fa-method": "warning", - "dependabot-alerts": "warning", - "dependabot-overdue": "warning", - "branch-protection": "warning", - "deploy-key-write": "warning", - "webhook-secret": "info", - "actions-allowlist": "warning", -} - -# Days an open alert with a patched version may stay open, by severity (spec org-security-baseline -# FR1). `dependency_deadline_days` in the standard overrides it; a missing severity has no deadline. -DEFAULT_DEADLINE_DAYS = {"critical": 7, "high": 30, "medium": 90} - - -class StandardError(ValueError): - """The standard file cannot be used.""" - - -@dataclass(frozen=True) -class Finding: - repo: str - rule: str - severity: str - message: str - - -def run_gh(command: list[str]) -> str: - # Every command is built in this file from fixed words and names GitHub returned. - no_window = getattr(subprocess, "CREATE_NO_WINDOW", 0) - return subprocess.run( - command, - check=True, - capture_output=True, - text=True, - encoding="utf-8", - creationflags=no_window, - ).stdout - - -class Github: - """The reads the audit needs, over the `gh` command line.""" - - def __init__(self, run: Callable[[list[str]], str] = run_gh): - self._run = run - - def org(self, org: str) -> dict: - return json.loads(self._run(["gh", "api", f"orgs/{org}"]) or "{}") - - def org_repos(self, org: str) -> list[dict]: - out = self._run( - [ - "gh", - "api", - f"orgs/{org}/repos?per_page=100&type=all", - "--paginate", - "--slurp", - ] - ) - listed = json.loads(out or "[]") - if listed and isinstance(listed[0], list): # --slurp returns one array per page - listed = [item for page in listed for item in page] - repos = [] - for entry in listed: - # The list endpoint omits settings such as delete_branch_on_merge: read each one. - detail = json.loads( - self._run(["gh", "api", f"repos/{org}/{entry['name']}"]) or "{}" - ) - repos.append(detail if isinstance(detail, dict) and detail else entry) - return repos - - def file_text(self, full_name: str, path: str) -> str | None: - try: - return self._run( - [ - "gh", - "api", - "-H", - "Accept: application/vnd.github.raw+json", - f"repos/{full_name}/contents/{path}", - ] - ) - except subprocess.CalledProcessError: - return None - - def dir_names(self, full_name: str, path: str) -> list[str]: - try: - out = self._run(["gh", "api", f"repos/{full_name}/contents/{path}"]) - except subprocess.CalledProcessError: - return [] - listing = json.loads(out or "[]") - return [item["name"] for item in listing] if isinstance(listing, list) else [] - - def branches(self, full_name: str) -> list[str]: - out = self._run( - [ - "gh", - "api", - f"repos/{full_name}/branches?per_page=100", - "--paginate", - "--jq", - ".[].name", - ] - ) - return [line.strip() for line in out.splitlines() if line.strip()] - - def insecure_two_factor_members(self, org: str) -> list[str]: - try: - out = self._run(["gh", "api", f"orgs/{org}/members?filter=2fa_insecure"]) - except subprocess.CalledProcessError: - return [] # needs organisation owner rights - return [member["login"] for member in json.loads(out or "[]")] - - def org_actions_permissions(self, org: str) -> dict: - try: - return json.loads(self._run(["gh", "api", f"orgs/{org}/actions/permissions"]) or "{}") - except subprocess.CalledProcessError: - return {} # needs organisation owner rights - - def dependabot_alerts(self, full_name: str) -> list[dict] | None: - """Open alerts, or None when Dependabot alerts are disabled or cannot be read.""" - try: - out = self._run( - [ - "gh", - "api", - f"repos/{full_name}/dependabot/alerts?state=open&per_page=100", - "--paginate", - "--slurp", - ] - ) - except subprocess.CalledProcessError: - return None - pages = json.loads(out or "[]") - return [item for page in pages for item in page] if pages and isinstance(pages[0], list) else pages - - def branch_protected(self, full_name: str, branch: str) -> bool: - try: - self._run(["gh", "api", f"repos/{full_name}/branches/{branch}/protection"]) - except subprocess.CalledProcessError: - return False - return True - - def deploy_keys(self, full_name: str) -> list[dict]: - try: - return json.loads(self._run(["gh", "api", f"repos/{full_name}/keys"]) or "[]") - except subprocess.CalledProcessError: - return [] - - def hooks(self, full_name: str) -> list[dict]: - try: - return json.loads(self._run(["gh", "api", f"repos/{full_name}/hooks"]) or "[]") - except subprocess.CalledProcessError: - return [] - - -def validate_standard(standard: dict) -> None: - for rule, severity in standard.get("severity", {}).items(): - if severity not in SEVERITIES: - raise StandardError( - f"severity of {rule} must be one of {', '.join(SEVERITIES)}" - ) - for item in standard.get("exceptions", []): - for key in ("repo", "rule", "reason", "expires"): - if not item.get(key): - raise StandardError(f"every exception needs `{key}`: {item}") - try: - dt.date.fromisoformat(item["expires"]) - except ValueError as exc: - raise StandardError( - f"`expires` must be a date (YYYY-MM-DD): {item}" - ) from exc - - -def audit(gh, standard: dict, now: dt.datetime) -> list[Finding]: - validate_standard(standard) - org = standard["organisation"] - today = now.date() - severity = {**DEFAULT_SEVERITY, **standard.get("severity", {})} - exceptions = standard.get("exceptions", []) - active = { - (item["repo"], item["rule"]) - for item in exceptions - if dt.date.fromisoformat(item["expires"]) >= today - } - findings: list[Finding] = [] - - def add(repo: str, rule: str, message: str, level: str | None = None) -> None: - if (repo, rule) in active: - return - findings.append(Finding(repo, rule, level or severity[rule], message)) - - for item in exceptions: - if dt.date.fromisoformat(item["expires"]) < today: - findings.append( - Finding( - item["repo"], - "exception-expired", - severity["exception-expired"], - f"the exception for `{item['rule']}` expired on {item['expires']} " - f"({item['reason']}); decide again", - ) - ) - - info = gh.org(org) - if not info.get("two_factor_requirement_enabled"): - add( - org, - "org-2fa", - "the organisation does not require two-factor authentication", - ) - insecure = gh.insecure_two_factor_members(org) - if insecure: - add( - org, - "org-2fa-method", - "members with an insecure second factor: " + ", ".join(insecure), - ) - permissions = gh.org_actions_permissions(org) - if permissions and ( - permissions.get("allowed_actions") != "selected" - or not permissions.get("sha_pinning_required") - ): - add( - org, - "actions-allowlist", - "actions are not restricted to a list or not pinned by SHA " - f"(allowed_actions={permissions.get('allowed_actions')}, " - f"sha_pinning_required={bool(permissions.get('sha_pinning_required'))})", - ) - - for repo in gh.org_repos(org): - if repo.get("archived"): - continue - full = repo["full_name"] - public = not repo.get("private", True) - _audit_repo(gh, standard, repo, full, public, now, add) - return findings - - -def _audit_security(gh, standard: dict, full: str, now: dt.datetime, add) -> None: - deadlines = {**DEFAULT_DEADLINE_DAYS, **standard.get("dependency_deadline_days", {})} - alerts = gh.dependabot_alerts(full) - if alerts is None: - add(full, "dependabot-alerts", "Dependabot alerts are disabled or cannot be read") - for item in alerts or []: - patched = (item.get("security_vulnerability") or {}).get("first_patched_version") - level = (item.get("security_advisory") or {}).get("severity") - if not patched or level not in deadlines: - continue # nothing to upgrade to yet, or a severity without a deadline - opened = dt.datetime.fromisoformat(item["created_at"].replace("Z", "+00:00")) - age = (now - opened).days - if age > deadlines[level]: - package = ((item.get("dependency") or {}).get("package") or {}).get("name", "?") - add( - full, - "dependabot-overdue", - f"{level} alert on `{package}` open {age} days, a fix exists " - f"(deadline {deadlines[level]} days)", - ) - for key in gh.deploy_keys(full): - if not key.get("read_only", True): - add(full, "deploy-key-write", f"deploy key `{key.get('title', '?')}` can write") - for hook in gh.hooks(full): - if hook.get("active") and not (hook.get("config") or {}).get("secret"): - add(full, "webhook-secret", "an active webhook has no secret (the URL is the credential)") - - -def _audit_repo( - gh, standard: dict, repo: dict, full: str, public: bool, now: dt.datetime, add -) -> None: - if not repo.get("delete_branch_on_merge"): - add( - full, - "delete-branch-on-merge", - "merged branches are not deleted automatically", - ) - - workflow_names = [ - name - for name in gh.dir_names(full, ".github/workflows") - if name.endswith((".yml", ".yaml")) - ] - if not workflow_names: - add(full, "has-ci", "no GitHub Actions workflow") - - has_dependabot = any( - gh.file_text(full, f".github/dependabot.{ext}") is not None - for ext in ("yml", "yaml") - ) - if not has_dependabot: - add( - full, - "dependabot-config", - "no .github/dependabot.yml", - "error" if workflow_names else "warning", - ) - - if not any( - gh.file_text(full, path) is not None - for path in (".github/CODEOWNERS", "CODEOWNERS", "docs/CODEOWNERS") - ): - add(full, "codeowners", "no CODEOWNERS file") - - if public: - security = repo.get("security_and_analysis") or {} - scanning = (security.get("secret_scanning") or {}).get("status") == "enabled" - protection = (security.get("secret_scanning_push_protection") or {}).get( - "status" - ) == "enabled" - if not (scanning and protection): - add( - full, - "secret-scanning", - "secret scanning or push protection is off (free on public repositories)", - ) - spdx = (repo.get("license") or {}).get("spdx_id") - if spdx in (None, "NOASSERTION"): - add(full, "license", "GitHub does not recognise the license") - branch = repo.get("default_branch", "main") - if not gh.branch_protected(full, branch): - add( - full, - "branch-protection", - f"`{branch}` is not protected (free on public repositories)", - ) - - _audit_security(gh, standard, full, now, add) - _audit_gate(gh, workflow_names, full, add) - - limit = standard.get("max_topic_branches", 8) - topics = [b for b in gh.branches(full) if b != repo.get("default_branch", "main")] - if len(topics) > limit: - add( - full, - "topic-branches", - f"{len(topics)} branches besides the default one (limit {limit})", - ) - - -def _audit_gate(gh, workflow_names: list[str], full: str, add) -> None: - if not workflow_names: - return - references = [] - for name in workflow_names: - text = gh.file_text(full, f".github/workflows/{name}") or "" - references += [ - line - for line in text.splitlines() - if GATE_REFERENCE in line - and "uses:" in line - and not line.lstrip().startswith("#") - ] - if not references: - add(full, "shared-gate", "no workflow calls the shared gate of ci-shared") - return - if not all(GOOD_PIN.search(line) for line in references): - add( - full, - "gate-pin", - "the shared workflow must be pinned by a full commit SHA with a `# vX.Y.Z` comment", - ) - - -def exit_code(findings: list[Finding], fail_on: str | None) -> int: - if fail_on is None: - return 0 - levels = {"error": ("error",), "warning": ("error", "warning")}[fail_on] - return 1 if any(f.severity in levels for f in findings) else 0 - - -def render(findings: list[Finding], now: dt.datetime) -> str: - counts = { - level: sum(1 for f in findings if f.severity == level) for level in SEVERITIES - } - parts = [f"{counts['error']} error{'s' if counts['error'] != 1 else ''}"] - parts.append(f"{counts['warning']} warning{'s' if counts['warning'] != 1 else ''}") - if counts["info"]: - parts.append(f"{counts['info']} info") - lines = [ - "# Standards audit", - "", - f"{now.strftime('%Y-%m-%d')}: {', '.join(parts)}.", - "", - ] - if not findings: - lines.append("No deviations from the standard.") - return "\n".join(lines) - order = {level: index for index, level in enumerate(SEVERITIES)} - for repo in sorted({f.repo for f in findings}): - lines.append(f"### {repo}") - for f in sorted( - (x for x in findings if x.repo == repo), - key=lambda x: (order[x.severity], x.rule), - ): - lines.append(f"- {f.severity} `{f.rule}`: {f.message}") - lines.append("") - return "\n".join(lines) - - -def run( - standard_path: Path | str, gh=None, now: dt.datetime | None = None -) -> list[Finding]: - standard = json.loads(Path(standard_path).read_text(encoding="utf-8")) - return audit(gh or Github(), standard, now or dt.datetime.now(dt.UTC)) - - -def main(argv: list[str] | None = None) -> int: - parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - parser.add_argument( - "--standard", default=str(Path(__file__).with_name("standards.json")) - ) - parser.add_argument( - "--fail-on", choices=("error", "warning"), help="exit 1 from this severity" - ) - parser.add_argument("--output", help="write the report here instead of printing it") - args = parser.parse_args(argv) - - now = dt.datetime.now(dt.UTC) - try: - findings = run(args.standard, now=now) - except StandardError as exc: - print(f"standard error: {exc}", file=sys.stderr) - return 2 - text = render(findings, now) - if args.output: - Path(args.output).write_text(text + "\n", encoding="utf-8") - else: - print(text) - return exit_code(findings, args.fail_on) - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/standards/bootstrap.py b/standards/bootstrap.py deleted file mode 100644 index 3d2ac89..0000000 --- a/standards/bootstrap.py +++ /dev/null @@ -1,226 +0,0 @@ -"""Apply the organisation's repository settings to a new repository. - - py -3 bootstrap.py owner/name # show what would change (dry run, the default) - py -3 bootstrap.py owner/name --apply # make the changes - -The settings come from the standards audit (audit.py): branch deletion after merge, secret -scanning and push protection where they are free (public repositories), Dependabot alerts and -security updates, and the two labels the merge train uses. Nothing is changed without --apply, and a -setting that already follows the standard is left alone. -""" - -from __future__ import annotations - -import argparse -import json -import os -import re -import subprocess -import sys -import tempfile -from collections.abc import Callable -from dataclasses import dataclass - -LABELS = { - "automerge": ( - "0E8A16", - "The merge train merges this pull request when its checks pass", - ), - "needs-human": ( - "D93F0B", - "A person must resolve this before the merge train retries", - ), -} -REPO_PATTERN = re.compile(r"^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$") - - -class BootstrapError(ValueError): - """The repository cannot be bootstrapped.""" - - -@dataclass(frozen=True) -class Change: - setting: str - current: str - wanted: str - - -def run_gh(command: list[str]) -> str: - # Every command is built in this file from fixed words and the repository name given. - no_window = getattr(subprocess, "CREATE_NO_WINDOW", 0) - return subprocess.run( - command, - check=True, - capture_output=True, - text=True, - encoding="utf-8", - creationflags=no_window, - ).stdout - - -class Github: - def __init__(self, run: Callable[[list[str]], str] = run_gh): - self._run = run - - def repo(self, full_name: str) -> dict: - return json.loads(self._run(["gh", "api", f"repos/{full_name}"]) or "{}") - - def labels(self, full_name: str) -> list[str]: - out = self._run( - [ - "gh", - "api", - f"repos/{full_name}/labels?per_page=100", - "--paginate", - "--slurp", - ] - ) - listed = json.loads(out or "[]") - if listed and isinstance(listed[0], list): - listed = [item for page in listed for item in page] - return [item["name"] for item in listed] - - def alerts_enabled(self, full_name: str) -> bool: - try: - self._run(["gh", "api", f"repos/{full_name}/vulnerability-alerts"]) - except subprocess.CalledProcessError: - return False - return True - - def security_fixes_enabled(self, full_name: str) -> bool: - try: - out = self._run( - [ - "gh", - "api", - f"repos/{full_name}/automated-security-fixes", - "--jq", - ".enabled", - ] - ) - except subprocess.CalledProcessError: - return False - return out.strip() == "true" - - def patch_repo(self, full_name: str, fields: dict) -> None: - with tempfile.NamedTemporaryFile( - "w", suffix=".json", delete=False, encoding="utf-8" - ) as handle: - json.dump(fields, handle) - path = handle.name - try: - self._run( - ["gh", "api", "-X", "PATCH", f"repos/{full_name}", "--input", path] - ) - finally: - os.unlink(path) - - def create_label( - self, full_name: str, name: str, color: str, description: str - ) -> None: - self._run( - [ - "gh", - "api", - "-X", - "POST", - f"repos/{full_name}/labels", - "-f", - f"name={name}", - "-f", - f"color={color}", - "-f", - f"description={description}", - ] - ) - - def enable_alerts(self, full_name: str) -> None: - self._run(["gh", "api", "-X", "PUT", f"repos/{full_name}/vulnerability-alerts"]) - - def enable_security_fixes(self, full_name: str) -> None: - self._run( - ["gh", "api", "-X", "PUT", f"repos/{full_name}/automated-security-fixes"] - ) - - -def plan(gh, full_name: str) -> list[Change]: - repo = gh.repo(full_name) - if repo.get("archived"): - raise BootstrapError(f"{full_name} is archived") - changes: list[Change] = [] - if not repo.get("delete_branch_on_merge"): - changes.append(Change("delete_branch_on_merge", "off", "on")) - if not repo.get("private", True): - security = repo.get("security_and_analysis") or {} - for key in ("secret_scanning", "secret_scanning_push_protection"): - if (security.get(key) or {}).get("status") != "enabled": - changes.append(Change(key, "off", "on")) - existing = set(gh.labels(full_name)) - for name in LABELS: - if name not in existing: - changes.append(Change(f"label:{name}", "missing", "created")) - if not gh.alerts_enabled(full_name): - changes.append(Change("vulnerability_alerts", "off", "on")) - if not gh.security_fixes_enabled(full_name): - changes.append(Change("automated_security_fixes", "off", "on")) - return changes - - -def apply(gh, full_name: str, changes: list[Change], dry_run: bool) -> None: - if dry_run: - return - fields: dict = {} - security: dict = {} - for change in changes: - if change.setting == "delete_branch_on_merge": - fields["delete_branch_on_merge"] = True - elif change.setting in ("secret_scanning", "secret_scanning_push_protection"): - security[change.setting] = {"status": "enabled"} - if security: - fields["security_and_analysis"] = security - if fields: - gh.patch_repo(full_name, fields) - for change in changes: - if change.setting.startswith("label:"): - name = change.setting.removeprefix("label:") - color, description = LABELS[name] - gh.create_label(full_name, name, color, description) - elif change.setting == "vulnerability_alerts": - gh.enable_alerts(full_name) - elif change.setting == "automated_security_fixes": - gh.enable_security_fixes(full_name) - - -def render(changes: list[Change], full_name: str, dry_run: bool) -> str: - mode = "dry run: nothing changed" if dry_run else "applied" - lines = [f"# Bootstrap of {full_name} ({mode})", ""] - if not changes: - lines.append(f"{full_name} already follows the standard.") - for change in changes: - lines.append(f"- {change.setting}: {change.current} -> {change.wanted}") - return "\n".join(lines) - - -def main(argv: list[str] | None = None) -> int: - parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - parser.add_argument("repo", help="owner/name") - parser.add_argument( - "--apply", action="store_true", help="make the changes (default: dry run)" - ) - args = parser.parse_args(argv) - if not REPO_PATTERN.match(args.repo): - print("repo must look like owner/name", file=sys.stderr) - return 2 - gh = Github() - try: - changes = plan(gh, args.repo) - except BootstrapError as exc: - print(f"bootstrap error: {exc}", file=sys.stderr) - return 2 - apply(gh, args.repo, changes, dry_run=not args.apply) - print(render(changes, args.repo, dry_run=not args.apply)) - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/standards/standards.json b/standards/standards.json deleted file mode 100644 index bc42174..0000000 --- a/standards/standards.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "organisation": "naindev-contrast3d", - "max_topic_branches": 8, - "severity": {}, - "exceptions": [ - { - "repo": "naindev-contrast3d/contrast-hub", - "rule": "shared-gate", - "reason": "its own `sello` job is the aggregate check and publishes the ci-ok seal (spec 365, ADR-0092)", - "expires": "2027-04-01" - }, - { - "repo": "naindev-contrast3d/ci-shared", - "rule": "shared-gate", - "reason": "it is the source of the gate and calls it by a local path in its own CI", - "expires": "2027-04-01" - }, - { - "repo": "naindev-contrast3d/.github", - "rule": "has-ci", - "reason": "the organisation profile repository holds only a README and community files", - "expires": "2027-04-01" - }, - { - "repo": "naindev-contrast3d/.github", - "rule": "dependabot-config", - "reason": "no workflows and no dependencies to update", - "expires": "2027-04-01" - }, - { - "repo": "naindev-contrast3d/.github", - "rule": "license", - "reason": "the organisation profile repository is documentation, not reusable code", - "expires": "2027-04-01" - }, - { - "repo": "naindev-contrast3d/dse", - "rule": "shared-gate", - "reason": "the session 'dse github move' is building its own CI; adoption is T23 of next-ci-reliability", - "expires": "2026-11-15" - } - ] -} diff --git a/tests/test_audit.py b/tests/test_audit.py deleted file mode 100644 index e3f71cb..0000000 --- a/tests/test_audit.py +++ /dev/null @@ -1,526 +0,0 @@ -"""Tests for standards/audit.py: each rule, the exceptions, the severities and the rendering.""" - -from __future__ import annotations - -import datetime as dt -import json -import subprocess -import sys -import unittest -from pathlib import Path - -sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "standards")) - -import audit - -ORG = "naindev-contrast3d" -NOW = dt.datetime(2026, 10, 14, 12, 0, 0, tzinfo=dt.UTC) -GOOD_PIN = ( - " uses: naindev-contrast3d/ci-shared/.github/workflows/gate.yml" - "@150de5008682330747ba6880f1649b388858c206 # v0.1.0\n" -) - - -def repo( - name, *, private=True, delete_branch=True, spdx="MIT", scanning=True, archived=False -): - status = "enabled" if scanning else "disabled" - return { - "name": name, - "full_name": f"{ORG}/{name}", - "private": private, - "visibility": "private" if private else "public", - "archived": archived, - "default_branch": "main", - "delete_branch_on_merge": delete_branch, - "allow_merge_commit": True, - "allow_squash_merge": True, - "allow_rebase_merge": True, - "license": {"spdx_id": spdx} if spdx else None, - "security_and_analysis": { - "secret_scanning": {"status": status}, - "secret_scanning_push_protection": {"status": status}, - }, - } - - -class FakeGithub: - def __init__( - self, - repos, - files=None, - dirs=None, - branches=None, - two_fa=True, - insecure=(), - alerts=None, - protected=True, - keys=None, - hooks=None, - actions=None, - ): - self._repos = repos - self._files = files or {} - self._dirs = dirs or {} - self._branches = branches or {} - self._two_fa = two_fa - self._insecure = list(insecure) - self._alerts = alerts or {} - self._protected = protected - self._keys = keys or {} - self._hooks = hooks or {} - self._actions = ( - {"allowed_actions": "selected", "sha_pinning_required": True} - if actions is None - else actions - ) - - def org(self, org): - return {"two_factor_requirement_enabled": self._two_fa} - - def org_actions_permissions(self, org): - return self._actions - - def dependabot_alerts(self, full_name): - return self._alerts.get(full_name, []) - - def branch_protected(self, full_name, branch): - return self._protected - - def deploy_keys(self, full_name): - return self._keys.get(full_name, []) - - def hooks(self, full_name): - return self._hooks.get(full_name, []) - - def org_repos(self, org): - return self._repos - - def file_text(self, full_name, path): - return self._files.get((full_name, path)) - - def dir_names(self, full_name, path): - return self._dirs.get((full_name, path), []) - - def branches(self, full_name): - return self._branches.get(full_name, ["main"]) - - def insecure_two_factor_members(self, org): - return self._insecure - - -def good_files(name): - full = f"{ORG}/{name}" - return ( - { - (full, ".github/dependabot.yml"): "version: 2\n", - (full, ".github/CODEOWNERS"): "* @Nain9Dev\n", - (full, ".github/workflows/ci.yml"): "jobs:\n gate:\n" + GOOD_PIN, - }, - {(full, ".github/workflows"): ["ci.yml"]}, - ) - - -def standard(**overrides): - base = { - "organisation": ORG, - "max_topic_branches": 8, - "severity": {}, - "exceptions": [], - } - base.update(overrides) - return base - - -def clean_world(**kw): - files, dirs = good_files("app") - return FakeGithub([repo("app")], files, dirs, **kw) - - -def rules(findings, name="app"): - return {f.rule for f in findings if f.repo == f"{ORG}/{name}"} - - -class Rules(unittest.TestCase): - def test_a_repository_that_follows_the_standard_has_no_findings(self): - self.assertEqual(audit.audit(clean_world(), standard(), NOW), []) - - def test_branch_deletion_after_merge_must_be_on(self): - files, dirs = good_files("app") - gh = FakeGithub([repo("app", delete_branch=False)], files, dirs) - findings = audit.audit(gh, standard(), NOW) - self.assertEqual(rules(findings), {"delete-branch-on-merge"}) - self.assertEqual(findings[0].severity, "error") - - def test_dependabot_is_an_error_when_the_repository_has_workflows(self): - files, dirs = good_files("app") - del files[(f"{ORG}/app", ".github/dependabot.yml")] - findings = audit.audit(FakeGithub([repo("app")], files, dirs), standard(), NOW) - self.assertEqual(rules(findings), {"dependabot-config"}) - self.assertEqual(findings[0].severity, "error") - - def test_codeowners_is_a_warning_and_any_of_the_three_places_counts(self): - files, dirs = good_files("app") - del files[(f"{ORG}/app", ".github/CODEOWNERS")] - findings = audit.audit(FakeGithub([repo("app")], files, dirs), standard(), NOW) - self.assertEqual( - (rules(findings), findings[0].severity), ({"codeowners"}, "warning") - ) - files[(f"{ORG}/app", "docs/CODEOWNERS")] = "* @x\n" - self.assertEqual( - audit.audit(FakeGithub([repo("app")], files, dirs), standard(), NOW), [] - ) - - def test_a_public_repository_must_have_secret_scanning_and_push_protection(self): - files, dirs = good_files("pub") - gh = FakeGithub([repo("pub", private=False, scanning=False)], files, dirs) - findings = audit.audit(gh, standard(), NOW) - self.assertEqual( - (rules(findings, "pub"), findings[0].severity), - ({"secret-scanning"}, "warning"), - ) - - def test_a_private_repository_is_not_asked_for_paid_secret_scanning(self): - files, dirs = good_files("app") - gh = FakeGithub([repo("app", private=True, scanning=False)], files, dirs) - self.assertEqual(audit.audit(gh, standard(), NOW), []) - - def test_a_public_repository_needs_a_license_github_recognises(self): - files, dirs = good_files("pub") - for spdx in ("NOASSERTION", None): - with self.subTest(spdx=spdx): - gh = FakeGithub([repo("pub", private=False, spdx=spdx)], files, dirs) - findings = audit.audit(gh, standard(), NOW) - self.assertEqual( - (rules(findings, "pub"), findings[0].severity), - ({"license"}, "error"), - ) - - def test_a_private_repository_may_have_no_license(self): - files, dirs = good_files("app") - gh = FakeGithub([repo("app", spdx=None)], files, dirs) - self.assertEqual(audit.audit(gh, standard(), NOW), []) - - def test_a_repository_without_workflows_is_flagged(self): - files, _ = good_files("app") - files.pop((f"{ORG}/app", ".github/workflows/ci.yml")) - gh = FakeGithub([repo("app")], files, {}) - self.assertIn("has-ci", rules(audit.audit(gh, standard(), NOW))) - - def test_the_shared_gate_pin_must_be_a_full_sha_with_a_version_comment(self): - bad_pins = { - "branch name": "@5b96639ee3e06da9f4ab7603c59fd818643ade6c # main\n", - "no comment": "@150de5008682330747ba6880f1649b388858c206\n", - "short sha": "@150de50 # v0.1.0\n", - "moving tag": "@v0 # v0\n", - } - for label, pin in bad_pins.items(): - with self.subTest(label): - files, dirs = good_files("app") - files[(f"{ORG}/app", ".github/workflows/ci.yml")] = ( - " uses: naindev-contrast3d/ci-shared/.github/workflows/gate.yml" - + pin - ) - findings = audit.audit( - FakeGithub([repo("app")], files, dirs), standard(), NOW - ) - self.assertEqual( - (rules(findings), findings[0].severity), ({"gate-pin"}, "error") - ) - - def test_a_commented_reference_is_documentation_not_a_call(self): - files, dirs = good_files("app") - files[(f"{ORG}/app", ".github/workflows/ci.yml")] = ( - "# example:\n" - "# uses: naindev-contrast3d/ci-shared/.github/workflows/gate.yml@\n" - "jobs:\n test:\n runs-on: x\n" - ) - findings = audit.audit(FakeGithub([repo("app")], files, dirs), standard(), NOW) - self.assertEqual(rules(findings), {"shared-gate"}) - - def test_a_ci_that_does_not_call_the_shared_gate_is_a_warning(self): - files, dirs = good_files("app") - files[(f"{ORG}/app", ".github/workflows/ci.yml")] = ( - "jobs:\n test:\n runs-on: x\n" - ) - findings = audit.audit(FakeGithub([repo("app")], files, dirs), standard(), NOW) - self.assertEqual( - (rules(findings), findings[0].severity), ({"shared-gate"}, "warning") - ) - - def test_too_many_topic_branches_is_a_warning_with_the_count(self): - files, dirs = good_files("app") - names = ["main"] + [f"feat/{i}" for i in range(12)] - gh = FakeGithub([repo("app")], files, dirs, branches={f"{ORG}/app": names}) - findings = audit.audit(gh, standard(), NOW) - self.assertEqual(rules(findings), {"topic-branches"}) - self.assertIn("12", findings[0].message) - - def test_archived_repositories_are_skipped(self): - gh = FakeGithub([repo("old", delete_branch=False, archived=True)]) - self.assertEqual(audit.audit(gh, standard(), NOW), []) - - def test_the_organisation_must_require_two_factor_authentication(self): - findings = audit.audit(clean_world(two_fa=False), standard(), NOW) - org_findings = [f for f in findings if f.repo == ORG] - self.assertEqual( - ([f.rule for f in org_findings], org_findings[0].severity), - (["org-2fa"], "error"), - ) - - def test_members_with_an_insecure_second_factor_are_a_warning(self): - findings = audit.audit(clean_world(insecure=["david"]), standard(), NOW) - org_findings = [f for f in findings if f.repo == ORG] - self.assertEqual( - ([f.rule for f in org_findings], org_findings[0].severity), - (["org-2fa-method"], "warning"), - ) - self.assertIn("david", org_findings[0].message) - - -def alert(severity, days_old, patched="1.2.3", package="left-pad"): - created = NOW - dt.timedelta(days=days_old) - return { - "created_at": created.isoformat().replace("+00:00", "Z"), - "dependency": {"package": {"name": package}}, - "security_advisory": {"severity": severity}, - "security_vulnerability": { - "first_patched_version": {"identifier": patched} if patched else None - }, - } - - -class SecurityRules(unittest.TestCase): - def world(self, **kw): - files, dirs = good_files("app") - return FakeGithub([repo("app")], files, dirs, **kw) - - def test_disabled_dependabot_alerts_are_a_warning(self): - gh = self.world(alerts={f"{ORG}/app": None}) - findings = audit.audit(gh, standard(), NOW) - self.assertEqual(rules(findings), {"dependabot-alerts"}) - self.assertEqual(findings[0].severity, "warning") - - def test_an_alert_inside_its_deadline_is_not_a_finding(self): - gh = self.world(alerts={f"{ORG}/app": [alert("critical", 6), alert("high", 29)]}) - self.assertEqual(audit.audit(gh, standard(), NOW), []) - - def test_an_alert_past_its_deadline_names_the_package_and_the_age(self): - gh = self.world(alerts={f"{ORG}/app": [alert("critical", 9, package="happy-dom")]}) - findings = audit.audit(gh, standard(), NOW) - self.assertEqual(rules(findings), {"dependabot-overdue"}) - self.assertIn("happy-dom", findings[0].message) - self.assertIn("9 days", findings[0].message) - - def test_an_alert_without_a_patched_version_is_never_overdue(self): - gh = self.world(alerts={f"{ORG}/app": [alert("high", 400, patched=None)]}) - self.assertEqual(audit.audit(gh, standard(), NOW), []) - - def test_the_deadlines_come_from_the_standard(self): - gh = self.world(alerts={f"{ORG}/app": [alert("medium", 20)]}) - std = standard(dependency_deadline_days={"medium": 10}) - self.assertEqual(rules(audit.audit(gh, std, NOW)), {"dependabot-overdue"}) - - def test_a_public_repository_must_protect_its_default_branch(self): - files, dirs = good_files("lib") - gh = FakeGithub([repo("lib", private=False)], files, dirs, protected=False) - self.assertEqual(rules(audit.audit(gh, standard(), NOW), "lib"), {"branch-protection"}) - - def test_a_private_repository_is_not_asked_for_paid_branch_protection(self): - self.assertEqual(audit.audit(self.world(protected=False), standard(), NOW), []) - - def test_a_writable_deploy_key_is_listed_by_title_without_key_material(self): - key = {"title": "release-tags", "read_only": False, "key": "ssh-ed25519 AAAA"} - gh = self.world(keys={f"{ORG}/app": [key, {"title": "ro", "read_only": True}]}) - findings = audit.audit(gh, standard(), NOW) - self.assertEqual(rules(findings), {"deploy-key-write"}) - self.assertIn("release-tags", findings[0].message) - self.assertNotIn("AAAA", findings[0].message) - self.assertEqual(len(findings), 1) - - def test_a_webhook_without_a_secret_is_an_observation(self): - hook = {"active": True, "config": {"url": "https://discord.com/api/webhooks/x"}} - gh = self.world(hooks={f"{ORG}/app": [hook]}) - findings = audit.audit(gh, standard(), NOW) - self.assertEqual(rules(findings), {"webhook-secret"}) - self.assertEqual(findings[0].severity, "info") - self.assertNotIn("discord.com/api", findings[0].message) - - def test_a_webhook_with_a_secret_is_fine(self): - hook = {"active": True, "config": {"url": "https://x.example/h", "secret": "********"}} - self.assertEqual( - audit.audit(self.world(hooks={f"{ORG}/app": [hook]}), standard(), NOW), [] - ) - - def test_actions_must_be_restricted_and_pinned_by_sha(self): - gh = self.world(actions={"allowed_actions": "all", "sha_pinning_required": False}) - findings = audit.audit(gh, standard(), NOW) - self.assertEqual({f.rule for f in findings}, {"actions-allowlist"}) - self.assertEqual(len(findings), 1) - - def test_unreadable_actions_permissions_are_skipped(self): - self.assertEqual(audit.audit(self.world(actions={}), standard(), NOW), []) - - -class Exceptions(unittest.TestCase): - def finding_world(self): - files, dirs = good_files("app") - return FakeGithub([repo("app", delete_branch=False)], files, dirs) - - def exception(self, expires): - return { - "repo": f"{ORG}/app", - "rule": "delete-branch-on-merge", - "reason": "kept on purpose", - "expires": expires, - } - - def test_a_valid_exception_silences_the_rule_for_that_repository(self): - std = standard(exceptions=[self.exception("2027-01-01")]) - self.assertEqual(audit.audit(self.finding_world(), std, NOW), []) - - def test_an_expired_exception_stops_applying_and_is_itself_a_finding(self): - std = standard(exceptions=[self.exception("2026-10-01")]) - found = {f.rule: f for f in audit.audit(self.finding_world(), std, NOW)} - self.assertEqual(set(found), {"delete-branch-on-merge", "exception-expired"}) - self.assertEqual(found["exception-expired"].severity, "error") - - def test_an_exception_for_another_repository_or_rule_changes_nothing(self): - other = dict(self.exception("2027-01-01"), repo=f"{ORG}/elsewhere") - std = standard( - exceptions=[other, dict(self.exception("2027-01-01"), rule="codeowners")] - ) - self.assertEqual( - rules(audit.audit(self.finding_world(), std, NOW)), - {"delete-branch-on-merge"}, - ) - - def test_an_exception_without_reason_or_date_is_rejected(self): - for bad in ( - {"repo": "a/b", "rule": "x"}, - {"repo": "a/b", "rule": "x", "reason": "r"}, - ): - with self.subTest(bad=bad), self.assertRaises(audit.StandardError): - audit.validate_standard(standard(exceptions=[bad])) - - -class Severity(unittest.TestCase): - def test_the_standard_can_change_the_severity_of_a_rule(self): - files, dirs = good_files("app") - gh = FakeGithub([repo("app", delete_branch=False)], files, dirs) - findings = audit.audit( - gh, standard(severity={"delete-branch-on-merge": "warning"}), NOW - ) - self.assertEqual(findings[0].severity, "warning") - - def test_an_unknown_severity_is_rejected(self): - with self.assertRaises(audit.StandardError): - audit.validate_standard(standard(severity={"codeowners": "fatal"})) - - def test_the_exit_code_follows_fail_on(self): - warning = [audit.Finding("o/a", "codeowners", "warning", "m")] - error = [audit.Finding("o/a", "license", "error", "m")] - self.assertEqual(audit.exit_code(warning, "error"), 0) - self.assertEqual(audit.exit_code(error, "error"), 1) - self.assertEqual(audit.exit_code(warning, "warning"), 1) - self.assertEqual(audit.exit_code([], "warning"), 0) - self.assertEqual(audit.exit_code(error, None), 0) - - -class Rendering(unittest.TestCase): - def test_findings_are_grouped_by_repository_and_ordered_by_severity(self): - findings = [ - audit.Finding("o/b", "codeowners", "warning", "no CODEOWNERS"), - audit.Finding("o/a", "license", "error", "license not recognised"), - audit.Finding("o/a", "codeowners", "warning", "no CODEOWNERS"), - ] - text = audit.render(findings, NOW) - self.assertLess(text.index("### o/a"), text.index("### o/b")) - self.assertLess( - text.index("license not recognised"), text.index("no CODEOWNERS") - ) - self.assertIn("- error `license`: license not recognised", text) - - def test_no_findings_says_so(self): - self.assertIn("No deviations", audit.render([], NOW)) - - def test_the_summary_counts_by_severity(self): - findings = [ - audit.Finding("o/a", "license", "error", "m"), - audit.Finding("o/a", "codeowners", "warning", "m"), - audit.Finding("o/b", "codeowners", "warning", "m"), - ] - self.assertIn("1 error, 2 warnings", audit.render(findings, NOW)) - - -class RealCommands(unittest.TestCase): - def setUp(self): - self.commands = [] - self.outputs = {} - self.errors = {} - self.gh = audit.Github(self.fake_run) - - def fake_run(self, command): - self.commands.append(command) - key = " ".join(command) - for needle, error in self.errors.items(): - if needle in key: - raise subprocess.CalledProcessError(1, command, stderr=error) - for needle, output in self.outputs.items(): - if needle in key: - return output - return "[]" - - def test_a_missing_file_reads_as_none(self): - self.errors["contents/.github/CODEOWNERS"] = "HTTP 404" - self.assertIsNone(self.gh.file_text(f"{ORG}/app", ".github/CODEOWNERS")) - - def test_a_file_is_read_through_the_raw_contents_media_type(self): - self.outputs["contents/.github/dependabot.yml"] = "version: 2\n" - self.assertEqual( - self.gh.file_text(f"{ORG}/app", ".github/dependabot.yml"), "version: 2\n" - ) - self.assertIn("application/vnd.github.raw+json", " ".join(self.commands[0])) - - def test_a_missing_directory_is_empty(self): - self.errors["contents/.github/workflows"] = "HTTP 404" - self.assertEqual(self.gh.dir_names(f"{ORG}/app", ".github/workflows"), []) - - def test_the_repositories_are_listed_with_the_fields_the_rules_read(self): - self.outputs["orgs/" + ORG + "/repos"] = json.dumps([repo("app")]) - self.assertEqual(self.gh.org_repos(ORG)[0]["name"], "app") - - def test_insecure_two_factor_members_are_listed_by_login(self): - self.outputs["2fa_insecure"] = json.dumps([{"login": "david"}]) - self.assertEqual(self.gh.insecure_two_factor_members(ORG), ["david"]) - - def test_disabled_dependabot_alerts_read_as_none(self): - self.errors["dependabot/alerts"] = "Dependabot alerts are disabled" - self.assertIsNone(self.gh.dependabot_alerts(f"{ORG}/app")) - - def test_open_alerts_are_flattened_across_pages(self): - self.outputs["dependabot/alerts"] = json.dumps([[{"a": 1}], [{"a": 2}]]) - self.assertEqual(self.gh.dependabot_alerts(f"{ORG}/app"), [{"a": 1}, {"a": 2}]) - self.assertIn("state=open", " ".join(self.commands[0])) - - def test_an_unprotected_branch_reads_as_false(self): - self.errors["branches/main/protection"] = "Branch not protected" - self.assertFalse(self.gh.branch_protected(f"{ORG}/app", "main")) - - def test_a_protected_branch_reads_as_true(self): - self.outputs["branches/main/protection"] = "{}" - self.assertTrue(self.gh.branch_protected(f"{ORG}/app", "main")) - - def test_keys_and_hooks_that_cannot_be_read_are_empty(self): - self.errors["/keys"] = "HTTP 403" - self.errors["/hooks"] = "HTTP 403" - self.assertEqual(self.gh.deploy_keys(f"{ORG}/app"), []) - self.assertEqual(self.gh.hooks(f"{ORG}/app"), []) - - def test_actions_permissions_that_cannot_be_read_are_empty(self): - self.errors["actions/permissions"] = "HTTP 403" - self.assertEqual(self.gh.org_actions_permissions(ORG), {}) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_automerge.py b/tests/test_automerge.py deleted file mode 100644 index e6d22fb..0000000 --- a/tests/test_automerge.py +++ /dev/null @@ -1,612 +0,0 @@ -"""Tests for train/automerge.py: the decision rules, the cycle and the real `gh` commands.""" - -from __future__ import annotations - -import datetime as dt -import json -import subprocess -import sys -import tempfile -import unittest -from pathlib import Path - -sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "train")) - -import automerge as train - -REPO = "naindev-contrast3d/example" -SHA = "a" * 40 - - -def pr( - number=1, - sha=SHA, - labels=("automerge",), - draft=False, - base="main", - mergeable="MERGEABLE", -): - return { - "number": number, - "headRefOid": sha, - "baseRefName": base, - "isDraft": draft, - "mergeable": mergeable, - "labels": [{"name": name} for name in labels], - } - - -class FakeGithub: - """Records every call; answers from plain dictionaries.""" - - def __init__( - self, - prs=None, - gate_ok=True, - sealed=True, - behind=0, - update_result="updated", - fail_repos=(), - merge_error=False, - queue=None, - queue_error=False, - comment_error=False, - ): - self.comment_error = comment_error - self.comments = [] - self.prs = prs or [] - self.queue = queue or {} - self.queue_error = queue_error - self.gate_ok = gate_ok - self.sealed_shas = sealed - self.behind = behind - self.update_result = update_result - self.fail_repos = set(fail_repos) - self.merge_error = merge_error - self.calls = [] - - def _answer(self, value, sha): - return value(sha) if callable(value) else value - - def open_prs(self, repo, label): - self.calls.append(("open_prs", repo)) - if repo in self.fail_repos: - raise subprocess.CalledProcessError(1, ["gh"], stderr="boom") - return self.prs.get(repo, []) if isinstance(self.prs, dict) else self.prs - - def queued_runs(self, repo): - if self.queue_error: - raise subprocess.CalledProcessError(1, ["gh"], stderr="queue boom") - return self.queue.get(repo, []) - - def gate_green(self, repo, sha, check_name): - return self._answer(self.gate_ok, sha) - - def sealed(self, repo, sha): - return self._answer(self.sealed_shas, sha) - - def behind_by(self, repo, base, sha): - return self._answer(self.behind, sha) - - def merge(self, repo, number, sha, method): - self.calls.append(("merge", repo, number, sha, method)) - if self.merge_error: - raise subprocess.CalledProcessError(1, ["gh"], stderr="not allowed") - - def comment(self, repo, number, body): - if self.comment_error: - raise subprocess.CalledProcessError(1, ["gh"], stderr="comment boom") - self.comments.append((repo, number, body)) - - def update_branch(self, repo, number, sha): - self.calls.append(("update", repo, number, sha)) - return self.update_result - - def flag_needs_human(self, repo, number, label, needs_label): - self.calls.append(("flag", repo, number, label, needs_label)) - - def mutations(self): - return [c for c in self.calls if c[0] != "open_prs"] - - -def run(gh, repos=None, dry_run=False, alerts=None, now=None, heartbeat=None): - logs = [] - settings = train.Settings() - configs = repos or [train.RepoConfig(repo=REPO)] - code = train.run_cycle( - gh, - configs, - settings, - dry_run=dry_run, - log=logs.append, - alerts=alerts, - now=now, - heartbeat=heartbeat, - ) - return code, logs - - -NOW = dt.datetime(2026, 10, 14, 13, 0, 0, tzinfo=dt.UTC) - - -class MergeMark(unittest.TestCase): - """The train marks what it merges, so a merge made around it can be counted (FR13).""" - - def test_a_merged_pull_request_gets_the_train_mark_with_its_head(self): - gh = FakeGithub(prs=[pr(7)]) - run(gh) - self.assertEqual(len(gh.comments), 1) - repo, number, body = gh.comments[0] - self.assertEqual((repo, number), (REPO, 7)) - self.assertIn(train.MERGE_MARK, body) - self.assertIn(SHA[:12], body) - - def test_nothing_is_marked_in_a_dry_run_or_when_the_merge_is_refused(self): - dry = FakeGithub(prs=[pr(7)]) - run(dry, dry_run=True) - refused = FakeGithub(prs=[pr(7)], merge_error=True) - run(refused) - self.assertEqual((dry.comments, refused.comments), ([], [])) - - def test_a_failing_comment_is_logged_and_does_not_undo_or_fail_the_merge(self): - gh = FakeGithub(prs=[pr(7)], comment_error=True) - code, logs = run(gh) - self.assertEqual(code, 0) - self.assertEqual(gh.mutations(), [("merge", REPO, 7, SHA, "merge")]) - self.assertTrue(any("mark failed" in line for line in logs)) - - -class HeartbeatLine(unittest.TestCase): - """A line at least once an hour proves the train is alive and says which script it runs (FR14).""" - - def state(self): - return Path(tempfile.mkdtemp()) / "heartbeat.json" - - def test_the_first_cycle_logs_a_heartbeat_with_counts_and_the_script_version(self): - gh = FakeGithub(prs=[pr(1), pr(2, "b" * 40)], behind=2) - _, logs = run(gh, heartbeat=train.Heartbeat(self.state()), now=NOW) - line = next(item for item in logs if "heartbeat" in item) - self.assertIn("1 repositories", line) - self.assertIn("2 labelled pull requests", line) - self.assertIn(train.script_version(), line) - - def test_no_second_heartbeat_within_the_hour_but_one_after_it(self): - path = self.state() - gh = FakeGithub(prs=[]) - _, first = run(gh, heartbeat=train.Heartbeat(path), now=NOW) - _, soon = run( - gh, heartbeat=train.Heartbeat(path), now=NOW + dt.timedelta(minutes=59) - ) - _, later = run( - gh, heartbeat=train.Heartbeat(path), now=NOW + dt.timedelta(minutes=61) - ) - counts = [ - sum("heartbeat" in item for item in logs) for logs in (first, soon, later) - ] - self.assertEqual(counts, [1, 0, 1]) - - def test_a_dry_run_does_not_write_the_heartbeat_state(self): - path = self.state() - run(FakeGithub(prs=[]), dry_run=True, heartbeat=train.Heartbeat(path), now=NOW) - self.assertFalse(path.exists()) - - def test_the_script_version_is_the_same_for_lf_and_crlf_copies(self): - text = "a\nb\n" - self.assertEqual( - train.text_version(text), train.text_version(text.replace("\n", "\r\n")) - ) - self.assertNotEqual(train.text_version(text), train.text_version(text + "c\n")) - - -def queued(run_id, minutes_ago, branch="feat/x", workflow="CI"): - created = NOW - dt.timedelta(minutes=minutes_ago) - return { - "databaseId": run_id, - "createdAt": created.strftime("%Y-%m-%dT%H:%M:%SZ"), - "headBranch": branch, - "workflowName": workflow, - } - - -class QueueAlert(unittest.TestCase): - def state_path(self): - return Path(tempfile.mkdtemp()) / "queue-alerts.json" - - def test_a_run_queued_longer_than_the_threshold_is_logged_with_its_details(self): - gh = FakeGithub(queue={REPO: [queued(77, 45, branch="feat/y", workflow="CI")]}) - _, logs = run(gh, alerts=train.QueueAlerts(self.state_path()), now=NOW) - line = next(item for item in logs if "queued" in item) - for part in (REPO, "77", "feat/y", "CI", "45"): - self.assertIn(part, line) - - def test_a_younger_run_is_not_logged(self): - gh = FakeGithub(queue={REPO: [queued(78, 5)]}) - _, logs = run(gh, alerts=train.QueueAlerts(self.state_path()), now=NOW) - self.assertFalse(any("queued" in item for item in logs)) - - def test_the_same_run_is_logged_only_once_even_across_restarts(self): - path = self.state_path() - gh = FakeGithub(queue={REPO: [queued(79, 60)]}) - _, first = run(gh, alerts=train.QueueAlerts(path), now=NOW) - _, again = run(gh, alerts=train.QueueAlerts(path), now=NOW) - self.assertEqual(sum("queued" in item for item in first), 1) - self.assertEqual(sum("queued" in item for item in again), 0) - - def test_runs_that_left_the_queue_are_forgotten(self): - path = self.state_path() - run( - FakeGithub(queue={REPO: [queued(80, 60)]}), - alerts=train.QueueAlerts(path), - now=NOW, - ) - run(FakeGithub(queue={REPO: []}), alerts=train.QueueAlerts(path), now=NOW) - self.assertNotIn("80", path.read_text(encoding="utf-8")) - - def test_a_dry_run_logs_but_does_not_remember(self): - path = self.state_path() - gh = FakeGithub(queue={REPO: [queued(81, 60)]}) - _, logs = run(gh, dry_run=True, alerts=train.QueueAlerts(path), now=NOW) - self.assertTrue(any("queued" in item for item in logs)) - self.assertFalse(path.exists()) - - def test_the_alert_works_even_when_the_repository_has_no_open_pull_requests(self): - gh = FakeGithub(prs=[], queue={REPO: [queued(82, 90)]}) - _, logs = run(gh, alerts=train.QueueAlerts(self.state_path()), now=NOW) - self.assertTrue(any("82" in item for item in logs)) - - def test_a_failing_queue_query_is_logged_and_does_not_stop_the_merge(self): - gh = FakeGithub(prs=[pr(3)], queue_error=True) - code, logs = run(gh, alerts=train.QueueAlerts(self.state_path()), now=NOW) - self.assertEqual(code, 0) - self.assertTrue(any("queue check failed" in item for item in logs)) - self.assertEqual(gh.mutations(), [("merge", REPO, 3, SHA, "merge")]) - - def test_without_an_alerts_object_nothing_is_checked(self): - gh = FakeGithub(queue={REPO: [queued(83, 90)]}) - _, logs = run(gh) - self.assertEqual(logs, []) - - def test_the_threshold_comes_from_the_settings(self): - gh = FakeGithub(queue={REPO: [queued(84, 10)]}) - logs = [] - train.run_cycle( - gh, - [train.RepoConfig(repo=REPO)], - train.Settings(queue_alert_minutes=5), - dry_run=False, - log=logs.append, - alerts=train.QueueAlerts(self.state_path()), - now=NOW, - ) - self.assertTrue(any("84" in item for item in logs)) - - -class DecisionRules(unittest.TestCase): - def cfg(self, **kw): - return train.RepoConfig(repo=REPO, **kw) - - def classify(self, pull, gh=None, **kw): - return train.classify( - pull, self.cfg(**kw), train.Settings(), gh or FakeGithub() - ) - - def test_a_sealed_green_up_to_date_pull_request_is_ready(self): - self.assertEqual(self.classify(pr())[0], "ready") - - def test_missing_label_draft_and_other_base_are_skipped(self): - self.assertEqual(self.classify(pr(labels=()))[0], "skip") - self.assertEqual(self.classify(pr(draft=True))[0], "skip") - self.assertEqual(self.classify(pr(base="develop"))[0], "skip") - - def test_unknown_mergeability_is_skipped_and_a_conflict_is_flagged(self): - self.assertEqual(self.classify(pr(mergeable="UNKNOWN"))[0], "skip") - self.assertEqual(self.classify(pr(mergeable="CONFLICTING"))[0], "conflict") - - def test_a_red_or_missing_gate_is_skipped(self): - state, reason = self.classify(pr(), FakeGithub(gate_ok=False)) - self.assertEqual(state, "skip") - self.assertIn("gate", reason) - - def test_the_seal_is_required_only_when_configured(self): - no_seal = FakeGithub(sealed=False) - self.assertEqual(self.classify(pr(), no_seal)[0], "ready") - state, reason = self.classify(pr(), no_seal, require_seal=True) - self.assertEqual(state, "skip") - self.assertIn("seal", reason) - - def test_a_head_that_misses_main_is_stale(self): - state, reason = self.classify(pr(), FakeGithub(behind=3)) - self.assertEqual(state, "stale") - self.assertIn("3", reason) - - def test_a_red_stale_pull_request_is_not_stale_but_skipped(self): - self.assertEqual( - self.classify(pr(), FakeGithub(behind=3, gate_ok=False))[0], "skip" - ) - - -class Cycle(unittest.TestCase): - def test_a_ready_pull_request_is_merged_at_its_exact_head(self): - gh = FakeGithub(prs=[pr(7)]) - code, _ = run(gh) - self.assertEqual(code, 0) - self.assertEqual(gh.mutations(), [("merge", REPO, 7, SHA, "merge")]) - - def test_the_merge_method_of_the_repository_is_used(self): - gh = FakeGithub(prs=[pr(7)]) - configs = [train.RepoConfig(repo=REPO, merge_method="squash")] - run(gh, repos=configs) - self.assertEqual(gh.mutations(), [("merge", REPO, 7, SHA, "squash")]) - - def test_only_the_oldest_ready_pull_request_is_merged_per_cycle(self): - gh = FakeGithub(prs=[pr(9, "b" * 40), pr(4, "c" * 40)]) - _, logs = run(gh) - self.assertEqual(gh.mutations(), [("merge", REPO, 4, "c" * 40, "merge")]) - self.assertTrue(any("#9" in line and "waits" in line for line in logs)) - - def test_a_stale_pull_request_gets_main_merged_in_and_is_not_merged(self): - gh = FakeGithub(prs=[pr(3)], behind=2) - run(gh) - self.assertEqual(gh.mutations(), [("update", REPO, 3, SHA)]) - - def test_a_ready_pull_request_is_merged_before_any_stale_one_is_updated(self): - def behind(sha): - return 0 if sha == "c" * 40 else 2 - - gh = FakeGithub(prs=[pr(2, "b" * 40), pr(5, "c" * 40)], behind=behind) - run(gh) - self.assertEqual(gh.mutations(), [("merge", REPO, 5, "c" * 40, "merge")]) - - def test_only_one_stale_pull_request_is_updated_per_cycle(self): - gh = FakeGithub(prs=[pr(2, "b" * 40), pr(5, "c" * 40)], behind=2) - run(gh) - self.assertEqual(gh.mutations(), [("update", REPO, 2, "b" * 40)]) - - def test_a_conflicting_pull_request_is_flagged_and_never_merged(self): - gh = FakeGithub(prs=[pr(6, mergeable="CONFLICTING")]) - run(gh) - self.assertEqual( - gh.mutations(), [("flag", REPO, 6, "automerge", "needs-human")] - ) - - def test_a_conflict_found_while_updating_the_branch_is_flagged(self): - gh = FakeGithub(prs=[pr(8)], behind=1, update_result="conflict") - run(gh) - self.assertEqual( - gh.mutations(), - [("update", REPO, 8, SHA), ("flag", REPO, 8, "automerge", "needs-human")], - ) - - def test_a_dry_run_changes_nothing(self): - gh = FakeGithub(prs=[pr(1), pr(2, "b" * 40, mergeable="CONFLICTING")], behind=0) - _, logs = run(gh, dry_run=True) - self.assertEqual(gh.mutations(), []) - self.assertTrue(any("dry run" in line for line in logs)) - - def test_a_failing_repository_does_not_stop_the_others(self): - gh = FakeGithub(prs={"o/working": [pr(1)]}, fail_repos={"o/broken"}) - configs = [ - train.RepoConfig(repo="o/broken"), - train.RepoConfig(repo="o/working"), - ] - code, logs = run(gh, repos=configs) - self.assertEqual(code, 1) - self.assertEqual(gh.mutations(), [("merge", "o/working", 1, SHA, "merge")]) - self.assertTrue(any("o/broken" in line and "failed" in line for line in logs)) - - def test_a_refused_merge_is_logged_and_reported(self): - gh = FakeGithub(prs=[pr(1)], merge_error=True) - code, logs = run(gh) - self.assertEqual(code, 1) - self.assertTrue(any("merge refused" in line for line in logs)) - - def test_no_open_pull_requests_is_a_quiet_success(self): - code, logs = run(FakeGithub(prs=[])) - self.assertEqual(code, 0) - self.assertEqual(logs, []) - - -class Config(unittest.TestCase): - def write(self, data): - directory = tempfile.mkdtemp() - path = Path(directory) / "repos.json" - path.write_text( - data if isinstance(data, str) else json.dumps(data), encoding="utf-8" - ) - return path - - def test_defaults_apply_to_a_minimal_entry(self): - settings, repos = train.load_config(self.write({"repos": [{"repo": "o/r"}]})) - self.assertEqual(settings.label, "automerge") - self.assertEqual(settings.needs_human_label, "needs-human") - self.assertEqual(repos[0].gate_check, "Gate / Gate") - self.assertFalse(repos[0].require_seal) - self.assertEqual(repos[0].base, "main") - self.assertEqual(repos[0].merge_method, "merge") - self.assertEqual(settings.queue_alert_minutes, 30) - - def test_the_queue_alert_threshold_can_be_set_and_must_be_a_positive_integer(self): - settings, _ = train.load_config( - self.write({"queue_alert_minutes": 10, "repos": [{"repo": "o/r"}]}) - ) - self.assertEqual(settings.queue_alert_minutes, 10) - for bad in (0, -5, "10", 1.5, True): - with self.subTest(bad=bad), self.assertRaises(train.ConfigError): - train.load_config( - self.write({"queue_alert_minutes": bad, "repos": [{"repo": "o/r"}]}) - ) - - def test_overrides_are_read(self): - _, repos = train.load_config( - self.write( - { - "repos": [ - { - "repo": "o/r", - "gate_check": "CI gate", - "require_seal": True, - "base": "trunk", - } - ], - } - ) - ) - self.assertEqual( - (repos[0].gate_check, repos[0].require_seal, repos[0].base), - ("CI gate", True, "trunk"), - ) - - def test_invalid_configuration_is_rejected(self): - for bad in ( - "not json", - {"repos": []}, - {"repos": [{"gate_check": "x"}]}, - {"repos": [{"repo": "no-slash"}]}, - {"repos": [{"repo": "o/r", "require_seal": "yes"}]}, - {"repos": [{"repo": "o/r", "merge_method": "fast-forward"}]}, - ): - with self.subTest(bad=bad), self.assertRaises(train.ConfigError): - train.load_config(self.write(bad)) - - -class RealGithubCommands(unittest.TestCase): - """The commands are built from fixed words plus GitHub's own numbers and shas.""" - - def setUp(self): - self.commands = [] - self.outputs = {} - self.errors = {} - self.gh = train.Github(self.fake_run) - - def fake_run(self, command): - self.commands.append(command) - key = " ".join(command) - for needle, error in self.errors.items(): - if needle in key: - raise subprocess.CalledProcessError(1, command, stderr=error) - for needle, output in self.outputs.items(): - if needle in key: - return output - return "" - - def test_the_merge_method_is_read_from_the_configuration(self): - directory = tempfile.mkdtemp() - path = Path(directory) / "repos.json" - path.write_text( - json.dumps({"repos": [{"repo": "o/r", "merge_method": "squash"}]}), - encoding="utf-8", - ) - _, repos = train.load_config(path) - self.assertEqual(repos[0].merge_method, "squash") - - def test_each_merge_method_maps_to_its_gh_flag(self): - for method in ("merge", "squash", "rebase"): - with self.subTest(method=method): - self.commands.clear() - self.gh.merge(REPO, 5, SHA, method) - self.assertIn(f"--{method}", self.commands[0]) - self.assertIn("--match-head-commit", self.commands[0]) - - def test_merge_pins_the_head_commit_and_makes_a_merge_commit(self): - self.gh.merge(REPO, 5, SHA, "merge") - self.assertEqual( - self.commands[0], - [ - "gh", - "pr", - "merge", - "5", - "--repo", - REPO, - "--merge", - "--match-head-commit", - SHA, - ], - ) - - def test_comment_posts_the_body_on_the_pull_request(self): - self.gh.comment(REPO, 9, f"{train.MERGE_MARK}\nMerged") - self.assertEqual( - self.commands[0][:7], ["gh", "pr", "comment", "9", "--repo", REPO, "--body"] - ) - self.assertIn(train.MERGE_MARK, self.commands[0][7]) - - def test_queued_runs_asks_for_queued_status_and_parses_json(self): - self.outputs["run list"] = json.dumps([queued(5, 40)]) - runs = self.gh.queued_runs(REPO) - self.assertEqual(runs[0]["databaseId"], 5) - command = self.commands[0] - self.assertEqual(command[:4], ["gh", "run", "list", "--repo"]) - self.assertIn("queued", command) - self.assertIn("databaseId,createdAt,headBranch,workflowName", command) - - def test_open_prs_filters_by_label_and_parses_json(self): - self.outputs["pr list"] = json.dumps([pr(2)]) - self.assertEqual(self.gh.open_prs(REPO, "automerge")[0]["number"], 2) - self.assertIn("--label", self.commands[0]) - self.assertIn("automerge", self.commands[0]) - - def test_gate_is_green_only_when_every_run_of_that_name_succeeded(self): - runs = { - "check_runs": [ - {"name": "Gate / Gate", "status": "completed", "conclusion": "success"}, - {"name": "Other", "status": "completed", "conclusion": "failure"}, - ] - } - self.outputs["check-runs"] = json.dumps(runs) - self.assertTrue(self.gh.gate_green(REPO, SHA, "Gate / Gate")) - runs["check_runs"].append( - {"name": "Gate / Gate", "status": "completed", "conclusion": "failure"} - ) - self.outputs["check-runs"] = json.dumps(runs) - self.assertFalse(self.gh.gate_green(REPO, SHA, "Gate / Gate")) - - def test_gate_is_not_green_when_missing_or_still_running(self): - self.outputs["check-runs"] = json.dumps({"check_runs": []}) - self.assertFalse(self.gh.gate_green(REPO, SHA, "Gate / Gate")) - self.outputs["check-runs"] = json.dumps( - { - "check_runs": [ - {"name": "Gate / Gate", "status": "in_progress", "conclusion": None} - ] - } - ) - self.assertFalse(self.gh.gate_green(REPO, SHA, "Gate / Gate")) - - def test_the_seal_is_a_tag_that_either_exists_or_not(self): - self.assertTrue(self.gh.sealed(REPO, SHA)) - self.errors["git/ref/tags"] = "Not Found" - self.assertFalse(self.gh.sealed(REPO, SHA)) - - def test_behind_by_reads_the_compare_endpoint(self): - self.outputs["compare"] = json.dumps({"behind_by": 4}) - self.assertEqual(self.gh.behind_by(REPO, "main", SHA), 4) - self.assertIn(f"repos/{REPO}/compare/main...{SHA}", self.commands[0]) - - def test_update_branch_pins_the_expected_head(self): - self.assertEqual(self.gh.update_branch(REPO, 3, SHA), "updated") - self.assertIn(f"expected_head_sha={SHA}", self.commands[0]) - self.assertIn("PUT", self.commands[0]) - - def test_update_branch_reports_a_merge_conflict_and_raises_on_other_errors(self): - self.errors["update-branch"] = ( - "gh: merge conflict between base and head (HTTP 422)" - ) - self.assertEqual(self.gh.update_branch(REPO, 3, SHA), "conflict") - self.errors["update-branch"] = "gh: Resource not accessible (HTTP 403)" - with self.assertRaises(subprocess.CalledProcessError): - self.gh.update_branch(REPO, 3, SHA) - - def test_flagging_creates_the_label_if_needed_then_swaps_labels(self): - self.errors["label create"] = "already exists" - self.gh.flag_needs_human(REPO, 6, "automerge", "needs-human") - edit = self.commands[-1] - self.assertEqual(edit[:5], ["gh", "pr", "edit", "6", "--repo"]) - self.assertIn("--add-label", edit) - self.assertIn("needs-human", edit) - self.assertIn("--remove-label", edit) - self.assertIn("automerge", edit) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_bootstrap.py b/tests/test_bootstrap.py deleted file mode 100644 index b20a044..0000000 --- a/tests/test_bootstrap.py +++ /dev/null @@ -1,203 +0,0 @@ -"""Tests for standards/bootstrap.py: the plan of settings for a new repository and its application.""" - -from __future__ import annotations - -import json -import subprocess -import sys -import unittest -from pathlib import Path - -sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "standards")) - -import bootstrap - -REPO = "naindev-contrast3d/new-app" - - -def settings(**overrides): - base = { - "private": True, - "archived": False, - "delete_branch_on_merge": False, - "security_and_analysis": { - "secret_scanning": {"status": "disabled"}, - "secret_scanning_push_protection": {"status": "disabled"}, - }, - } - base.update(overrides) - return base - - -class FakeGithub: - def __init__(self, repo=None, labels=(), alerts=False, fixes=False): - self._repo = repo or settings() - self._labels = list(labels) - self._alerts = alerts - self._fixes = fixes - self.calls = [] - - def repo(self, full_name): - return self._repo - - def labels(self, full_name): - return self._labels - - def alerts_enabled(self, full_name): - return self._alerts - - def security_fixes_enabled(self, full_name): - return self._fixes - - def patch_repo(self, full_name, fields): - self.calls.append(("patch", fields)) - - def create_label(self, full_name, name, color, description): - self.calls.append(("label", name)) - - def enable_alerts(self, full_name): - self.calls.append(("alerts",)) - - def enable_security_fixes(self, full_name): - self.calls.append(("fixes",)) - - -def names(changes): - return {c.setting for c in changes} - - -class Plan(unittest.TestCase): - def test_a_fresh_private_repository_needs_branch_deletion_labels_and_security_updates( - self, - ): - changes = bootstrap.plan(FakeGithub(), REPO) - self.assertEqual( - names(changes), - { - "delete_branch_on_merge", - "label:automerge", - "label:needs-human", - "vulnerability_alerts", - "automated_security_fixes", - }, - ) - - def test_secret_scanning_is_asked_for_only_on_public_repositories(self): - public = FakeGithub(settings(private=False)) - self.assertIn("secret_scanning", names(bootstrap.plan(public, REPO))) - self.assertIn( - "secret_scanning_push_protection", names(bootstrap.plan(public, REPO)) - ) - self.assertNotIn("secret_scanning", names(bootstrap.plan(FakeGithub(), REPO))) - - def test_settings_already_in_place_are_not_planned(self): - done = settings(delete_branch_on_merge=True) - gh = FakeGithub( - done, labels=["automerge", "needs-human"], alerts=True, fixes=True - ) - self.assertEqual(bootstrap.plan(gh, REPO), []) - - def test_an_archived_repository_is_refused(self): - with self.assertRaises(bootstrap.BootstrapError): - bootstrap.plan(FakeGithub(settings(archived=True)), REPO) - - def test_every_change_says_what_it_is_now_and_what_it_will_be(self): - change = next( - c - for c in bootstrap.plan(FakeGithub(), REPO) - if c.setting == "delete_branch_on_merge" - ) - self.assertEqual((change.current, change.wanted), ("off", "on")) - - -class Apply(unittest.TestCase): - def test_nothing_changes_without_apply(self): - gh = FakeGithub() - bootstrap.apply(gh, REPO, bootstrap.plan(gh, REPO), dry_run=True) - self.assertEqual(gh.calls, []) - - def test_apply_makes_each_planned_change_once(self): - gh = FakeGithub() - bootstrap.apply(gh, REPO, bootstrap.plan(gh, REPO), dry_run=False) - kinds = [call[0] for call in gh.calls] - self.assertEqual(sorted(kinds), ["alerts", "fixes", "label", "label", "patch"]) - patch = next(call for call in gh.calls if call[0] == "patch") - self.assertEqual(patch[1], {"delete_branch_on_merge": True}) - - def test_public_security_settings_go_in_one_patch(self): - gh = FakeGithub(settings(private=False, delete_branch_on_merge=True)) - bootstrap.apply(gh, REPO, bootstrap.plan(gh, REPO), dry_run=False) - patch = next(call for call in gh.calls if call[0] == "patch") - self.assertEqual( - patch[1], - { - "security_and_analysis": { - "secret_scanning": {"status": "enabled"}, - "secret_scanning_push_protection": {"status": "enabled"}, - } - }, - ) - - -class Rendering(unittest.TestCase): - def test_the_plan_is_printed_as_a_list_and_says_when_nothing_is_needed(self): - text = bootstrap.render(bootstrap.plan(FakeGithub(), REPO), REPO, dry_run=True) - self.assertIn("dry run", text.lower()) - self.assertIn("delete_branch_on_merge: off -> on", text) - done = FakeGithub( - settings(delete_branch_on_merge=True), - labels=["automerge", "needs-human"], - alerts=True, - fixes=True, - ) - self.assertIn( - "already follows", - bootstrap.render(bootstrap.plan(done, REPO), REPO, dry_run=True), - ) - - -class RealCommands(unittest.TestCase): - def setUp(self): - self.commands = [] - self.outputs = {} - self.errors = {} - self.gh = bootstrap.Github(self.fake_run) - - def fake_run(self, command): - self.commands.append(command) - key = " ".join(command) - for needle, error in self.errors.items(): - if needle in key: - raise subprocess.CalledProcessError(1, command, stderr=error) - for needle, output in self.outputs.items(): - if needle in key: - return output - return "" - - def test_alerts_are_enabled_when_the_endpoint_answers_and_not_when_it_is_404(self): - self.assertTrue(self.gh.alerts_enabled(REPO)) - self.errors["vulnerability-alerts"] = "HTTP 404" - self.assertFalse(self.gh.alerts_enabled(REPO)) - - def test_labels_are_read_by_name(self): - self.outputs["labels"] = json.dumps([{"name": "automerge"}, {"name": "bug"}]) - self.assertEqual(self.gh.labels(REPO), ["automerge", "bug"]) - - def test_the_repository_is_patched_with_a_json_body(self): - self.gh.patch_repo(REPO, {"delete_branch_on_merge": True}) - command = self.commands[0] - self.assertIn("PATCH", command) - self.assertIn("--input", command) - - def test_security_updates_and_alerts_use_their_endpoints(self): - self.gh.enable_alerts(REPO) - self.gh.enable_security_fixes(REPO) - joined = [" ".join(c) for c in self.commands] - self.assertTrue(any("PUT" in c and "vulnerability-alerts" in c for c in joined)) - self.assertTrue( - any("PUT" in c and "automated-security-fixes" in c for c in joined) - ) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_ci_report.py b/tests/test_ci_report.py deleted file mode 100644 index 2b229cc..0000000 --- a/tests/test_ci_report.py +++ /dev/null @@ -1,549 +0,0 @@ -"""Tests for report/ci_report.py: failure classification, the metrics and the rendered report.""" - -from __future__ import annotations - -import datetime as dt -import json -import subprocess -import sys -import unittest -from pathlib import Path - -sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "report")) - -import ci_report as report - -REPO = "naindev-contrast3d/example" -NOW = dt.datetime(2026, 10, 14, 12, 0, 0, tzinfo=dt.UTC) - - -def iso(minutes_ago: float, seconds: int = 0) -> str: - moment = NOW - dt.timedelta(minutes=minutes_ago) + dt.timedelta(seconds=seconds) - return moment.strftime("%Y-%m-%dT%H:%M:%SZ") - - -def run(run_id, conclusion, created_min_ago, duration_s, name="CI", status="completed"): - return { - "databaseId": run_id, - "conclusion": conclusion, - "status": status, - "workflowName": name, - "createdAt": iso(created_min_ago), - "startedAt": iso(created_min_ago), - "updatedAt": iso(created_min_ago, duration_s), - "event": "pull_request", - "headBranch": "feat/x", - } - - -def job(name, conclusion, started_after_s, failed_step=None): - steps = [{"name": failed_step, "conclusion": "failure"}] if failed_step else [] - return { - "name": name, - "conclusion": conclusion, - "startedAt": started_after_s, - "steps": steps, - } - - -class FakeGithub: - def __init__(self, runs, jobs, runners=None, queued=None, prs=None): - self._runs = runs - self._jobs = jobs # run id -> list of (name, conclusion, delay_s, failed_step) - self._runners = runners if runners is not None else [] - self._queued = queued or [] - self._prs = prs or [] - - def runs(self, repo, limit): - return self._runs - - def jobs(self, repo, run_id): - created = next(r for r in self._runs if r["databaseId"] == run_id)["createdAt"] - base = dt.datetime.fromisoformat(created) - out = [] - for name, conclusion, delay, failed_step in self._jobs.get(run_id, []): - started = (base + dt.timedelta(seconds=delay)).strftime( - "%Y-%m-%dT%H:%M:%SZ" - ) - out.append(job(name, conclusion, started, failed_step)) - return out - - def job_timings(self, repo, run_id): - return getattr(self, "timings", {}).get(run_id, []) - - def runners(self, repo): - return self._runners - - def queued_runs(self, repo): - return self._queued - - def open_prs(self, repo): - return self._prs - - def merged_prs(self, repo, limit): - return getattr(self, "merged", []) - - def file_text(self, repo, path): - return getattr(self, "files", {}).get((repo, path)) - - -def sample_github(): - runs = [ - run(1, "success", 60, 300), - run(2, "success", 120, 600), - run(3, "failure", 180, 120), # a real test failure - run(4, "failure", 240, 60), # the runner could not start the job - run(5, "cancelled", 300, 30), - run(6, "skipped", 360, 0), - run(7, "success", 60 * 24 * 10, 300), # older than the window - run(8, "success", 70, 100, name="Other"), # another workflow - ] - jobs = { - 1: [("Verify", "success", 30, None)], - 2: [("Verify", "success", 10, None)], - 3: [("Verify", "success", 90, None), ("Tests", "failure", 95, "Pruebas")], - 4: [("Verify", "failure", 200, "Set up job")], - } - runners = [ - {"name": "vm-01", "status": "online", "busy": True}, - {"name": "vm-02", "status": "offline", "busy": False}, - ] - queued = [ - {"databaseId": 90, "createdAt": iso(45)}, - {"databaseId": 91, "createdAt": iso(5)}, - ] - prs = [ - {"number": 1, "labels": [{"name": "automerge"}], "createdAt": iso(60 * 5)}, - {"number": 2, "labels": [], "createdAt": iso(60)}, - ] - return FakeGithub(runs, jobs, runners, queued, prs) - - -class Classification(unittest.TestCase): - def test_a_job_that_never_started_its_steps_is_infrastructure(self): - jobs = [job("Verify", "failure", iso(1), "Set up job")] - self.assertEqual(report.classify_failure(jobs), "infra") - - def test_a_failure_with_no_steps_at_all_is_infrastructure(self): - self.assertEqual( - report.classify_failure([job("Verify", "failure", iso(1))]), "infra" - ) - - def test_a_failed_test_step_is_code(self): - jobs = [job("Tests", "failure", iso(1), "Pruebas")] - self.assertEqual(report.classify_failure(jobs), "code") - - def test_the_shared_preflight_failing_is_infrastructure(self): - jobs = [ - job("Runner preflight", "failure", iso(1), "Check tools, memory and disk") - ] - self.assertEqual(report.classify_failure(jobs), "infra") - - def test_a_run_is_infrastructure_only_when_every_failed_job_is(self): - jobs = [ - job("Verify", "failure", iso(1), "Set up job"), - job("Tests", "failure", iso(1), "Pruebas"), - ] - self.assertEqual(report.classify_failure(jobs), "code") - - def test_no_failed_job_is_reported_as_code(self): - self.assertEqual( - report.classify_failure([job("Verify", "success", iso(1))]), "code" - ) - - -class Metrics(unittest.TestCase): - def setUp(self): - self.stats = report.collect(sample_github(), REPO, "CI", days=7, now=NOW) - - def test_only_conclusive_runs_of_the_workflow_inside_the_window_are_counted(self): - self.assertEqual(self.stats.conclusive, 4) - self.assertEqual(self.stats.failed, 2) - self.assertEqual(self.stats.cancelled, 1) - - def test_failures_are_split_by_cause(self): - self.assertEqual(self.stats.infra_failures, 1) - - def test_the_median_duration_is_over_conclusive_runs(self): - self.assertEqual(self.stats.median_duration_s, 210) # 60, 120, 300, 600 - - def test_the_median_queue_time_is_the_first_job_start_after_the_run_was_created( - self, - ): - self.assertEqual(self.stats.median_queue_s, 60) # 10, 30, 90, 200 - - def test_the_snapshot_reports_runners_the_queue_and_open_pull_requests(self): - self.assertEqual((self.stats.runners_online, self.stats.runners_busy), (1, 1)) - self.assertEqual(self.stats.runners_offline, 1) - self.assertEqual(self.stats.queued_now, 2) - self.assertEqual(self.stats.oldest_queued_min, 45) - self.assertEqual((self.stats.open_prs, self.stats.automerge_prs), (2, 1)) - - def test_a_repository_without_runs_has_no_rates_instead_of_dividing_by_zero(self): - stats = report.collect(FakeGithub([], {}), REPO, "CI", days=7, now=NOW) - self.assertEqual(stats.conclusive, 0) - self.assertIsNone(stats.fail_rate) - self.assertIsNone(stats.median_duration_s) - self.assertIsNone(stats.median_queue_s) - - -MARK = "" - - -def merged_pr(number, minutes_ago, marked): - comments = ( - [{"body": f"{MARK}\nMerged by the merge train"}] - if marked - else [{"body": "lgtm"}] - ) - return {"number": number, "mergedAt": iso(minutes_ago), "comments": comments} - - -class MergedOutsideTheTrain(unittest.TestCase): - """A merged pull request without the train's mark was merged around the train (FR13).""" - - def stats(self, merged, train_repos=(REPO,), train_since=None): - gh = sample_github() - gh.merged = merged - return report.collect( - gh, - REPO, - "CI", - days=7, - now=NOW, - train_repos=set(train_repos), - train_since=train_since, - ) - - def test_unmarked_merges_inside_the_window_are_counted(self): - stats = self.stats( - [merged_pr(1, 60, True), merged_pr(2, 120, False), merged_pr(3, 180, False)] - ) - self.assertEqual((stats.merged_total, stats.merged_by_hand), (3, 2)) - - def test_merges_older_than_the_window_or_before_the_train_are_not_counted(self): - old = merged_pr( - 4, 60 * 24 * 10, False - ) # ten days ago, outside the 7-day window - before_train = merged_pr(5, 60 * 24 * 3, False) - since = NOW - dt.timedelta(days=1) - stats = self.stats( - [old, before_train, merged_pr(6, 30, True)], train_since=since - ) - self.assertEqual((stats.merged_total, stats.merged_by_hand), (1, 0)) - - def test_a_repository_without_the_shared_train_is_not_counted_at_all(self): - stats = self.stats([merged_pr(1, 60, False)], train_repos=()) - self.assertIsNone(stats.merged_by_hand) - self.assertIsNone(stats.merged_total) - - def test_the_snapshot_says_how_many_were_merged_around_the_train(self): - stats = self.stats([merged_pr(1, 60, True), merged_pr(2, 120, False)]) - text = report.render([stats], days=7, now=NOW) - self.assertIn("Merged outside the train: 1 of 2", text) - - def test_the_real_query_asks_for_merged_pull_requests_with_their_comments(self): - commands = [] - gh = report.Github(lambda command: commands.append(command) or "[]") - gh.merged_prs(REPO, 100) - self.assertIn("merged", commands[0]) - self.assertTrue(any("comments" in part for part in commands[0])) - - def test_the_mark_is_the_same_text_the_train_writes(self): - sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "train")) - import automerge as train - - self.assertEqual(report.TRAIN_MARK, train.MERGE_MARK) - - -class TrainHealth(unittest.TestCase): - """The report shows whether the train is alive and runs the current script (FR14).""" - - def setUp(self): - import os - import tempfile - - self.os = os - self.dir = Path(tempfile.mkdtemp()) - self.gh = FakeGithub([], {}) - self.gh.files = { - ("naindev-contrast3d/ci-shared", "train/automerge.py"): "script v1\n" - } - - def write(self, name, text, minutes_ago=None): - path = self.dir / name - path.write_text(text, encoding="utf-8", newline="") - if minutes_ago is not None: - stamp = (NOW - dt.timedelta(minutes=minutes_ago)).timestamp() - self.os.utime(path, (stamp, stamp)) - - def health(self): - return report.train_health(self.dir, self.gh, NOW) - - def test_a_recent_log_and_the_current_script_are_healthy(self): - self.write("train.log", "[x] heartbeat\n", minutes_ago=12) - self.write("automerge.py", "script v1\n") - health = self.health() - self.assertEqual(health.log_age_min, 12) - self.assertFalse(health.silent) - self.assertEqual(health.copy, "current") - - def test_a_log_older_than_ninety_minutes_means_the_train_is_silent(self): - self.write("train.log", "[x] heartbeat\n", minutes_ago=130) - self.write("automerge.py", "script v1\n") - self.assertTrue(self.health().silent) - - def test_a_copy_that_differs_from_ci_shared_main_is_stale(self): - self.write("train.log", "x\n", minutes_ago=5) - self.write("automerge.py", "script v0\n") - health = self.health() - self.assertEqual(health.copy, "stale") - self.assertNotEqual(health.installed_version, health.repository_version) - - def test_line_endings_alone_do_not_make_a_copy_stale(self): - self.write("train.log", "x\n", minutes_ago=5) - self.write("automerge.py", "script v1\r\n") - self.assertEqual(self.health().copy, "current") - - def test_a_missing_folder_is_reported_as_not_installed(self): - health = report.train_health(self.dir / "nowhere", self.gh, NOW) - self.assertEqual(health.copy, "missing") - self.assertIsNone(health.log_age_min) - - def test_the_section_states_each_finding_in_words(self): - self.write("train.log", "x\n", minutes_ago=130) - self.write("automerge.py", "script v0\n") - text = report.render_train(self.health()) - self.assertIn("## Merge train", text) - self.assertIn("no log line for 130 min", text) - self.assertIn("differs from ci-shared main", text) - - def test_the_version_function_matches_the_trains(self): - sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "train")) - import automerge as train - - for sample in ("a\nb\n", "a\r\nb\r\n", ""): - self.assertEqual(report.text_version(sample), train.text_version(sample)) - - -class AuditSection(unittest.TestCase): - """`--audit` appends the standards audit to the report.""" - - def test_the_audit_module_is_found_beside_the_report(self): - module = report.load_audit() - self.assertTrue(callable(module.run)) - self.assertTrue(callable(module.render)) - - def test_the_section_is_the_audit_report_without_its_own_title(self): - module = report.load_audit() - findings = [module.Finding("o/a", "license", "error", "license not recognised")] - text = report.audit_section(module.render(findings, NOW)) - self.assertTrue(text.startswith("## Standards audit")) - self.assertIn("- error `license`: license not recognised", text) - self.assertNotIn( - "# Standards audit\n\n2026", text.replace("## Standards audit", "") - ) - - -class Until(unittest.TestCase): - """A window that ends in the past makes a baseline reproducible after later changes.""" - - def test_runs_created_after_the_end_of_the_window_are_ignored(self): - gh = sample_github() - gh._runs.append(run(20, "failure", 10, 60)) # 10 minutes ago - gh._jobs[20] = [("Verify", "failure", 5, "Pruebas")] - until = NOW - dt.timedelta(minutes=30) - stats = report.collect(gh, REPO, "CI", days=7, now=NOW, until=until) - self.assertEqual(stats.conclusive, 4) - self.assertEqual(stats.failed, 2) - - def test_without_until_the_window_ends_now(self): - gh = sample_github() - gh._runs.append(run(20, "failure", 10, 60)) - gh._jobs[20] = [("Verify", "failure", 5, "Pruebas")] - stats = report.collect(gh, REPO, "CI", days=7, now=NOW) - self.assertEqual(stats.conclusive, 5) - - def test_the_window_start_moves_with_until(self): - until = NOW - dt.timedelta(days=3) - text = report.render([], days=7, now=NOW, until=until) - self.assertIn("2026-10-04 to 2026-10-11", text) - self.assertIn("snapshot", text.lower()) - - def test_a_moment_may_be_a_date_or_a_date_and_time_in_utc(self): - self.assertEqual( - report.parse_moment("2026-10-14"), - dt.datetime(2026, 10, 14, 0, 0, tzinfo=dt.UTC), - ) - self.assertEqual( - report.parse_moment("2026-10-14T11:00"), - dt.datetime(2026, 10, 14, 11, 0, tzinfo=dt.UTC), - ) - self.assertEqual( - report.parse_moment("2026-10-14T11:00:00Z"), - dt.datetime(2026, 10, 14, 11, 0, tzinfo=dt.UTC), - ) - - -class Rendering(unittest.TestCase): - def test_the_table_row_is_pinned(self): - stats = report.collect(sample_github(), REPO, "CI", days=7, now=NOW) - text = report.render([stats], days=7, now=NOW) - self.assertIn( - f"| {REPO} | 4 | 2 | 50% | 50% | 3m30s | 1m00s |", - text, - ) - - def test_the_snapshot_lines_are_present(self): - stats = report.collect(sample_github(), REPO, "CI", days=7, now=NOW) - text = report.render([stats], days=7, now=NOW) - self.assertIn("Runners: 1 online (1 busy), 1 offline", text) - self.assertIn("Queued now: 2 (oldest 45 min)", text) - self.assertIn("Open pull requests: 2 (1 labelled automerge)", text) - - def test_a_repository_without_data_renders_dashes(self): - stats = report.collect(FakeGithub([], {}), REPO, "CI", days=7, now=NOW) - text = report.render([stats], days=7, now=NOW) - self.assertIn(f"| {REPO} | 0 | 0 | - | - | - | - |", text) - - def test_the_header_states_the_period(self): - text = report.render([], days=7, now=NOW) - self.assertIn("2026-10-07", text) - self.assertIn("2026-10-14", text) - - def test_durations_are_formatted_for_people(self): - self.assertEqual(report.fmt_duration(45), "45s") - self.assertEqual(report.fmt_duration(210), "3m30s") - self.assertEqual(report.fmt_duration(3720), "1h02m") - - -def timing(name, queued_s, conclusion="success", started=True): - """A job from the REST API that waited `queued_s` seconds for a runner.""" - created = NOW - dt.timedelta(hours=1) - began = created + dt.timedelta(seconds=queued_s) - stamp = "%Y-%m-%dT%H:%M:%SZ" - return { - "name": name, - "conclusion": conclusion, - "created_at": created.strftime(stamp), - "started_at": began.strftime(stamp) if started else None, - } - - -class JobQueueTime(unittest.TestCase): - def test_a_job_waits_from_its_creation_to_its_start(self): - waits = report.job_waits([timing("Verify", 45), timing("Seal", 780)]) - self.assertEqual(waits, [("Verify", 45), ("Seal", 780)]) - - def test_skipped_and_never_started_jobs_do_not_count(self): - jobs = [timing("A", 0, "skipped"), timing("B", 0, None, started=False)] - self.assertEqual(report.job_waits(jobs), []) - - def test_a_clock_skew_never_gives_a_negative_wait(self): - self.assertEqual(report.job_waits([timing("A", -3)]), [("A", 0)]) - - def test_the_percentile_is_the_nearest_rank(self): - values = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] - self.assertEqual(report.percentile(values, 90), 90) - self.assertEqual(report.percentile(values, 50), 50) - self.assertEqual(report.percentile([7], 90), 7) - self.assertIsNone(report.percentile([], 90)) - - def test_the_report_gives_median_p90_max_and_the_slowest_jobs(self): - gh = sample_github() - gh.timings = { - 1: [timing("Verify", 10), timing("Seal", 780)], - 2: [timing("Verify", 20), timing("Seal", 600)], - 3: [timing("Verify", 30), timing("Seal", 900)], - } - stats = report.collect(gh, REPO, "CI", days=7, now=NOW) - self.assertEqual(stats.jobs_sampled, 6) - self.assertEqual(stats.job_wait_max_s, 900) - self.assertEqual(stats.job_wait_p90_s, 900) - self.assertEqual(stats.job_wait_median_s, 315) # 10, 20, 30, 600, 780, 900 - self.assertEqual(stats.slowest_jobs[0], ("Seal", 780, 3)) - - def test_a_repository_without_timings_has_no_queue_figures(self): - stats = report.collect(sample_github(), REPO, "CI", days=7, now=NOW) - self.assertEqual(stats.jobs_sampled, 0) - self.assertIsNone(stats.job_wait_median_s) - self.assertEqual(stats.slowest_jobs, []) - - def test_the_section_names_the_slowest_job_and_the_runner_count(self): - gh = sample_github() - gh.timings = {1: [timing("Verify", 10), timing("Seal", 780)]} - stats = report.collect(gh, REPO, "CI", days=7, now=NOW) - text = report.render([stats], days=7, now=NOW) - self.assertIn("## Queue time per job", text) - self.assertIn( - f"| {REPO} | 2 | 6m35s | 13m00s | 13m00s | Seal (13m00s) | 1 |", text - ) - - def test_the_section_is_left_out_when_no_repository_has_timings(self): - stats = report.collect(sample_github(), REPO, "CI", days=7, now=NOW) - self.assertNotIn( - "## Queue time per job", report.render([stats], days=7, now=NOW) - ) - - def test_the_real_command_reads_the_jobs_of_the_run_with_their_creation_time(self): - calls = [] - - def fake(command): - calls.append(command) - return json.dumps({"jobs": [timing("Seal", 5)]}) - - jobs = report.Github(fake).job_timings(REPO, 42) - self.assertEqual(jobs[0]["name"], "Seal") - self.assertEqual(calls[0][:2], ["gh", "api"]) - self.assertIn(f"repos/{REPO}/actions/runs/42/jobs", " ".join(calls[0])) - - def test_a_run_whose_jobs_cannot_be_read_gives_no_timings(self): - def refuse(command): - raise subprocess.CalledProcessError(1, command, stderr="HTTP 404") - - self.assertEqual(report.Github(refuse).job_timings(REPO, 42), []) - - -class RealCommands(unittest.TestCase): - def setUp(self): - self.commands = [] - self.outputs = {} - self.gh = report.Github(self.fake_run) - - def fake_run(self, command): - self.commands.append(command) - key = " ".join(command) - for needle, output in self.outputs.items(): - if needle in key: - return output - return "[]" - - def test_runs_asks_for_the_fields_the_metrics_need(self): - self.gh.runs(REPO, 200) - command = self.commands[0] - self.assertEqual(command[:4], ["gh", "run", "list", "--repo"]) - fields = ( - "databaseId,conclusion,status,workflowName,createdAt,startedAt,updatedAt" - ) - self.assertTrue(any(fields in part for part in command)) - - def test_jobs_reads_the_jobs_of_one_run(self): - self.outputs["run view"] = json.dumps( - {"jobs": [job("Verify", "success", iso(1))]} - ) - self.assertEqual(self.gh.jobs(REPO, 7)[0]["name"], "Verify") - self.assertIn("7", self.commands[0]) - - def test_runners_reads_the_repository_runners(self): - self.outputs["actions/runners"] = json.dumps({"runners": [{"name": "vm-01"}]}) - self.assertEqual(self.gh.runners(REPO)[0]["name"], "vm-01") - - def test_a_repository_without_runner_access_reports_none_instead_of_failing(self): - def refuse(command): - raise subprocess.CalledProcessError(1, command, stderr="HTTP 403") - - self.assertEqual(report.Github(refuse).runners(REPO), []) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_runner_watch.py b/tests/test_runner_watch.py deleted file mode 100644 index 37aa3d5..0000000 --- a/tests/test_runner_watch.py +++ /dev/null @@ -1,239 +0,0 @@ -"""Tests for report/runner_watch.py: when a runner or a queue deserves a toast, and only once.""" - -from __future__ import annotations - -import datetime as dt -import json -import subprocess -import sys -import unittest -from pathlib import Path - -sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "report")) - -import runner_watch as watch - -NOW = dt.datetime(2026, 10, 15, 12, 0, 0, tzinfo=dt.UTC) -ORG = "acme" - - -def ago(minutes: float) -> str: - return (NOW - dt.timedelta(minutes=minutes)).strftime("%Y-%m-%dT%H:%M:%SZ") - - -def snapshot(runners=(), queued=()): - return {"runners": list(runners), "queued": list(queued)} - - -class Offline(unittest.TestCase): - def test_an_online_runner_raises_nothing(self): - alerts, state = watch.evaluate( - snapshot([("acme/a", "a-01", "online")]), {}, NOW - ) - self.assertEqual(alerts, []) - self.assertEqual(state["offline_since"], {}) - - def test_a_runner_just_seen_offline_is_remembered_not_reported(self): - alerts, state = watch.evaluate( - snapshot([("acme/a", "a-01", "offline")]), {}, NOW - ) - self.assertEqual(alerts, []) - self.assertEqual(state["offline_since"], {"acme/a/a-01": ago(0)}) - - def test_it_is_reported_once_it_has_been_offline_long_enough(self): - state = {"offline_since": {"acme/a/a-01": ago(11)}} - alerts, state = watch.evaluate( - snapshot([("acme/a", "a-01", "offline")]), state, NOW - ) - self.assertEqual([a.key for a in alerts], ["offline:acme/a/a-01"]) - self.assertIn("a-01", alerts[0].body) - self.assertIn("11 min", alerts[0].body) - - def test_a_runner_offline_for_less_than_the_threshold_is_not_reported(self): - state = {"offline_since": {"acme/a/a-01": ago(9)}} - alerts, _ = watch.evaluate( - snapshot([("acme/a", "a-01", "offline")]), state, NOW - ) - self.assertEqual(alerts, []) - - def test_the_same_runner_is_not_reported_twice(self): - state = {"offline_since": {"acme/a/a-01": ago(30)}} - alerts, state = watch.evaluate( - snapshot([("acme/a", "a-01", "offline")]), state, NOW - ) - self.assertEqual(len(alerts), 1) - again, _ = watch.evaluate(snapshot([("acme/a", "a-01", "offline")]), state, NOW) - self.assertEqual(again, []) - - def test_a_runner_that_comes_back_is_forgotten_and_can_be_reported_again(self): - state = { - "offline_since": {"acme/a/a-01": ago(30)}, - "alerted": ["offline:acme/a/a-01"], - } - alerts, state = watch.evaluate( - snapshot([("acme/a", "a-01", "online")]), state, NOW - ) - self.assertEqual(alerts, []) - self.assertEqual(state["offline_since"], {}) - self.assertEqual(state["alerted"], []) - - def test_an_ignored_runner_is_never_reported(self): - state = {"offline_since": {"acme/a/a-01": ago(300)}} - alerts, state = watch.evaluate( - snapshot([("acme/a", "a-01", "offline")]), state, NOW, ignore={"a-01"} - ) - self.assertEqual(alerts, []) - self.assertEqual(state["offline_since"], {}) - - def test_a_runner_that_vanished_from_the_list_is_forgotten(self): - state = { - "offline_since": {"acme/a/gone": ago(300)}, - "alerted": ["offline:acme/a/gone"], - } - _, state = watch.evaluate(snapshot([]), state, NOW) - self.assertEqual(state["offline_since"], {}) - self.assertEqual(state["alerted"], []) - - -class Queue(unittest.TestCase): - def test_a_young_queued_run_is_not_reported(self): - alerts, _ = watch.evaluate(snapshot(queued=[("acme/a", 7, ago(14))]), {}, NOW) - self.assertEqual(alerts, []) - - def test_an_old_queued_run_is_reported_once(self): - snap = snapshot(queued=[("acme/a", 7, ago(16))]) - alerts, state = watch.evaluate(snap, {}, NOW) - self.assertEqual([a.key for a in alerts], ["queue:acme/a/7"]) - self.assertIn("16 min", alerts[0].body) - again, _ = watch.evaluate(snap, state, NOW) - self.assertEqual(again, []) - - def test_a_run_that_started_is_forgotten(self): - state = {"alerted": ["queue:acme/a/7"]} - _, state = watch.evaluate(snapshot(queued=[]), state, NOW) - self.assertEqual(state["alerted"], []) - - def test_the_thresholds_are_parameters(self): - snap = snapshot(queued=[("acme/a", 7, ago(5))]) - alerts, _ = watch.evaluate(snap, {}, NOW, queue_min=3) - self.assertEqual(len(alerts), 1) - - -class Collecting(unittest.TestCase): - def test_it_reads_the_organisation_and_the_private_repositories(self): - class Gh: - def org_repos(self, org): - return [ - {"name": "a", "visibility": "PRIVATE", "isArchived": False}, - {"name": "old", "visibility": "PRIVATE", "isArchived": True}, - {"name": "open", "visibility": "PUBLIC", "isArchived": False}, - ] - - def org_runners(self, org): - return [{"name": "pool-01", "status": "online"}] - - def runners(self, repo): - return [{"name": f"{repo}-01", "status": "offline"}] - - def queued_runs(self, repo): - return [{"databaseId": 5, "createdAt": ago(40)}] - - snap = watch.collect(Gh(), ORG) - self.assertIn(("acme", "pool-01", "online"), snap["runners"]) - self.assertIn(("acme/a", "acme/a-01", "offline"), snap["runners"]) - self.assertEqual(snap["queued"], [("acme/a", 5, ago(40))]) - self.assertEqual( - len(snap["runners"]), 2, "archived and public repositories are skipped" - ) - - def test_an_unreadable_part_does_not_stop_the_rest(self): - class Gh: - def org_repos(self, org): - return [{"name": "a", "visibility": "PRIVATE", "isArchived": False}] - - def org_runners(self, org): - raise subprocess.CalledProcessError(1, ["gh"], stderr="HTTP 403") - - def runners(self, repo): - return [{"name": "a-01", "status": "online"}] - - def queued_runs(self, repo): - raise subprocess.CalledProcessError(1, ["gh"], stderr="HTTP 502") - - snap = watch.collect(Gh(), ORG) - self.assertEqual(snap["runners"], [("acme/a", "a-01", "online")]) - self.assertEqual(snap["queued"], []) - - -class RealCommands(unittest.TestCase): - def setUp(self): - self.calls = [] - - def fake(self, command): - self.calls.append(command) - return json.dumps({"runners": [{"name": "pool-01", "status": "online"}]}) - - def test_org_runners_asks_the_organisation_endpoint(self): - runners = watch.Github(self.fake).org_runners(ORG) - self.assertEqual(runners[0]["name"], "pool-01") - self.assertIn("orgs/acme/actions/runners", " ".join(self.calls[0])) - - def test_org_repos_asks_for_visibility_and_archived(self): - watch.Github(lambda c: self.calls.append(c) or "[]").org_repos(ORG) - joined = " ".join(self.calls[0]) - self.assertIn("repo list acme", joined) - self.assertIn("name,visibility,isArchived", joined) - - -class Notifying(unittest.TestCase): - def test_each_alert_becomes_one_toast_command(self): - sent = [] - alerts = [watch.Alert("k1", "T1", "B1"), watch.Alert("k2", "T2", "B2")] - watch.notify(alerts, r"C:\x\notify.ps1", lambda c: sent.append(c)) - self.assertEqual(len(sent), 2) - self.assertIn("-File", sent[0]) - self.assertEqual(sent[0][sent[0].index("-Title") + 1], "T1") - self.assertEqual(sent[1][sent[1].index("-Body") + 1], "B2") - - def test_a_failing_toast_never_raises(self): - def boom(command): - raise OSError("no powershell") - - watch.notify([watch.Alert("k", "T", "B")], "notify.ps1", boom) - - -class Main(unittest.TestCase): - def test_state_is_saved_and_a_second_run_stays_quiet(self): - import tempfile - - class Gh: - def org_repos(self, org): - return [] - - def org_runners(self, org): - return [{"name": "pool-01", "status": "offline"}] - - with tempfile.TemporaryDirectory() as tmp: - path = Path(tmp) / "state.json" - state = {"offline_since": {"acme/pool-01": ago(40)}} - path.write_text(json.dumps(state), encoding="utf-8") - first = watch.run(Gh(), ORG, path, NOW, notify_path=None) - second = watch.run(Gh(), ORG, path, NOW, notify_path=None) - self.assertEqual(len(first), 1) - self.assertEqual(second, []) - self.assertIn( - "offline:acme/pool-01", - json.loads(path.read_text(encoding="utf-8"))["alerted"], - ) - - def test_a_corrupt_state_file_is_a_clean_slate(self): - import tempfile - - with tempfile.TemporaryDirectory() as tmp: - path = Path(tmp) / "state.json" - path.write_text("{not json", encoding="utf-8") - self.assertEqual(watch.load_state(path), {}) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_weekly_report.py b/tests/test_weekly_report.py deleted file mode 100644 index a241137..0000000 --- a/tests/test_weekly_report.py +++ /dev/null @@ -1,191 +0,0 @@ -"""Tests for report/weekly_report.py: the report written to a file, and a toast only for a deviation.""" - -from __future__ import annotations - -import datetime as dt -import sys -import tempfile -import unittest -from pathlib import Path - -sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "report")) - -import ci_report -import weekly_report as weekly - -NOW = dt.datetime(2026, 10, 19, 8, 0, 0, tzinfo=dt.UTC) # a Monday -ORG = "acme" - - -def stats(repo="acme/a", conclusive=20, failed=2, infra=0, p90=None): - s = ci_report.RepoStats( - repo=repo, conclusive=conclusive, failed=failed, infra_failures=infra - ) - s.job_wait_p90_s = p90 - s.jobs_sampled = 1 if p90 is not None else 0 - return s - - -class Deviations(unittest.TestCase): - def test_a_healthy_repository_raises_nothing(self): - self.assertEqual(weekly.find_deviations([stats(failed=2, p90=60)]), []) - - def test_a_high_failure_rate_is_a_deviation(self): - found = weekly.find_deviations([stats(conclusive=20, failed=6)]) - self.assertEqual(len(found), 1) - self.assertIn("acme/a", found[0]) - self.assertIn("30%", found[0]) - - def test_a_few_runs_prove_nothing(self): - # Two failures out of three is noise: below the minimum number of runs nothing is judged. - self.assertEqual(weekly.find_deviations([stats(conclusive=3, failed=2)]), []) - - def test_a_long_queue_is_a_deviation(self): - found = weekly.find_deviations([stats(p90=601)]) - self.assertEqual(len(found), 1) - self.assertIn("10m01s", found[0]) - - def test_infrastructure_failures_are_a_deviation_of_their_own(self): - found = weekly.find_deviations([stats(conclusive=20, failed=4, infra=3)]) - self.assertTrue(any("infrastructure" in f for f in found)) - - def test_the_thresholds_are_parameters(self): - self.assertEqual( - len(weekly.find_deviations([stats(failed=2)], fail_rate_max=0.05)), 1 - ) - self.assertEqual(weekly.find_deviations([stats(p90=601)], wait_p90_max=900), []) - - def test_a_repository_without_data_is_not_judged(self): - self.assertEqual(weekly.find_deviations([stats(conclusive=0, failed=0)]), []) - - -class FakeGithub: - """Just enough of the reads `ci_report.collect` makes.""" - - def __init__(self, failing=False): - self.failing = failing - - def org_repos(self, org): - return [ - {"name": "a", "visibility": "PRIVATE", "isArchived": False}, - {"name": "old", "visibility": "PRIVATE", "isArchived": True}, - {"name": "open", "visibility": "PUBLIC", "isArchived": False}, - ] - - def runs(self, repo, limit): - out = [] - for i in range(10): - conclusion = "failure" if (self.failing and i < 6) else "success" - moment = (NOW - dt.timedelta(hours=i + 1)).strftime("%Y-%m-%dT%H:%M:%SZ") - out.append( - { - "databaseId": i + 1, - "conclusion": conclusion, - "status": "completed", - "workflowName": "CI", - "createdAt": moment, - "startedAt": moment, - "updatedAt": moment, - "event": "push", - "headBranch": "main", - } - ) - return out - - def jobs(self, repo, run_id): - return [ - { - "name": "Verify", - "conclusion": "failure", - "startedAt": None, - "steps": [{"name": "Tests", "conclusion": "failure"}], - } - ] - - def job_timings(self, repo, run_id): - return [] - - def runners(self, repo): - return [] - - def queued_runs(self, repo): - return [] - - def open_prs(self, repo): - return [] - - -class Running(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.out = Path(self.tmp.name) - self.toasts = [] - - def tearDown(self): - self.tmp.cleanup() - - def go(self, gh, notify_path=r"C:\x\notify.ps1"): - return weekly.run( - gh, - ORG, - self.out, - NOW, - days=7, - notify_path=notify_path, - runner=self.toasts.append, - ) - - def test_the_report_is_written_with_the_date_in_its_name_and_as_latest(self): - result = self.go(FakeGithub()) - dated = self.out / "ci-report-2026-10-19.md" - self.assertTrue(dated.exists()) - self.assertEqual( - (self.out / "latest.md").read_text(encoding="utf-8"), - dated.read_text(encoding="utf-8"), - ) - text = dated.read_text(encoding="utf-8") - self.assertIn("# CI health report", text) - self.assertIn("acme/a", text) - self.assertEqual(result.path, dated) - - def test_only_private_repositories_that_are_not_archived_are_reported(self): - self.go(FakeGithub()) - text = (self.out / "latest.md").read_text(encoding="utf-8") - self.assertNotIn("acme/old", text) - self.assertNotIn("acme/open", text) - - def test_a_healthy_week_writes_the_report_and_raises_no_toast(self): - result = self.go(FakeGithub()) - self.assertEqual(result.deviations, []) - self.assertEqual(self.toasts, []) - - def test_a_bad_week_raises_one_toast_naming_the_repositories(self): - result = self.go(FakeGithub(failing=True)) - self.assertGreaterEqual(len(result.deviations), 1) - self.assertEqual(len(self.toasts), 1) - command = self.toasts[0] - self.assertIn("-File", command) - self.assertIn("acme/a", command[command.index("-Body") + 1]) - - def test_without_a_notify_path_nothing_is_toasted(self): - self.go(FakeGithub(failing=True), notify_path=None) - self.assertEqual(self.toasts, []) - - def test_a_failing_toast_never_stops_the_report(self): - def boom(command): - raise OSError("no powershell") - - result = weekly.run( - FakeGithub(failing=True), - ORG, - self.out, - NOW, - days=7, - notify_path="n.ps1", - runner=boom, - ) - self.assertTrue(result.path.exists()) - - -if __name__ == "__main__": - unittest.main() diff --git a/train/automerge.py b/train/automerge.py deleted file mode 100644 index 15b1cc8..0000000 --- a/train/automerge.py +++ /dev/null @@ -1,565 +0,0 @@ -"""Merge sealed pull requests into `main` for every repository of a list (the merge train). - - py -3 automerge.py --config repos.json # one cycle over every repository - py -3 automerge.py --config repos.json --dry-run # say what would happen, change nothing - -GitHub's auto-merge needs branch protection, which free private repositories do not have, so the -desktop does it: a scheduled task runs this every two minutes with the owner's `gh` login. Per -repository and cycle, at most one pull request is merged. A pull request is merged only when all of -this holds, and anything unclear is skipped, never merged: - -- open, into the base branch, not a draft, labelled `automerge`; -- GitHub says it is mergeable (no conflicts); -- the repository's gate check is green on its head commit, and, if `require_seal` is set, its head - carries the `ci-ok/` seal; -- its head contains the base branch. A sealed head that misses commits of the base was never tested - together with them, so the train merges the base into the branch through the API (never a force - push), stops for that cycle, and merges the new head once CI is green again. One stale pull - request is updated per repository and cycle, and only when no other one is ready to merge. - -A conflict (found by GitHub or while updating the branch) is flagged: the pull request gets the -`needs-human` label and loses `automerge`, so the train does not try again until the owner resolves -it and labels it again. The merge pins the exact head (`--match-head-commit`), so a push after the -checks cannot slip in. The configuration is a JSON file, see `repos.example.json`. -""" - -from __future__ import annotations - -import argparse -import datetime as dt -import hashlib -import json -import re -import subprocess -import sys -from collections.abc import Callable -from dataclasses import dataclass -from pathlib import Path - -PR_FIELDS = "number,headRefOid,baseRefName,isDraft,mergeable,labels" -REPO_PATTERN = re.compile(r"^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$") - - -class ConfigError(ValueError): - """The configuration file cannot be used.""" - - -@dataclass(frozen=True) -class Settings: - label: str = "automerge" - needs_human_label: str = "needs-human" - # A workflow run queued this long is logged once: a runner that is offline or saturated holds - # jobs for up to 24 hours before they fail. - queue_alert_minutes: int = 30 - - -@dataclass(frozen=True) -class RepoConfig: - repo: str - gate_check: str = "Gate / Gate" - require_seal: bool = False - base: str = "main" - # How `gh pr merge` merges; a repository may allow only some methods (for example only squash). - merge_method: str = "merge" - - -MERGE_METHODS = ("merge", "squash", "rebase") - - -def load_config(path: Path | str) -> tuple[Settings, list[RepoConfig]]: - try: - data = json.loads(Path(path).read_text(encoding="utf-8")) - except (OSError, json.JSONDecodeError) as exc: - raise ConfigError(f"cannot read {path}: {exc}") from exc - if not isinstance(data, dict): - raise ConfigError("the configuration must be a JSON object") - - defaults = Settings() - settings = Settings( - label=_text(data, "label", defaults.label), - needs_human_label=_text(data, "needs_human_label", defaults.needs_human_label), - queue_alert_minutes=_positive_int( - data, "queue_alert_minutes", defaults.queue_alert_minutes - ), - ) - entries = data.get("repos") - if not isinstance(entries, list) or not entries: - raise ConfigError("`repos` must be a non-empty list") - - repos = [] - for entry in entries: - if not isinstance(entry, dict): - raise ConfigError("every entry of `repos` must be an object") - repo = entry.get("repo") - if not isinstance(repo, str) or not REPO_PATTERN.match(repo): - raise ConfigError(f"`repo` must look like owner/name, got {repo!r}") - require_seal = entry.get("require_seal", False) - if not isinstance(require_seal, bool): - raise ConfigError(f"{repo}: `require_seal` must be true or false") - merge_method = _text(entry, "merge_method", RepoConfig.merge_method) - if merge_method not in MERGE_METHODS: - raise ConfigError( - f"{repo}: `merge_method` must be one of {', '.join(MERGE_METHODS)}" - ) - repos.append( - RepoConfig( - repo=repo, - gate_check=_text(entry, "gate_check", RepoConfig.gate_check), - require_seal=require_seal, - base=_text(entry, "base", RepoConfig.base), - merge_method=merge_method, - ) - ) - return settings, repos - - -def _positive_int(source: dict, key: str, default: int) -> int: - value = source.get(key, default) - if isinstance(value, bool) or not isinstance(value, int) or value < 1: - raise ConfigError(f"`{key}` must be a positive integer") - return value - - -def _text(source: dict, key: str, default: str) -> str: - value = source.get(key, default) - if not isinstance(value, str) or not value: - raise ConfigError(f"`{key}` must be a non-empty string") - return value - - -def run_gh(command: list[str]) -> str: - # Every command is built in this file from fixed words and GitHub's own numbers and shas. - # No console window for `gh`: the task runs every two minutes on the owner's desktop. - no_window = getattr(subprocess, "CREATE_NO_WINDOW", 0) - return subprocess.run( - command, check=True, capture_output=True, text=True, creationflags=no_window - ).stdout - - -class Github: - """The few GitHub operations the train needs, over the `gh` command line.""" - - def __init__(self, run: Callable[[list[str]], str] = run_gh): - self._run = run - - def queued_runs(self, repo: str) -> list[dict]: - out = self._run( - [ - "gh", - "run", - "list", - "--repo", - repo, - "--status", - "queued", - "--json", - "databaseId,createdAt,headBranch,workflowName", - "--limit", - "50", - ] - ) - return json.loads(out or "[]") - - def open_prs(self, repo: str, label: str) -> list[dict]: - out = self._run( - [ - "gh", - "pr", - "list", - "--repo", - repo, - "--state", - "open", - "--label", - label, - "--json", - PR_FIELDS, - "--limit", - "50", - ] - ) - return json.loads(out or "[]") - - def gate_green(self, repo: str, sha: str, check_name: str) -> bool: - out = self._run( - ["gh", "api", f"repos/{repo}/commits/{sha}/check-runs?per_page=100"] - ) - runs = [ - r - for r in json.loads(out or "{}").get("check_runs", []) - if r.get("name") == check_name - ] - return bool(runs) and all( - r.get("status") == "completed" and r.get("conclusion") == "success" - for r in runs - ) - - def sealed(self, repo: str, sha: str) -> bool: - try: - self._run(["gh", "api", f"repos/{repo}/git/ref/tags/ci-ok/{sha}"]) - except subprocess.CalledProcessError: - return False - return True - - def behind_by(self, repo: str, base: str, sha: str) -> int: - out = self._run(["gh", "api", f"repos/{repo}/compare/{base}...{sha}"]) - return int(json.loads(out)["behind_by"]) - - def merge(self, repo: str, number: int, sha: str, method: str = "merge") -> None: - if method not in MERGE_METHODS: - raise ValueError(f"unknown merge method {method!r}") - self._run( - [ - "gh", - "pr", - "merge", - str(number), - "--repo", - repo, - f"--{method}", - "--match-head-commit", - sha, - ] - ) - - def comment(self, repo: str, number: int, body: str) -> None: - self._run(["gh", "pr", "comment", str(number), "--repo", repo, "--body", body]) - - def update_branch(self, repo: str, number: int, sha: str) -> str: - try: - self._run( - [ - "gh", - "api", - "-X", - "PUT", - f"repos/{repo}/pulls/{number}/update-branch", - "-f", - f"expected_head_sha={sha}", - ] - ) - except subprocess.CalledProcessError as exc: - if "conflict" in (exc.stderr or "").lower(): - return "conflict" - raise - return "updated" - - def flag_needs_human( - self, repo: str, number: int, label: str, needs_label: str - ) -> None: - try: - self._run( - [ - "gh", - "label", - "create", - needs_label, - "--repo", - repo, - "--color", - "D93F0B", - "--description", - "A person must resolve this before the merge train retries", - ] - ) - except subprocess.CalledProcessError: - pass # most likely the label exists already; the edit below fails loudly if not - self._run( - [ - "gh", - "pr", - "edit", - str(number), - "--repo", - repo, - "--add-label", - needs_label, - "--remove-label", - label, - ] - ) - - -def classify(pr: dict, cfg: RepoConfig, settings: Settings, gh) -> tuple[str, str]: - """(state, reason) of one pull request: ready, stale, conflict or skip.""" - if settings.label not in {item.get("name") for item in pr.get("labels", [])}: - return "skip", "no automerge label" - if pr.get("isDraft"): - return "skip", "draft" - if pr.get("baseRefName") != cfg.base: - return "skip", f"not into {cfg.base}" - mergeable = pr.get("mergeable") - if mergeable == "CONFLICTING": - return "conflict", "conflicts with the base branch" - if mergeable != "MERGEABLE": - return "skip", f"mergeability is {mergeable}" - - sha = pr["headRefOid"] - if not gh.gate_green(cfg.repo, sha, cfg.gate_check): - return "skip", f"gate check '{cfg.gate_check}' is not green on its head" - if cfg.require_seal and not gh.sealed(cfg.repo, sha): - return "skip", "no ci-ok seal on its head" - behind = gh.behind_by(cfg.repo, cfg.base, sha) - if behind > 0: - return "stale", f"head misses {behind} commit(s) of {cfg.base}" - return "ready", "ready" - - -# Written as a comment on every pull request the train merges; the health report counts the merged -# pull requests that lack it as merged outside the train. -MERGE_MARK = "" - - -def text_version(text: str) -> str: - """A short fingerprint of a script, the same for LF and CRLF copies.""" - normalised = text.replace("\r\n", "\n") - return hashlib.sha256(normalised.encode("utf-8")).hexdigest()[:12] - - -def script_version() -> str: - return text_version(Path(__file__).read_text(encoding="utf-8")) - - -class Heartbeat: - """Decides when the train writes its hourly proof of life, and remembers the last one.""" - - EVERY = dt.timedelta(minutes=60) - - def __init__(self, path: Path | str | None): - self.path = Path(path) if path else None - self._last: dt.datetime | None = None - if self.path is not None and self.path.exists(): - try: - self._last = dt.datetime.fromisoformat( - json.loads(self.path.read_text(encoding="utf-8"))["last"] - ) - except (OSError, ValueError, KeyError, TypeError): - self._last = ( - None # an unreadable state only means one heartbeat too many - ) - - def due(self, now: dt.datetime) -> bool: - return self._last is None or now - self._last >= self.EVERY - - def mark(self, now: dt.datetime) -> None: - self._last = now - if self.path is not None: - self.path.write_text( - json.dumps({"last": now.isoformat()}), encoding="utf-8" - ) - - -class QueueAlerts: - """Remembers which queued runs were already reported, so each one is logged once.""" - - def __init__(self, path: Path | str | None): - self.path = Path(path) if path else None - self._seen: dict[str, list[int]] = {} - if self.path is not None and self.path.exists(): - try: - data = json.loads(self.path.read_text(encoding="utf-8")) - self._seen = {repo: [int(i) for i in ids] for repo, ids in data.items()} - except (OSError, ValueError, TypeError, AttributeError): - self._seen = {} # an unreadable state only means some runs are reported again - - def check( - self, - repo: str, - runs: list[dict], - now: dt.datetime, - threshold_minutes: int, - log: Callable[[str], None], - persist: bool = True, - ) -> None: - known = set(self._seen.get(repo, [])) - keep = known & {run["databaseId"] for run in runs} - for run in sorted(runs, key=lambda item: item["databaseId"]): - run_id = run["databaseId"] - created = dt.datetime.fromisoformat(run["createdAt"]) - minutes = (now - created).total_seconds() / 60 - if minutes >= threshold_minutes and run_id not in known: - log( - f"queued {int(minutes)} min: {run.get('workflowName', '?')} on " - f"{run.get('headBranch', '?')} (run {run_id})" - ) - keep.add(run_id) - if persist and (keep != known or repo not in self._seen): - self._seen[repo] = sorted(keep) - self._save() - - def _save(self) -> None: - if self.path is not None: - self.path.write_text( - json.dumps(self._seen, sort_keys=True), encoding="utf-8" - ) - - -def run_cycle( - gh, - configs: list[RepoConfig], - settings: Settings, - *, - dry_run: bool, - log: Callable[[str], None], - alerts: QueueAlerts | None = None, - now: dt.datetime | None = None, - heartbeat: Heartbeat | None = None, -) -> int: - """One pass over every repository. Returns 0 when nothing went wrong, 1 otherwise.""" - code = 0 - moment = now or dt.datetime.now(dt.UTC) - seen: list[int] = [] - for cfg in configs: - repo_log = lambda line, r=cfg.repo: log(f"{r} {line}") - if alerts is not None: - # A failing queue query must never stop the merging that follows. - try: - runs = gh.queued_runs(cfg.repo) - alerts.check( - cfg.repo, - runs, - moment, - settings.queue_alert_minutes, - repo_log, - persist=not dry_run, - ) - except ( - subprocess.CalledProcessError, - OSError, - ValueError, - KeyError, - ) as exc: - detail = (getattr(exc, "stderr", "") or str(exc)).strip()[:200] - repo_log(f"queue check failed: {detail}") - try: - _repo_cycle(gh, cfg, settings, dry_run, repo_log, seen) - except (subprocess.CalledProcessError, OSError, ValueError, KeyError) as exc: - detail = (getattr(exc, "stderr", "") or str(exc)).strip()[:300] - log(f"{cfg.repo}: failed: {detail}") - code = 1 - if heartbeat is not None and heartbeat.due(moment): - log( - f"heartbeat: {len(configs)} repositories, {sum(seen)} labelled pull requests, " - f"script {script_version()}" - ) - if not dry_run: - heartbeat.mark(moment) - return code - - -def _repo_cycle( - gh, - cfg: RepoConfig, - settings: Settings, - dry_run: bool, - log, - seen: list[int] | None = None, -) -> None: - prs = gh.open_prs(cfg.repo, settings.label) - if seen is not None: - seen.append(len(prs)) # for the heartbeat line - if not prs: - return - states = {} - for pr in sorted(prs, key=lambda p: p["number"]): - states[pr["number"]] = (pr, *classify(pr, cfg, settings, gh)) - for number, (_, state, reason) in sorted(states.items()): - log(f"#{number}: {reason}") - - tag = " (dry run)" if dry_run else "" - for number, (pr, state, _) in sorted(states.items()): - if state == "conflict": - log(f"#{number}: flagged {settings.needs_human_label}{tag}") - if not dry_run: - gh.flag_needs_human( - cfg.repo, number, settings.label, settings.needs_human_label - ) - - ready = [ - (n, pr) for n, (pr, state, _) in sorted(states.items()) if state == "ready" - ] - stale = [ - (n, pr) for n, (pr, state, _) in sorted(states.items()) if state == "stale" - ] - for number, _ in ready[1:]: - log(f"#{number}: waits for the next cycle") - - if ready: - number, pr = ready[0] - if dry_run: - log(f"#{number}: would merge {pr['headRefOid'][:12]} (dry run)") - return - try: - gh.merge(cfg.repo, number, pr["headRefOid"], cfg.merge_method) - except subprocess.CalledProcessError as exc: - log(f"#{number}: merge refused: {(exc.stderr or '').strip()[:300]}") - raise - log(f"#{number}: merged {pr['headRefOid'][:12]}") - # The mark tells apart a merge made by the train from one made around it (FR13). The merge - # is already done: a failing comment is logged, never an error of the cycle. - try: - gh.comment( - cfg.repo, - number, - f"{MERGE_MARK}\nMerged by the merge train at head `{pr['headRefOid'][:12]}`.", - ) - except subprocess.CalledProcessError as exc: - log(f"#{number}: mark failed: {(exc.stderr or '').strip()[:200]}") - elif stale: - number, pr = stale[0] - if dry_run: - log(f"#{number}: would merge {cfg.base} into the branch (dry run)") - return - if gh.update_branch(cfg.repo, number, pr["headRefOid"]) == "conflict": - log(f"#{number}: update conflicts, flagged {settings.needs_human_label}") - gh.flag_needs_human( - cfg.repo, number, settings.label, settings.needs_human_label - ) - else: - log( - f"#{number}: {cfg.base} merged into the branch; waiting for a new green gate" - ) - - -def main(argv: list[str] | None = None) -> int: - parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - parser.add_argument( - "--config", - default=str(Path(__file__).with_name("repos.json")), - help="JSON list of repositories (default: repos.json beside this script)", - ) - parser.add_argument( - "--dry-run", action="store_true", help="say what would happen, change nothing" - ) - parser.add_argument("--log", help="append to this file instead of printing") - args = parser.parse_args(argv) - - def log(message: str) -> None: - line = f"[{dt.datetime.now().isoformat(timespec='seconds')}] {message}" - if args.log: - # The scheduled task runs under pythonw, which has no console: the log is the only trace. - with open(args.log, "a", encoding="utf-8") as handle: - handle.write(line + "\n") - else: - print(line, flush=True) - - try: - settings, configs = load_config(args.config) - except ConfigError as exc: - log(f"configuration error: {exc}") - return 2 - alerts = QueueAlerts(Path(args.config).with_name("queue-alerts.json")) - heartbeat = Heartbeat(Path(args.config).with_name("heartbeat.json")) - return run_cycle( - Github(), - configs, - settings, - dry_run=args.dry_run, - log=log, - alerts=alerts, - heartbeat=heartbeat, - ) - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/train/install.ps1 b/train/install.ps1 deleted file mode 100644 index df25723..0000000 --- a/train/install.ps1 +++ /dev/null @@ -1,78 +0,0 @@ -# Installs the merge train on the desktop: every two minutes, one cycle over the repositories listed -# in repos.json (see automerge.py). Run it from a normal PowerShell window of the owner's session: -# scheduled tasks created from a sandboxed or elevated shell can be private to that shell. -# -# powershell -NoProfile -ExecutionPolicy Bypass -File train\install.ps1 -# powershell -NoProfile -ExecutionPolicy Bypass -File train\install.ps1 -Remove -# -# The script is copied to $Destination, so the task does not depend on which branch a checkout is -# on (learned the hard way). Run this again after automerge.py changes. -# repos.json is created from repos.example.json only when it does not exist; it is never overwritten. -# The task uses the owner's `gh` login; nothing else is stored. -param( - [string]$Destination = 'D:\Development\Tools\ci-train', - [switch]$Remove -) - -$ErrorActionPreference = 'Stop' -$taskName = 'CI train' - -if ($Remove) { - Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue - Write-Host "Task '$taskName' removed. Files in $Destination are left in place." - exit 0 -} - -if (-not (Get-Command gh -ErrorAction SilentlyContinue)) { throw 'gh is not installed' } -gh auth status *> $null -if ($LASTEXITCODE -ne 0) { throw 'gh is not signed in: run gh auth login' } - -# The real pythonw.exe, not the `pyw` launcher: under the task scheduler the launcher exited with -# code 2 and wrote nothing, while the interpreter itself runs fine. -$python = (py -3 -c "import sys;print(sys.executable)") -$pythonw = Join-Path (Split-Path $python) 'pythonw.exe' -if (-not (Test-Path $pythonw)) { throw "pythonw.exe not found at $pythonw" } - -$source = $PSScriptRoot -$script = Join-Path $Destination 'automerge.py' -$config = Join-Path $Destination 'repos.json' -$log = Join-Path $Destination 'train.log' - -New-Item -ItemType Directory -Force -Path $Destination | Out-Null -Copy-Item -Force (Join-Path $source 'automerge.py') $script -if (-not (Test-Path $config)) { - Copy-Item (Join-Path $source 'repos.example.json') $config - Write-Host "Created $config from the example. Review the list of repositories." -} - -# pythonw: no console window flashing every two minutes; the script writes its own log. -# No -WorkingDirectory: with it the task failed with 0x8007010B on this desktop (30/09/2026), -# although the directory exists; every path below is absolute anyway. -$action = New-ScheduledTaskAction ` - -Execute $pythonw ` - -Argument "`"$script`" --config `"$config`" --log `"$log`"" -$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes(1) ` - -RepetitionInterval (New-TimeSpan -Minutes 2) -$settings = New-ScheduledTaskSettingsSet ` - -MultipleInstances IgnoreNew ` - -ExecutionTimeLimit (New-TimeSpan -Minutes 5) ` - -AllowStartIfOnBatteries ` - -DontStopIfGoingOnBatteries ` - -StartWhenAvailable -$principal = New-ScheduledTaskPrincipal -UserId "$env:USERDOMAIN\$env:USERNAME" ` - -LogonType Interactive -RunLevel Limited - -Register-ScheduledTask ` - -TaskName $taskName ` - -Action $action ` - -Trigger $trigger ` - -Settings $settings ` - -Principal $principal ` - -Description 'Merges pull requests labelled automerge whose gate is green and whose head contains main.' ` - -Force | Out-Null - -Write-Host "Task '$taskName' installed: every 2 minutes." -Write-Host " Configuration: $config" -Write-Host " Log: $log" -Write-Host " Try without merging: py -3 `"$script`" --config `"$config`" --dry-run" -Write-Host " Remove: train\install.ps1 -Remove" diff --git a/train/repos.example.json b/train/repos.example.json deleted file mode 100644 index 0093808..0000000 --- a/train/repos.example.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "label": "automerge", - "needs_human_label": "needs-human", - "repos": [ - { "repo": "your-org/service-a" }, - { "repo": "your-org/service-b" }, - { "repo": "your-org/web-app", "merge_method": "squash" }, - { "repo": "your-org/tooling" } - ] -}