Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions .github/workflows/ci-ready.yml
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,13 @@ jobs:
run: python -m pip install -e ".[dev]"
- name: Ruff
run: ruff check src tests tools
- name: Architecture anchor drift (advisory)
continue-on-error: true
run: python -m pytest -q tests/test_architecture_anchors.py::test_architecture_anchors_resolve_to_existing_sources_and_checks
- name: Tests (smoke + unit)
run: pytest -rs
run: >-
pytest -rs --deselect
tests/test_architecture_anchors.py::test_architecture_anchors_resolve_to_existing_sources_and_checks

dashboard-browser:
if: ${{ github.event_name == 'pull_request' && !github.event.pull_request.draft }}
Expand Down Expand Up @@ -99,18 +104,21 @@ jobs:

pr-references:
if: github.event_name == 'pull_request'
# Reports closing syntax in PR body text at each ready-lane event; not a branch-protection gate.
# Advisory PR body and contract-scope feedback at each ready-lane event.
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
contents: read
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 2
persist-credentials: false
- name: Reject closing syntax inside PR body text
- name: Check PR references and advise on contract scope
env:
PR_BODY: ${{ github.event.pull_request.body }}
PR_BASE_SHA: ${{ github.event.pull_request.base.sha }}
PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
run: python3 tools/check_pr_references.py

host-compatibility:
Expand Down
97 changes: 97 additions & 0 deletions tests/test_architecture_anchors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import re
import subprocess
import sys
from pathlib import Path
from urllib.parse import SplitResult, unquote, urlsplit

import pytest

from tools.check_pr_references import anchor_section

ROOT = Path(__file__).resolve().parents[1]
ARCHITECTURE = ROOT / "docs" / "architecture.md"
CODE_FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})([^\n]*)$")
HEADING = re.compile(r"^#{1,6}[ \t]+([^\n]+)$")


def _heading_ids(path: Path) -> set[str]:
ids: set[str] = set()
fence = ""
for line in path.read_text(encoding="utf-8").split("\n"):
marker = CODE_FENCE.fullmatch(line)
if fence:
if marker and marker[1].startswith(fence) and not marker[2].strip(" \t"):
fence = ""
continue
if marker and (marker[1][0] == "~" or "`" not in marker[2]):
fence = marker[1]
continue
heading = HEADING.fullmatch(line)
if not heading:
continue
text = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", heading[1]).strip(" #")
slug = re.sub(r"[^\w -]", "", text.lower()).replace(" ", "-")
unique = slug
suffix = 1
while unique in ids:
unique = f"{slug}-{suffix}"
suffix += 1
ids.add(unique)
return ids


def _links(text: str) -> list[SplitResult]:
return [urlsplit(url) for url in re.findall(r"\]\(([^)\s]+)\)", text)]


@pytest.mark.parametrize(("opening", "shorter", "closing"), [
("```bash", "~~~", "```"),
(" ```` bash", "```", " `````"),
("~~~sh", "```", "~~~"),
])
def test_heading_ids_ignore_code_fences(tmp_path, opening, shorter, closing):
document = tmp_path / "target.md"
document.write_text(
f"# Policy\n{opening}\n# Policy\n{shorter}\n# Install dependencies\n"
f"{closing}\n# Policy\n",
encoding="utf-8",
)
assert _heading_ids(document) == {"policy", "policy-1"}


def test_architecture_anchors_resolve_to_existing_sources_and_checks():
section = anchor_section(ARCHITECTURE.read_text(encoding="utf-8"))
assert section, "docs/architecture.md needs an Architecture anchors section"
_, *entries = re.split(r"^###[ \t]+([^\n]+)\n", section, flags=re.MULTILINE)
assert 1 <= len(entries) // 2 <= 10

test_refs = set()
for number, (title, content) in enumerate(zip(entries[::2], entries[1::2]), 1):
assert title.startswith(f"A{number} — "), f"Expected A{number}, got {title}"
summary, marker, checks = content.partition("**Checked by**")
assert marker and checks.strip(), f"{title} needs a Checked by line"
assert any(
link.fragment and not (link.scheme or link.netloc) for link in _links(summary)
), f"{title} needs a source heading"
for link in _links(content):
if link.scheme or link.netloc:
continue
destination = (
(ARCHITECTURE.parent / unquote(link.path)).resolve()
if link.path else ARCHITECTURE
)
assert destination.is_relative_to(ROOT) and destination.is_file(), (title, link)
if link.fragment:
assert unquote(link.fragment) in _heading_ids(destination), (title, link)
test_refs.update(re.findall(r"`(tests/[^`\n]+)`", checks))

if test_refs:
for ref in test_refs:
path = (ROOT / ref.partition("::")[0]).resolve()
assert path.is_relative_to(ROOT / "tests") and path.is_file(), ref
command = [sys.executable, "-m", "pytest", "--collect-only", "-q", "-o", "addopts="]
result = subprocess.run(
[*command, *sorted(test_refs)],
cwd=ROOT, capture_output=True, text=True, check=False,
)
assert result.returncode == 0, result.stdout + result.stderr
105 changes: 105 additions & 0 deletions tests/test_pr_references.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from io import BytesIO
from pathlib import Path

import pytest
Expand Down Expand Up @@ -81,3 +82,107 @@ def test_main_passes_silently(monkeypatch, capsys):
monkeypatch.setenv("PR_BODY", "Refs #1\nRefs #3\n")
assert check.main() == 0
assert capsys.readouterr().out == ""


@pytest.mark.parametrize(("changes", "before", "after", "expected"), [
("", "", "", False),
("M\0docs/contracts/current-design.md\0", "", "", True),
("D\0docs/module-layout.md\0", "", "", True),
("A\0docs/legacy-knowledge-manifest.json\0", "", "", True),
("M\0docs/architecture.md\0", "Before", "After", False),
(
"M\0docs/architecture.md\0",
"## Architecture anchors\nA1\n## Other\nBefore",
"## Architecture anchors\nA1\n## Other\nAfter",
False,
),
(
"M\0docs/architecture.md\0",
"## Architecture anchors\nOld",
"## Architecture anchors\nNew",
True,
),
("D\0docs/architecture.md\0", "## Architecture anchors\nA1", None, True),
("A\0docs/architecture.md\0", None, "## Architecture anchors\nA1", True),
])
def test_contract_diff_at_pr_merge_commit(monkeypatch, changes, before, after, expected):
git_output = {
("show", "-s", "--format=%P", "HEAD"): "base head\n",
(
"diff", "--name-status", "--no-renames", "-z", "HEAD^1", "HEAD",
"--", *check.CONTRACT_PATHS,
): changes,
}
if before is not None:
git_output[("show", "HEAD^1:docs/architecture.md")] = before
if after is not None:
git_output[("show", "HEAD:docs/architecture.md")] = after
monkeypatch.setattr(check, "_git", lambda *args: git_output[args])
assert check.contracts_changed("base", "head") is expected
with pytest.raises(ValueError, match="Checkout does not match"):
check.contracts_changed("other-base", "head")


@pytest.mark.parametrize("body", ["Refs owner/repo#574", "See #574", ""])
def test_contract_advice_requires_plain_same_repo_reference(monkeypatch, body):
def unexpected_lookup(*args):
pytest.fail("An invalid reference reached the API lookup")

monkeypatch.setattr(check, "_load_issue", unexpected_lookup)
level, advice = check.scope_advice(body, "https://api.github.test/repos/org/repo")
assert level == "warning"
assert "plain Refs #N" in advice


@pytest.mark.parametrize(("issue", "level"), [
({}, "warning"),
({"labels": []}, "warning"),
({"pull_request": {}, "labels": [{"name": "status:accepted"}]}, "warning"),
(
{"repository_url": "https://api.github.test/repos/org/other",
"labels": [{"name": "status:accepted"}]},
"warning",
),
({"labels": [{"name": "status:accepted"}]}, "notice"),
])
def test_contract_advice_verifies_label_and_leaves_scope_to_review(monkeypatch, issue, level):
repo_url = "https://api.github.test/repos/org/repo"

def get_issue(url, number):
assert (url, number) == (repo_url, "574")
return {"repository_url": url, **issue}

monkeypatch.setattr(check, "_load_issue", get_issue)
annotation, advice = check.scope_advice("Refs #574\r\n", repo_url)
assert annotation == level
assert "#574" in advice
if level == "notice":
assert "decision recorded" in advice


def test_issue_lookup_uses_public_api_without_credentials(monkeypatch):
repo_url = "https://api.github.test/repos/org/repo"

def open_public_issue(request, timeout):
assert request.full_url == f"{repo_url}/issues/574"
assert dict(request.header_items()) == {"Accept": "application/vnd.github+json"}
assert timeout == 10
return BytesIO(b'{"number": 574}')

monkeypatch.setattr(check, "urlopen", open_public_issue)
assert check._load_issue(repo_url, "574") == {"number": 574}


def test_contract_advice_unavailable_leaves_the_existing_result(monkeypatch, capsys):
def unavailable(*args):
raise TimeoutError

monkeypatch.setenv("PR_BASE_SHA", "base")
monkeypatch.setenv("PR_HEAD_SHA", "head")
monkeypatch.setattr(check, "contracts_changed", unavailable)
monkeypatch.setenv("PR_BODY", "Refs #574")
assert check.main() == 0
assert "::warning::" in capsys.readouterr().out
monkeypatch.setenv("PR_BODY", "Closes #574")
assert check.main() == 1
assert "::warning::" in capsys.readouterr().out
93 changes: 92 additions & 1 deletion tools/check_pr_references.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,31 @@
from __future__ import annotations

import json
import os
import re
import subprocess
import sys
from http.client import HTTPException
from urllib.error import HTTPError
from urllib.request import Request, urlopen

# GitHub links an Issue for closure on merge when one of these keywords precedes the
# reference, including inside a negated sentence such as "this PR does not close #12".
KEYWORD = r"(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)"
REFERENCE = r"(?:[\w.-]+/[\w.-]+)?#\d+|https://github\.com/[\w.-]+/[\w.-]+/issues/\d+"
CLOSING = re.compile(rf"\b{KEYWORD}:?[ \t]+(?:{REFERENCE})\b", re.IGNORECASE)
GOVERNING_REF = re.compile(r"^Refs #([1-9][0-9]*)[ \t]*\r?$", re.MULTILINE)
ARCHITECTURE = "docs/architecture.md"
CONTRACT_PATHS = (
ARCHITECTURE,
"docs/contracts/",
"docs/module-layout.md",
"docs/legacy-knowledge-manifest.json",
)
ANCHOR_SECTION = re.compile(
r"^## Architecture anchors[ \t]*(?:\n|\Z).*?(?=^##[ \t]|\Z)",
re.MULTILINE | re.DOTALL,
)

ADVICE = (
"GitHub closes the referenced Issue on merge even when the sentence negates it. "
Expand All @@ -25,13 +42,87 @@ def violations(body: str) -> list[tuple[int, str]]:
]


def anchor_section(markdown: str) -> str | None:
match = ANCHOR_SECTION.search(markdown)
return match.group() if match else None


def _git(*args: str) -> str:
return subprocess.check_output(
("git", *args), encoding="utf-8", stderr=subprocess.PIPE
)


def contracts_changed(base: str, head: str) -> bool:
if _git("show", "-s", "--format=%P", "HEAD").split() != [base, head]:
raise ValueError("Checkout does not match the pull request merge commit")
changes = _git(
"diff", "--name-status", "--no-renames", "-z", "HEAD^1", "HEAD",
"--", *CONTRACT_PATHS,
).rstrip("\0").split("\0")
for status, path in zip(changes[::2], changes[1::2]):
if path != ARCHITECTURE:
return True
before = "" if status == "A" else _git("show", f"HEAD^1:{path}")
after = "" if status == "D" else _git("show", f"HEAD:{path}")
if anchor_section(before) != anchor_section(after):
return True
return False


def _load_issue(repo_url: str, number: str) -> dict:
# This checker runs from the PR checkout and reads public Issue metadata.
request = Request(
f"{repo_url}/issues/{number}",
headers={"Accept": "application/vnd.github+json"},
)
try:
with urlopen(request, timeout=10) as response:
return json.load(response)
except HTTPError as error:
if error.code in (404, 410):
return {}
raise


def scope_advice(body: str, repo_url: str) -> tuple[str, str]:
ref = GOVERNING_REF.search(body)
if not ref:
return "warning", "A9 requires a plain Refs #N for the governing Issue."
number = ref[1]
issue = _load_issue(repo_url, number)
if (
issue.get("repository_url", "").casefold() != repo_url.casefold()
or "pull_request" in issue
or "status:accepted" not in {label["name"] for label in issue.get("labels", [])}
):
return "warning", f"For A9, Refs #{number} needs a local Issue labelled status:accepted."
return "notice", f"Verify the decision recorded in #{number} accepts this contract change."


def _advise_on_contract_scope(body: str, base: str) -> None:
try:
if not contracts_changed(base, os.environ["PR_HEAD_SHA"]):
return
api = os.environ["GITHUB_API_URL"].rstrip("/")
repo_url = f"{api}/repos/{os.environ['GITHUB_REPOSITORY']}"
level, advice = scope_advice(body, repo_url)
except (subprocess.CalledProcessError, ValueError, KeyError, OSError, HTTPException):
level = "warning"
advice = "A9 check unavailable. Verify the live contract diff and accepted Issue."
print(f"::{level}::{advice}")


def main() -> int:
found = violations(os.environ["PR_BODY"])
body = os.environ["PR_BODY"]
found = violations(body)
# Each printed line starts with "line" so PR text cannot form a workflow command.
for number, line in found:
print(f"line {number}: closing syntax in PR body: {line}")
if found:
print(ADVICE)
if base := os.environ.get("PR_BASE_SHA"):
_advise_on_contract_scope(body, base)
return 1 if found else 0


Expand Down
Loading