diff --git a/.github/workflows/heart-health.yml b/.github/workflows/heart-health.yml index 1977d0ae..64ac62ee 100644 --- a/.github/workflows/heart-health.yml +++ b/.github/workflows/heart-health.yml @@ -106,6 +106,8 @@ jobs: # No GITHUB_TOKEN extraheader in .git/config: it would shadow the # App credential the commit step pushes with. persist-credentials: false + # Reruns retain the event SHA. Collect main's evidence on current main. + ref: ${{ github.ref == 'refs/heads/main' && 'refs/heads/main' || github.sha }} # The shared board look the dashboard renders with — imported from the # Brain, never copied here. @@ -261,41 +263,18 @@ jobs: env: GH_TOKEN: ${{ steps.push_token.outputs.token }} run: | - python - <<'PY' - import pathlib, re - readme = pathlib.Path("README.md") - text = readme.read_text() - board = pathlib.Path("readme_strip.md").read_text().strip() - begin, end = "", "" - block = f"{begin}\n{board}\n{end}" - if begin in text and end in text: - text = re.sub(re.escape(begin) + r".*?" + re.escape(end), block, - text, flags=re.DOTALL) - else: - # First run: insert the block just after the H1 title line. - lines = text.splitlines() - for i, ln in enumerate(lines): - if ln.startswith("# "): - lines.insert(i + 1, "\n" + block + "\n") - break - text = "\n".join(lines) - readme.write_text(text) - PY - # `git status --porcelain` rather than `git diff --quiet`, because - # the record's first line for a repo creates an UNTRACKED file, which - # a diff of the working tree cannot see. One commit a day carries both - # the README block and the day's appended lines. + gh auth setup-git + git fetch --no-tags origin refs/heads/main + python scripts/prepare_health_writeback.py if [ -n "$(git status --porcelain README.md timings/)" ]; then git config user.name "pyautolabs-bot[bot]" git config user.email "346909844+pyautolabs-bot[bot]@users.noreply.github.com" git add README.md timings/ git commit -m "docs(heart): daily board block + timing record [skip ci]" - # gh as git's credential helper, reading GH_TOKEN (the App token). - gh auth setup-git - git push - else - echo "README health block and timing record unchanged — nothing to commit." fi + # Also check a no-op publication. A racing writer wins and Pages skips. + git push origin HEAD:refs/heads/main + # Transition-only push alert. Compare the feed published by the PREVIOUS # run (live on Pages until this run deploys) with the one just rendered diff --git a/scripts/prepare_health_writeback.py b/scripts/prepare_health_writeback.py new file mode 100644 index 00000000..4e2256a9 --- /dev/null +++ b/scripts/prepare_health_writeback.py @@ -0,0 +1,52 @@ +"""Prepare generated Heart Health output for a normal push to fetched main.""" + +import subprocess +from pathlib import Path + +BEGIN = b"" +END = b"" + + +def git(*args): + return subprocess.check_output(["git", *args]) + + +def board_parts(readme): + """Return the text around the managed strip, including a first-run slot.""" + if BEGIN not in readme and END not in readme: + offset = 0 + for line in readme.splitlines(keepends=True): + offset += len(line) + if line.startswith(b"# "): + return readme[:offset].rstrip(b"\r\n") + b"\n\n", None, b"\n" + readme[offset:] + if readme.count(BEGIN) == readme.count(END) == 1: + prefix, _, tail = readme.partition(BEGIN) + block, marker, suffix = tail.partition(END) + if marker: + return prefix, block, suffix + raise SystemExit("Invalid README board markers or missing title. Publication stopped.") + + +def main(): + tip = git("rev-parse", "FETCH_HEAD").decode().strip() + subprocess.run(["git", "merge-base", "--is-ancestor", "HEAD", tip], check=True) + changed = git("diff", "--name-only", "-z", "HEAD", tip).split(b"\0") + if any(name not in (b"", b"README.md") for name in changed): + raise SystemExit("Collector inputs may have changed. Dispatch Heart Health on current main.") + if not git("ls-tree", tip, "README.md").startswith(b"100644 blob "): + raise SystemExit("README is missing or changed type. Publication stopped.") + original = board_parts(git("show", "HEAD:README.md")) + prefix, block, suffix = board_parts(git("show", tip + ":README.md")) + if original[1] != block: + raise SystemExit("Another writer changed the board strip. Dispatch Heart Health on current main.") + strip = Path("readme_strip.md").read_bytes().strip() + if not strip or BEGIN in strip or END in strip: + raise SystemExit("Rendered README board strip is empty or contains a marker.") + # Git carries the collector's unstaged timing appends across this checkout. + # Their committed baselines are identical at both commits (checked above). + git("switch", "--detach", tip) + Path("README.md").write_bytes(prefix + BEGIN + b"\n" + strip + b"\n" + END + suffix) + + +if __name__ == "__main__": + main() diff --git a/tests/test_health_writeback.py b/tests/test_health_writeback.py new file mode 100644 index 00000000..8239dd7e --- /dev/null +++ b/tests/test_health_writeback.py @@ -0,0 +1,94 @@ +"""Run the workflow's publication step against a bare remote and two clones.""" +import os +import shutil +import subprocess +from pathlib import Path + +import pytest +import yaml + +from heart.timings import append_gates + +ROOT = Path(__file__).resolve().parents[1] +README = "# Heart\n\n\nold\n\n" + + +def git(repo, *args): + return subprocess.check_output(["git", "-C", str(repo), *args], text=True).strip() + + +@pytest.fixture +def clones(tmp_path, monkeypatch): + remote = tmp_path / "origin.git" + git(tmp_path, "init", "--bare", "-b", "main", str(remote)) + collector = tmp_path / "collector" + git(tmp_path, "clone", str(remote), str(collector)) + for key in ("AUTHOR", "COMMITTER"): + monkeypatch.setenv(f"GIT_{key}_NAME", "test writer") + monkeypatch.setenv(f"GIT_{key}_EMAIL", "test@example.org") + (collector / "README.md").write_text(README) + (collector / "scripts").mkdir() + shutil.copy(ROOT / "scripts/prepare_health_writeback.py", collector / "scripts") + git(collector, "add", ".") + git(collector, "commit", "-m", "baseline") + git(collector, "push", "origin", "main") + writer = tmp_path / "writer" + git(tmp_path, "clone", str(remote), str(writer)) + (collector / "readme_strip.md").write_text("new") + # The production step installs Git credentials. A local remote needs none. + gh = tmp_path / "gh" + gh.write_text('#!/bin/sh\ntest "$*" = "auth setup-git"\n') + gh.chmod(0o755) + monkeypatch.setenv("PATH", str(tmp_path) + os.pathsep + os.environ["PATH"]) + return remote, collector, writer + + +def publish(collector): + workflow = yaml.safe_load((ROOT / ".github/workflows/heart-health.yml").read_text()) + steps = workflow["jobs"]["heart-health"]["steps"] + assert steps[0]["with"]["ref"] == "${{ github.ref == 'refs/heads/main' && 'refs/heads/main' || github.sha }}" + step = next(s for s in steps if s["name"].startswith("Commit the README block")) + return subprocess.run(["bash", "-eu", "-c", step["run"]], cwd=collector, + capture_output=True, text=True) + + +def advance(writer, name, content): + path = writer / name + path.parent.mkdir(exist_ok=True) + path.write_text(content) + git(writer, "add", name) + git(writer, "commit", "-m", "independent advance") + git(writer, "push") + + +def test_publish_over_prose_and_repeat_without_duplicate(clones): + remote, collector, writer = clones + advance(writer, "README.md", README + "New prose.\n") + record = collector / "timings/gates.jsonl" + observation = {"date": "2026-10-25", "gates": {}} + assert append_gates(record, observation) + result = publish(collector) + assert result.returncode == 0, result.stderr + published = git(remote, "rev-parse", "main") + assert git(remote, "rev-parse", "main^") == git(writer, "rev-parse", "HEAD") + assert git(remote, "show", "main:README.md") == README.replace("old", "new").strip() + "\nNew prose." + assert not append_gates(record, observation) + result = publish(collector) + assert result.returncode == 0, result.stderr + assert git(remote, "rev-parse", "main") == published + assert len(git(remote, "show", "main:timings/gates.jsonl").splitlines()) == 1 + + +@pytest.mark.parametrize(("name", "content"), [ + ("README.md", README.replace("old", "concurrent board")), + ("timings/gates.jsonl", '{"date":"2026-10-25"}\n'), + ("collector.py", "changed input"), +]) +def test_conflict_stops_publication_even_with_unchanged_output(clones, name, content): + remote, collector, writer = clones + (collector / "readme_strip.md").write_text("old") + advance(writer, name, content) + result = publish(collector) + assert result.returncode != 0 + assert "Dispatch Heart Health on current main" in result.stderr + assert git(remote, "rev-parse", "main") == git(writer, "rev-parse", "HEAD")