Skip to content
28 changes: 25 additions & 3 deletions .github/actions/runtime-changes/action.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
name: "4FusionLab runtime change detection"
description: "Compare the entire push range to the repository's auditable release-paths allowlist"
description: "Check runtime changes since the last published release, with an opt-in recovery mode"
inputs:
before:
description: "Previous commit in push event (github.event.before)"
Expand All @@ -11,13 +11,27 @@ inputs:
description: "Repository-relative runtime allowlist"
required: false
default: ".github/release-paths.txt"
recover-unpublished:
description: "If true, compare to last published ancestor release instead of just the push range"
required: false
default: "false"
token:
description: "Read-only GitHub token needed for Release API in recovery mode"
required: false
default: ""
outputs:
release:
description: "true iff runtime-affecting file was added/modified/deleted/renamed"
description: "true iff eligible runtime changes have not been published"
value: ${{ steps.changes.outputs.release }}
matched-count:
description: "Number of matched runtime paths"
value: ${{ steps.changes.outputs.matched_count }}
baseline-sha:
description: "Commit used as comparison baseline"
value: ${{ steps.changes.outputs.baseline_sha }}
baseline-tag:
description: "Published Release tag used as checkpoint, or blank for push range"
value: ${{ steps.changes.outputs.baseline_tag }}
runs:
using: composite
steps:
Expand All @@ -28,10 +42,18 @@ runs:
RELEASE_BEFORE: ${{ inputs.before }}
RELEASE_AFTER: ${{ inputs.after }}
RELEASE_PATHS_FILE: ${{ inputs.paths-file }}
RELEASE_RECOVERY: ${{ inputs.recover-unpublished }}
GITHUB_TOKEN: ${{ inputs.token }}
run: |
set -euo pipefail
args=()
case "$RELEASE_RECOVERY" in
true) args+=(--recover-unpublished) ;;
false) ;;
*) echo "Expected recover-unpublished=true|false" >&2; exit 2 ;;
esac
python3 "${{ github.action_path }}/detect.py" \
--config "$GITHUB_WORKSPACE/$RELEASE_PATHS_FILE" \
--before "$RELEASE_BEFORE" \
--after "$RELEASE_AFTER" \
--github-output "$GITHUB_OUTPUT"
--github-output "$GITHUB_OUTPUT" "${args[@]}"
101 changes: 98 additions & 3 deletions .github/actions/runtime-changes/detect.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,22 @@
"""Determine release eligibility from Git changes and a repository-specific allowlist."""
"""Determine release eligibility from changes since the last published release.

Legacy mode checks only github.event.before..github.sha. In opt-in recovery
mode, consider the cumulative net Git diff since the last published GitHub
Release on this branch. This repairs missed publications on later docs-only
pushes without touching or moving historical release tags.
"""
import argparse
import fnmatch
import subprocess
import json
import os
from pathlib import Path
import re
import subprocess
from urllib.request import Request, urlopen


VERSION_TAG = re.compile(r"^v[0-9]+\.[0-9]+\.[0-9]+(?:-[a-zA-Z0-9][a-zA-Z0-9.-]*)?$")
REPOSITORY = re.compile(r"^[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+$")


def read_rules(path):
Expand Down Expand Up @@ -40,24 +54,105 @@ def evaluate(paths, rules):
return len(matches) > 0, matches


def fetch_releases(repository, token):
"""Fail closed on API failures, rather than silently losing recovery."""
if (not REPOSITORY.fullmatch(repository)
or any(component in (".", "..") for component in repository.split("/"))):
raise ValueError("Expected a GitHub owner/repository name.")
if not token:
raise ValueError("GITHUB_TOKEN is required to recover unpublished releases.")
results = []
headers = {
"Accept": "application/vnd.github+json",
"Authorization": "Bearer " + token,
"User-Agent": "4FusionLab-Release-Recovery",
"X-GitHub-Api-Version": "2022-11-28",
}
for page in range(1, 102):
url = f"https://api.github.com/repos/{repository}/releases?per_page=100&page={page}"
with urlopen(Request(url, headers=headers), timeout=30) as response:
batch = json.load(response)
if not isinstance(batch, list):
raise ValueError("Unexpected response while listing published Releases.")
results.extend(batch)
if len(batch) < 100:
return results
raise ValueError("Published release pagination limit exceeded.")


def published_release_anchor(after, releases):
"""Return (tag, SHA) for the newest valid, published ancestor release.

An old published release may omit sidecar SHA-256 files (RuEn v1.0.0),
so ZIP assets suffice to establish a historical checkpoint. New releases
still have their own ZIP, manifest and checksum verification gates.
"""
candidates = []
for item in releases:
if item.get("draft") or not item.get("published_at"):
continue
tag = item.get("tag_name", "")
if not VERSION_TAG.fullmatch(tag):
continue
assets = item.get("assets") or []
if not any(a.get("name", "").endswith(".zip") for a in assets):
continue
candidates.append((item["published_at"], tag))
for _published_at, tag in sorted(candidates, reverse=True):
ref = f"refs/tags/{tag}^{{commit}}"
result = subprocess.run(
["git", "rev-parse", "--verify", "--quiet", ref],
capture_output=True, text=True,
)
if result.returncode:
raise RuntimeError(f"Published GitHub Release has no local tag: {tag}. Fetch all tags.")
sha = result.stdout.strip()
ancestry = subprocess.run(["git", "merge-base", "--is-ancestor", sha, after])
if ancestry.returncode == 0:
return tag, sha
if ancestry.returncode != 1:
raise RuntimeError(f"Cannot inspect published Release ancestry: {tag}")
if candidates:
raise RuntimeError("None of the published release tags is an ancestor of HEAD.")
return None


def release_baseline(before, after, repository, token):
"""If no releases exist, preserve the original per-push behavior."""
checkpoint = published_release_anchor(after, fetch_releases(repository, token))
if checkpoint:
tag, sha = checkpoint
return sha, tag
return before, ""


def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--config", required=True)
parser.add_argument("--before")
parser.add_argument("--after")
parser.add_argument("--github-output")
parser.add_argument("--changed", nargs="*")
parser.add_argument("--recover-unpublished", action="store_true")
args = parser.parse_args()
rules = read_rules(args.config)
files = args.changed if args.changed is not None else git_paths(args.before, args.after)
before, baseline_tag = args.before, ""
if args.recover_unpublished and args.changed is None:
before, baseline_tag = release_baseline(
args.before, args.after, os.environ.get("GITHUB_REPOSITORY", ""),
os.environ.get("GITHUB_TOKEN", ""),
)
files = args.changed if args.changed is not None else git_paths(before, args.after)
eligible, matched = evaluate(files, rules)
value = "true" if eligible else "false"
print(f"Baseline: {baseline_tag or 'push range'} ({before or 'initial tree'})")
print(f"Release eligible: {value} ({len(matched)} matching paths)")
for path in matched:
print(" " + path)
if args.github_output:
with open(args.github_output, "a", encoding="utf-8") as output:
output.write(f"release={value}\nmatched_count={len(matched)}\n")
output.write(f"baseline_sha={before or ''}\nbaseline_tag={baseline_tag}\n")


if __name__ == "__main__":
Expand Down
195 changes: 195 additions & 0 deletions .github/tests/test_release_recovery.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
"""Regression tests for opt-in recovery of GitHub Releases that failed CI.

All tests use local Git history and mocked GitHub API responses. No releases,
tags on real repositories, network calls or writes to remote branches occur.
"""

import importlib.util
import io
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
from unittest import mock


DETECTOR = Path(__file__).resolve().parents[1] / "actions" / "runtime-changes" / "detect.py"
SPEC = importlib.util.spec_from_file_location("recovery_detector", DETECTOR)
detect = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(detect)


def release(tag, published_at="2026-11-07T09:00:00Z", *, draft=False, assets=None):
return {
"tag_name": tag,
"draft": draft,
"published_at": published_at,
"assets": [{"name": name} for name in (
["Example-1.0.0.zip"] if assets is None else assets
)],
}


class RecoveryTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.original_cwd = os.getcwd()
os.chdir(self.root)
self.addCleanup(os.chdir, self.original_cwd)
self.git("init", "-b", "main")
self.git("config", "user.name", "CI")
self.git("config", "user.email", "ci@example.invalid")
self.rules = ["Example/**", "scripts/build_release.py"]

def git(self, *args):
return subprocess.run(
["git", *args], check=True, capture_output=True, text=True,
).stdout.strip()

def file(self, path, contents="new"):
target = self.root / path
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(contents, encoding="utf-8")

def commit(self, message):
self.git("add", "-A")
self.git("commit", "-m", message)
return self.git("rev-parse", "HEAD")

def baseline(self, tag="v1.0.0"):
self.file("Example/runtime.py", "baseline")
sha = self.commit("initial published runtime")
self.git("tag", tag)
return sha

def test_failed_runtime_release_recovers_on_docs_only_push(self):
baseline = self.baseline()
self.file("Example/runtime.py", "new runtime")
failed = self.commit("feat: runtime changed, CI publication failed")
self.file("README.md", "docs")
current = self.commit("docs: update README")
self.assertEqual(detect.impacted(detect.git_paths(failed, current), self.rules), [])
with mock.patch.object(detect, "fetch_releases", return_value=[release("v1.0.0")]):
start, tag = detect.release_baseline(failed, current, "4FusionLab/Example", "token")
self.assertEqual((start, tag), (baseline, "v1.0.0"))
matched = detect.impacted(detect.git_paths(start, current), self.rules)
self.assertEqual(matched, ["Example/runtime.py"])

def test_after_successful_release_docs_only_never_releases(self):
self.baseline()
self.file("Example/runtime.py", "published change")
runtime = self.commit("fix: published change")
self.git("tag", "v1.0.1")
self.file("README.md", "docs")
current = self.commit("docs only")
with mock.patch.object(detect, "fetch_releases", return_value=[
release("v1.0.0", "2026-11-06T09:00:00Z"),
release("v1.0.1", "2026-11-07T09:00:00Z"),
]):
start, tag = detect.release_baseline(runtime, current, "4FusionLab/Example", "token")
self.assertEqual((start, tag), (runtime, "v1.0.1"))
self.assertFalse(detect.evaluate(detect.git_paths(start, current), self.rules)[0])

def test_no_published_release_preserves_legacy_push_range(self):
self.baseline()
self.file("Example/runtime.py", "unpublished change")
previous = self.commit("runtime change never published")
self.file("README.md", "docs")
current = self.commit("documentation")
with mock.patch.object(detect, "fetch_releases", return_value=[]):
start, tag = detect.release_baseline(previous, current, "4FusionLab/Example", "token")
self.assertEqual((start, tag), (previous, ""))
self.assertFalse(detect.evaluate(detect.git_paths(start, current), self.rules)[0])

def test_newest_published_ancestor_not_most_recent_unrelated_release(self):
baseline = self.baseline()
self.file("Example/runtime.py", "main branch change")
head = self.commit("main runtime")
self.git("checkout", "--orphan", "other")
self.git("rm", "-r", "-f", ".")
self.file("README.md", "different branch")
self.commit("other branch")
self.git("tag", "v9.0.0")
self.git("checkout", "main")
checkpoint = detect.published_release_anchor(head, [
release("v9.0.0", "2026-11-08T09:00:00Z"),
release("v1.0.0", "2026-11-07T09:00:00Z"),
])
self.assertEqual(checkpoint, ("v1.0.0", baseline))

def test_draft_without_zip_and_malformed_tag_are_not_checkpoints(self):
baseline = self.baseline()
self.assertEqual(detect.published_release_anchor(baseline, [
release("v5.0.0", draft=True),
release("v4.0.0", assets=["release-notes.md"]),
release("v1.0.0; echo BAD"),
release("v1.0.0"),
]), ("v1.0.0", baseline))

def test_unfetchable_published_tag_fails_closed(self):
baseline = self.baseline()
with self.assertRaisesRegex(RuntimeError, "no local tag"):
detect.published_release_anchor(baseline, [release("v2.0.0")])

def test_http_failure_does_not_silently_disable_recovery(self):
with mock.patch.object(detect, "urlopen", side_effect=OSError("API offline")):
with self.assertRaisesRegex(OSError, "API offline"):
detect.fetch_releases("4FusionLab/Example", "token")
with self.assertRaisesRegex(ValueError, "GITHUB_TOKEN"):
detect.fetch_releases("4FusionLab/Example", "")
with self.assertRaisesRegex(ValueError, "owner/repository"):
detect.fetch_releases("../unsafe", "token")

def test_api_pagination_and_bearer_auth(self):
class APIResponse(io.BytesIO):
pass

seen = []

def urlopen(req, timeout):
seen.append((req.full_url, req.headers.get("Authorization"), timeout))
data = [release("v1.0.0")] * (100 if len(seen) == 1 else 1)
return APIResponse(json.dumps(data).encode("utf-8"))

with mock.patch.object(detect, "urlopen", side_effect=urlopen):
releases = detect.fetch_releases("4FusionLab/Example", "secure")
self.assertEqual(len(releases), 101)
self.assertEqual(len(seen), 2)
self.assertTrue(seen[0][0].endswith("page=1"))
self.assertTrue(seen[1][0].endswith("page=2"))
self.assertEqual(seen[0][1], "Bearer secure")

def test_composite_outputs_have_real_newlines_and_valid_version_tags(self):
baseline = self.baseline()
self.file("Example/feature.py")
current = self.commit("runtime missing release")
self.assertTrue(detect.VERSION_TAG.fullmatch("v1.2.3"))
self.assertTrue(detect.VERSION_TAG.fullmatch("v1.2.3-beta.1"))
self.assertFalse(detect.VERSION_TAG.fullmatch("v1_2_3"))
config = self.root / "release-paths.txt"
config.write_text("Example/**\n", encoding="utf-8")
output = self.root / "output"
args = [
"detect.py", "--config", str(config), "--before", baseline,
"--after", current, "--github-output", str(output),
"--recover-unpublished",
]
with mock.patch.object(sys, "argv", args), mock.patch.object(
detect, "fetch_releases", return_value=[release("v1.0.0")]
), mock.patch.dict(os.environ, {
"GITHUB_REPOSITORY": "4FusionLab/Example", "GITHUB_TOKEN": "token",
}):
detect.main()
self.assertEqual(output.read_text(encoding="utf-8"), (
"release=true\nmatched_count=1\n"
f"baseline_sha={baseline}\nbaseline_tag=v1.0.0\n"
))


if __name__ == "__main__":
unittest.main()
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ This repository holds reusable, **read-only** CI building blocks and organizatio

## Git, CI and releasing
- Prefer a small, reviewed PR for CI/publishing changes. Do not force-push or amend public history. Keep direct main pushes possible where repository permissions allow them.
- Do not manually create release tags. A direct push or PR merge to `main` triggers **only if the changed-file set includes shipped runtime inputs**.
- Do not manually create release tags. A push or PR merge to `main` may publish **only when shipped runtime inputs have changed since the last published Release**. A docs-only push can recover an earlier failed runtime release, but must never independently create one. See [`RELEASE_RECOVERY.md`](RELEASE_RECOVERY.md).
- Preserve each repository's `.github/release-paths.txt` as its reviewed release-eligibility allowlist. Pure README, docs, test, workflow, policy and AGENTS.md changes must not create a GitHub Release.
- GitVersion.Tool is pinned to **6.8.2**. Full Git history is required. Published tags, releases and uploaded assets are immutable; never retarget tags, clobber artifacts or downgrade a prerelease to Stable.
- Core shared Actions live at `.github/actions/` and must be pinned by their exact commit SHA in consuming projects. Do not reference the moving `main` branch in production release jobs.
Expand Down
Loading
Loading