diff --git a/.github/tests/pr-route.sh b/.github/tests/pr-route.sh new file mode 100644 index 0000000..0f9901b --- /dev/null +++ b/.github/tests/pr-route.sh @@ -0,0 +1,208 @@ +#!/usr/bin/env bash +# Fixture tests for the inline classifier of .github/workflows/pr-route.yml. The allowlists and cases reproduce +# the routers it replaces (api-kit and genre-kit scripts/pytest_route.py, pipelines scripts/ci_route.py). +set -euo pipefail + +workflow="$(cd "$(dirname "$0")/.." && pwd)/workflows/pr-route.yml" +work="$(mktemp -d "${TMPDIR:-/tmp}/pr-route-test.XXXXXX")" +trap 'rm -rf "$work"' EXIT + +# The classifier is the heredoc body of the "Classify changed paths" step, indented by 10 spaces. +awk "/python3 -I - <<'PY'/{on=1;next} on&&/^ *PY\$/{exit} on{sub(/^ {10}/,\"\");print}" "$workflow" > "$work/route.py" +[ -s "$work/route.py" ] || { echo 'could not extract the classifier' >&2; exit 1; } + +python3 -I - "$work" <<'PY' +import json +import os +import subprocess +import sys + +work = sys.argv[1] +RULES = ".github/pr-route.json" +CALLER = ".github/workflows/ci.yml" +SHARED_WORKFLOWS = [f".github/workflows/{n}.yml" for n in ("agent-drift", "org-conformance", "release")] + + +def rules(files=(), prefixes=(), suffixes=(), build_inputs=()): + return json.dumps( + {"skip_files": list(files), "skip_prefixes": list(prefixes), "skip_suffixes": list(suffixes), + "build_inputs": list(build_inputs)} + ) + + +API_KIT = rules( + ["LICENSE", ".release-please-manifest.json", "release-please-config.json", ".github/release-policy.json", + ".github/workflows/pr-title.yml", *SHARED_WORKFLOWS], + [".github/skills/", ".pr-descriptions/"], + [".md"], +) +GENRE_KIT = rules( + ["LICENSE", "packages/genre-graph/LICENSE", ".release-please-manifest.json", "release-please-config.json", + ".github/release-policy.json", ".github/genre-graph-release-policy.json", ".github/workflows/pr-title.yml", + *SHARED_WORKFLOWS], + [".agents/", ".claude/", ".github/skills/"], + [".md"], + ["README.md", "packages/genre-graph/README.md", "LICENSE", "packages/genre-graph/LICENSE"], +) +PIPELINES = rules( + ["LICENSE", "VERSION", ".gitignore", ".agent-tmp/.gitignore", ".pre-commit-config.yaml", "renovate.json", + ".github/actionlint.yaml", ".github/release-policy.json", ".github/workflows/live-contract.yml", + ".github/workflows/release-tag.yml", *SHARED_WORKFLOWS], + ["docs/", ".agents/", ".claude/", ".github/skills/"], + [".md"], + ["pipelines/*/README.md"], +) + +env = {**os.environ, "GIT_AUTHOR_NAME": "t", "GIT_AUTHOR_EMAIL": "t@example.com", "GIT_COMMITTER_NAME": "t", + "GIT_COMMITTER_EMAIL": "t@example.com", "GIT_CONFIG_GLOBAL": "/dev/null"} +counter = 0 +failures = [] + + +def git(repo, *args, stdin=None): + return subprocess.run(["git", "-C", repo, *args], check=True, capture_output=True, input=stdin, env=env).stdout + + +def commit(repo, files, parent=None, gitlinks=None): + """Commit exactly `files` (path -> content) through the index, so any byte sequence can be a path.""" + git(repo, "read-tree", "--empty") + for path, content in files.items(): + blob = git(repo, "hash-object", "-w", "--stdin", stdin=content.encode()).strip().decode() + git(repo, "update-index", "--add", "--cacheinfo", "100644", blob, path) + for path, sha in (gitlinks or {}).items(): + git(repo, "update-index", "--add", "--cacheinfo", "160000", sha, path) + tree = git(repo, "write-tree").strip().decode() + parents = ["-p", parent] if parent else [] + return git(repo, "commit-tree", tree, "-m", "c", *parents).strip().decode() + + +def check(name, expected, ruleset, changes, head_rules=None, rules_path=RULES, base_only=None, submodule=False, + **overrides): + """changes: (status, path[, content]) tuples, status among A, M, D. base_only: files the base branch gained after + the PR forked.""" + global counter + counter += 1 + repo = os.path.join(work, f"repo{counter}") + subprocess.run(["git", "init", "-q", repo], check=True, env=env) + fork = {"keep": "k"} + if ruleset is not None: + fork[rules_path] = ruleset + for status, path, *content in changes: + # The base ruleset stays valid, otherwise a rules file change would fail closed and prove nothing. + if status != "A" and path != rules_path: + fork[path] = content[0] if content else "old" + head = dict(fork) + for status, path, *content in changes: + if status == "D": + del head[path] + else: + # Distinct default content per path keeps the fixture independent of rename detection. + head[path] = content[0] if content else f"new {path!r}" + if head_rules is not None: + head[rules_path] = head_rules + links = [None, None] + if submodule: + modules = '[submodule "sub"]\n\tpath = sub\n\turl = ./sub\n\tignore = all\n' + fork[".gitmodules"] = head[".gitmodules"] = modules + with open(os.path.join(repo, ".gitmodules"), "w") as handle: + handle.write(modules) + links = [{"sub": "1" * 40}, {"sub": "2" * 40}] + base_sha = commit(repo, fork, gitlinks=links[0]) + head_sha = commit(repo, head, base_sha, gitlinks=links[1]) + if base_only is not None: + base_sha = commit(repo, {**fork, **base_only}, base_sha, gitlinks=links[0]) + output = os.path.join(repo, "output") + run_env = {**env, "EVENT_NAME": "pull_request", "BASE_SHA": base_sha, "HEAD_SHA": head_sha, "RULES_FILE": rules_path, + "REPOSITORY": "org/repo", "CALLER_WORKFLOW_REF": f"org/repo/{CALLER}@refs/pull/1/merge", + "GITHUB_OUTPUT": output, **overrides} + proc = subprocess.run([sys.executable, "-I", os.path.join(work, "route.py")], cwd=repo, env=run_env, + capture_output=True) + got = open(output).read() if os.path.exists(output) else "" + if proc.returncode or got != f"applicable={expected}\n": + failures.append(f"{name}: expected {expected}, exit {proc.returncode}, got {got!r}\n" + f"{proc.stdout.decode(errors='replace')}{proc.stderr.decode(errors='replace')}") + + +def m(*paths): + return [("M", p) for p in paths] + + +# api-kit +for paths in (["README.md"], ["CHANGELOG.md", "LICENSE"], + [".github/skills/code-review/SKILL.md", ".pr-descriptions/x.md"]): + check(f"api-kit skip {paths}", "false", API_KIT, m(*paths)) +for paths in ([], ["src/the_music_tree_api_kit/filters.py"], ["tests/test_smoke.py"], ["pyproject.toml"], ["uv.lock"], + [".github/workflows/validate.yml"], ["baselines/ruff.toml"], ["README.md", "pyproject.toml"]): + check(f"api-kit full {paths}", "true", API_KIT, m(*paths)) + +# genre-kit +for changes in (m("README.md"), m("CHANGELOG.md", "LICENSE"), + [("A", "docs/genre-graph-v2.md"), ("M", ".agents/rules/model-migrations.md")], + m(".github/skills/code-review/SKILL.md", ".github/release-policy.json"), + [("D", "docs/old.md"), ("A", "docs/new.md")]): + check(f"genre-kit skip {changes}", "false", GENRE_KIT, changes) +for changes in ([], m("src/the_music_tree_genre_kit/checks.py"), m("tests/test_pytest_route.py"), m("pyproject.toml"), + m("uv.lock"), m(".github/workflows/validate.yml"), m("scripts/pytest_route.py"), + m("README.md", "pyproject.toml"), [("D", "README.md")], [("D", "packages/genre-graph/README.md")], + [("D", "LICENSE")], [("D", "src/x.py"), ("A", "docs/x.md")]): + check(f"genre-kit full {changes}", "true", GENRE_KIT, changes) + +# pipelines +for changes in (m("README.md", "pipelines/gold/DESIGN.md", "docs/validation/p706_topology.py"), + m(".agents/skills/x/SKILL.md", ".claude/settings.json", ".github/skills/code-review/SKILL.md"), + m(".github/workflows/release.yml", "VERSION", "CHANGELOG.md"), + [("D", "docs/a.md"), ("A", "docs/b.md")], + [("D", "pipelines/gold/src/gold/schemas/README.md")], + m("docs/a b.md", "LICENSE")): + check(f"pipelines skip {changes}", "false", PIPELINES, changes) +for changes in (m("README.md", "pipelines/gold/src/gold/__main__.py"), m(".github/workflows/ci.yml"), m("uv.lock"), + m("scripts/ci_route.py"), [], [("D", "pipelines/common/src/common/x.py"), ("A", "docs/x.md")], + [("D", "pipelines/gold/README.md")], [("D", "docs/a.md"), ("A", "moved.py"), ("D", "keep.py")]): + check(f"pipelines full {changes}", "true", PIPELINES, changes) +# Intended difference with ci_route.py: only losing a package readme breaks the build. +check("pipelines modified package readme", "false", PIPELINES, m("pipelines/gold/README.md")) +check("non-UTF-8 path", "true", PIPELINES, m(b"\xff.md".decode("utf-8", "surrogateescape"))) + +# fail closed +DOC = m("README.md") +for event in ("push", "merge_group", "workflow_dispatch", "pull_request_target"): + check(f"event {event}", "true", API_KIT, DOC, EVENT_NAME=event) +check("missing rules file", "true", None, DOC) +check("rules added by the PR only", "true", None, DOC, head_rules=API_KIT) +check("head cannot loosen the rules", "true", API_KIT, m("src/x.py"), head_rules=rules(suffixes=[".py", ".json"])) +for name, bad in (("not JSON", "{"), ("not an object", "[]"), ("missing key", '{"skip_files": []}'), + ("unknown key", json.dumps({**json.loads(API_KIT), "skip": []})), + ("not a list", json.dumps({**json.loads(API_KIT), "skip_files": "LICENSE"})), + ("empty prefix", rules(prefixes=[""], suffixes=[".md"]))): + check(f"invalid rules: {name}", "true", bad, DOC) +check("unknown base commit", "true", API_KIT, DOC, BASE_SHA="0" * 40) +check("empty base commit", "true", API_KIT, DOC, BASE_SHA="") +check("foreign caller ref", "true", API_KIT, DOC, CALLER_WORKFLOW_REF="other/repo/.github/workflows/ci.yml@main") + +# CI definitions +check("rules file is never skippable", "true", rules([RULES], [".github/"], [".json"]), m(RULES)) +check("caller workflow is never skippable", "true", rules([CALLER]), m(CALLER)) +check("suffix and prefix never cover workflows", "true", rules(prefixes=[".github/"], suffixes=[".yml"]), + m(".github/workflows/other.yml")) +check("prefix covers other .github files", "false", rules(prefixes=[".github/"]), m(".github/dependabot.yml")) +PERF = ".github/pr-route-perf.json" +check("alternate rules file", "false", rules(suffixes=[".md"]), DOC, rules_path=PERF) +check("alternate rules file is never skippable", "true", rules(suffixes=[".json"]), m(PERF), rules_path=PERF) +check("non-canonical rules path stays protected", "true", rules(suffixes=[".json"]), m(RULES), RULES_FILE=f"./{RULES}") + +# diff and base commit +check("identical doc rename", "false", rules(suffixes=[".md"]), [("D", "a.md", "same"), ("A", "b.md", "same")]) +check("identical rename from source to doc", "true", rules(suffixes=[".md"]), + [("D", "a.py", "same"), ("A", "a.md", "same")]) +check("base branch advances are not part of the PR", "false", rules(suffixes=[".md"]), DOC, + base_only={"src/x.py": "base"}) +check("rules come from the base commit, not the head", "false", rules(suffixes=[".md"]), m("src/x.py"), + base_only={RULES: rules(suffixes=[".py"])}) +check("rules tightened on base apply", "true", rules(suffixes=[".md"]), DOC, base_only={RULES: rules()}) +check("ignored submodule change is seen", "true", rules([".gitmodules"], suffixes=[".md"]), DOC, submodule=True) + +if failures: + print("\n".join(failures), file=sys.stderr) + sys.exit(f"{len(failures)} of {counter} pr-route cases failed") +print(f"ok: {counter} pr-route cases") +PY diff --git a/.github/workflows/pr-route.yml b/.github/workflows/pr-route.yml new file mode 100644 index 0000000..bd8c30f --- /dev/null +++ b/.github/workflows/pr-route.yml @@ -0,0 +1,151 @@ +# PR test routing (BehindTheMusicTree/github-config#85): `applicable=false` skips the test jobs of the caller only when +# every changed path is explicitly known to have no effect on them. Anything else runs everything. +# Rules live in the caller repository and are read from the PR base commit, so a PR cannot loosen its own rule. +# `applicable` is the scope output of the `Tests success` gate recognized by github-config check-required-gates.sh. +# Concurrency is owned by the calling workflow, as for the other reusable workflows of this repository. +name: PR route + +on: + workflow_call: + inputs: + rules-file: + description: >- + JSON rules in the caller repository, with the string arrays skip_files, skip_prefixes, skip_suffixes + (paths without effect on the routed jobs) and build_inputs (paths whose deletion runs everything; + `*` matches within one path segment) + default: .github/pr-route.json + type: string + runs-on: + description: Runner label + default: ubuntu-latest + type: string + timeout-minutes: + description: Job timeout in minutes + default: 5 + type: number + outputs: + applicable: + description: "false when every changed path of the pull request is skippable, true otherwise" + value: ${{ jobs.route.outputs.applicable }} + +permissions: + contents: read + +jobs: + route: + runs-on: ${{ inputs.runs-on }} + timeout-minutes: ${{ inputs.timeout-minutes }} + outputs: + applicable: ${{ steps.route.outputs.applicable }} + steps: + - uses: actions/checkout@v5 + if: ${{ github.event_name == 'pull_request' }} + with: + fetch-depth: 0 + persist-credentials: false + - name: Classify changed paths + id: route + env: + EVENT_NAME: ${{ github.event_name }} + BASE_SHA: ${{ github.event.pull_request.base.sha }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + RULES_FILE: ${{ inputs.rules-file }} + REPOSITORY: ${{ github.repository }} + CALLER_WORKFLOW_REF: ${{ github.workflow_ref }} + run: | + python3 -I - <<'PY' + import json + import os + import posixpath + import subprocess + from fnmatch import fnmatchcase + + KEYS = ("skip_files", "skip_prefixes", "skip_suffixes", "build_inputs") + + + def annotation(level, message): + escaped = message.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A") + print(f"::{level}::{escaped}") + + + def git(*args): + return subprocess.run(["git", *args], check=True, capture_output=True).stdout + + + def load_rules(base, rules_file): + rules = json.loads(git("show", f"{base}:{rules_file}")) + if not isinstance(rules, dict) or set(rules) != set(KEYS): + raise ValueError(f"{rules_file} must be an object with exactly the keys {', '.join(KEYS)}") + for key in KEYS: + values = rules[key] + # An empty prefix or suffix would match every path. + if not isinstance(values, list) or not all(isinstance(v, str) and v for v in values): + raise ValueError(f"{rules_file}: {key} must be a list of non-empty strings") + return rules + + + def changed_paths(base, head): + raw = git("diff", "--no-renames", "--ignore-submodules=none", "-z", "--name-status", f"{base}...{head}") + tokens = raw.decode("utf-8").split("\0") + if tokens[-1] == "": + tokens.pop() + if len(tokens) % 2: + raise ValueError("malformed diff") + return list(zip(tokens[::2], tokens[1::2])) + + + def matches(path, pattern): + parts, wanted = path.split("/"), pattern.split("/") + return len(parts) == len(wanted) and all(map(fnmatchcase, parts, wanted)) + + + def is_skippable(rules, protected, status, path): + if path in protected: + return False + if status.startswith("D") and any(matches(path, p) for p in rules["build_inputs"]): + return False + if path in rules["skip_files"]: + return True + # A workflow file is skippable only when listed by name: a broad prefix or suffix never covers CI. + if path.startswith(".github/workflows/"): + return False + return path.startswith(tuple(rules["skip_prefixes"])) or path.endswith(tuple(rules["skip_suffixes"])) + + + def applicable(): + if os.environ["EVENT_NAME"] != "pull_request": + print("Not a pull request: running everything") + return True + base, head = os.environ["BASE_SHA"], os.environ["HEAD_SHA"] + # Normalized so that the rules file matches its own path in the diff. + rules_file = posixpath.normpath(os.environ["RULES_FILE"]) + prefix = os.environ["REPOSITORY"] + "/" + caller = os.environ["CALLER_WORKFLOW_REF"].split("@", 1)[0] + if not base or not head or not caller.startswith(prefix): + raise ValueError("pull request commits or caller workflow unknown") + rules = load_rules(base, rules_file) + protected = {rules_file, caller[len(prefix):]} + changes = changed_paths(base, head) + if not changes: + annotation("warning", "Empty diff: running everything") + return True + offending = [path for status, path in changes if not is_skippable(rules, protected, status, path)] + for path in offending[:5]: + print(f"Runs everything: {path!r}") + return bool(offending) + + + try: + result = applicable() + except subprocess.CalledProcessError as error: + annotation("warning", f"Running everything: {error.stderr.decode('utf-8', 'replace').strip()}") + result = True + except Exception as error: + annotation("warning", f"Running everything: {error}") + result = True + + line = f"applicable={str(result).lower()}" + print(line) + with open(os.environ["GITHUB_OUTPUT"], "a") as output: + output.write(line + "\n") + PY diff --git a/.github/workflows/test-actions.yml b/.github/workflows/test-actions.yml index 5ae05b2..d11920a 100644 --- a/.github/workflows/test-actions.yml +++ b/.github/workflows/test-actions.yml @@ -76,6 +76,15 @@ jobs: - name: Verify thresholds, missing data and patch coverage run: bash .github/tests/coverage.sh + pr-route-tests: + name: pr-route workflow fixtures + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@v5 + - name: Verify the routing rules of the replaced routers + run: bash .github/tests/pr-route.sh + release-script-tests: name: release script tests runs-on: ubuntu-latest diff --git a/README.md b/README.md index 5dbbdc2..90c682f 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ Contributions are welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines - [Org conformance](#org-conformance) - [Agent drift](#agent-drift) - [Coverage](#coverage) + - [PR route](#pr-route) - [Actionlint](#actionlint) - [Python publication](#python-publication) - [Call Redeployment Webhook](#call-redeployment-webhook) @@ -317,6 +318,43 @@ jobs: Require `Tests success` only; the test jobs and `coverage` are declared optional in `BehindTheMusicTree/github-config`, which fails the repository when the gate does not need a job calling this workflow. A caller with a docs-only skip uses the scoped gate (`classify` job exposing `outputs.applicable`) described in that repository's README. +### PR route + +Skips the test jobs of a pull request only when every changed path is explicitly known to have no effect on them (`BehindTheMusicTree/github-config#85`). It outputs `applicable` (`true`/`false`), the scope output of the scoped `Tests success` gate. + +**Workflow file:** `.github/workflows/pr-route.yml` + +| Input | Default | Description | +| ----------------- | ----------------------- | ------------------------------------------------- | +| `rules-file` | `.github/pr-route.json` | Rules of the caller; a second scope uses another file. | +| `runs-on` | `ubuntu-latest` | Runner label. | +| `timeout-minutes` | `5` | Job timeout. | + +The rules file holds exactly these four arrays of non-empty strings: + +```json +{ + "skip_files": ["LICENSE", ".github/workflows/release.yml"], + "skip_prefixes": ["docs/", ".agents/"], + "skip_suffixes": [".md"], + "build_inputs": ["LICENSE", "packages/*/README.md"] +} +``` + +`build_inputs` lists files the build reads: deleting (or renaming away) one runs everything, and `*` matches within one path segment. Add a path to the rules only after checking that the routed jobs do not read it. + +Rules are read from the PR base commit, so a PR that changes them is judged by the previous ones. `applicable` is `true` outside `pull_request` events, on an empty or unreadable diff, on a missing or invalid rules file (with a warning annotation) and on any unlisted path. The rules file and the calling workflow are never skippable; another workflow file is skippable only when named in `skip_files`. + +```yaml +jobs: + route: + uses: BehindTheMusicTree/github-workflows/.github/workflows/pr-route.yml@ + tests: + needs: [route] + if: needs.route.outputs.applicable == 'true' + # ... +``` + ### Actionlint Runs [actionlint](https://github.com/rhysd/actionlint) on the caller repo. Uses `.github/actionlint.yaml` from the caller if present, so repo-specific ignore rules (e.g. for reusable workflow calls) apply.