Skip to content

Commit c4711cb

Browse files
wesbillmanCarl
andcommitted
fix(release): tag immutable desktop candidates
Make the merged release PR authorize publication of its exact reviewed head, freeze trusted check evidence at merge time, and carry a metadata-backed ledger across squash-merged candidate tags. Co-authored-by: Carl <c7ebe626f000404285d3686e1dc74cc07cc60a9754a150041ba132e14bd3e2ec@buzz.block.builderlab.xyz> Signed-off-by: Wes <[email protected]>
1 parent 79c5216 commit c4711cb

11 files changed

Lines changed: 341 additions & 269 deletions

‎.github/workflows/auto-tag-on-release-pr-merge.yml‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ jobs:
9191
echo "enabled=true"
9292
echo "tag=${TAG_PREFIX}${VERSION}"
9393
if [[ "$TAG_PREFIX" == desktop-v ]]; then
94-
echo "target_sha=${{ github.event.pull_request.merge_commit_sha }}"
94+
echo "target_sha=${{ github.event.pull_request.head.sha }}"
9595
echo "desktop=true"
9696
else
9797
echo "target_sha=$GITHUB_SHA"
@@ -112,6 +112,7 @@ jobs:
112112
PR_BASE_REF: ${{ github.event.pull_request.base.ref }}
113113
PR_HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name }}
114114
MERGE_SHA: ${{ github.event.pull_request.merge_commit_sha }}
115+
MERGED_AT: ${{ github.event.pull_request.merged_at }}
115116
run: |
116117
VERSION="${VERSION#desktop-v}"
117118
export VERSION
@@ -146,7 +147,17 @@ jobs:
146147
exit 1
147148
fi
148149
fi
149-
gh api --method POST "repos/$GITHUB_REPOSITORY/git/refs" \
150+
if ! gh api --method POST "repos/$GITHUB_REPOSITORY/git/refs" \
150151
-f ref="refs/tags/$TAG" \
151152
-f sha="$TARGET_SHA" \
152-
--silent
153+
--silent; then
154+
# Ref creation is atomic. A concurrent retry may have won the race;
155+
# accept that only when it created the exact immutable ref.
156+
EXISTING_SHA="$(gh api "repos/$GITHUB_REPOSITORY/commits/$TAG" --jq .sha)"
157+
if [ "$EXISTING_SHA" = "$TARGET_SHA" ]; then
158+
echo "Tag $TAG was concurrently created at $TARGET_SHA"
159+
exit 0
160+
fi
161+
echo "::error::Tag creation failed and $TAG resolves to $EXISTING_SHA (expected $TARGET_SHA)"
162+
exit 1
163+
fi

‎RELEASING.md‎

Lines changed: 24 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -48,28 +48,30 @@ or mobile GitHub Release.
4848
### Desktop
4949

5050
1. Run `just release-desktop <version>` from a clean, up-to-date `main` checkout.
51-
The script fetches the current `origin/main`, regenerates
52-
`version-bump/<version>` as one
53-
deterministic candidate commit, records the frozen base and proposed
54-
`desktop-v<version>` tag in `.release/desktop-candidate.json`, updates every
55-
desktop manifest and lockfile, writes a full-SHA changelog, and opens or
56-
updates the PR.
57-
2. Review the recorded base and candidate SHA, the complete changelog, and CI.
58-
The required **Desktop Release Candidate** check validates the exact head.
59-
A trusted repository member, owner, or collaborator must approve that exact
60-
candidate head. Any regeneration or push changes the head, invalidates the
61-
prior approval, and requires both the checks and approval to run again.
62-
3. **Squash merge** the PR. The protected branch must still be exactly the
63-
recorded base; otherwise regenerate the candidate from current `main`.
64-
4. `auto-tag-on-release-pr-merge` verifies the frozen parent, full-tree identity,
65-
required checks, and trusted approval on the exact candidate head, then tags
66-
the squash commit as `desktop-v<version>`. An admin or ruleset bypass does not
67-
authorize desktop tagging.
68-
5. The tag triggers `release.yml`. It builds and stages Apple Silicon and Intel
69-
macOS, Windows, and Linux artifacts; publishes the versioned release only
70-
after the complete set succeeds; then updates the rolling updater manifest
71-
last for stable versions. A failed platform leaves no partially published
72-
versioned release.
51+
The script creates one deterministic candidate commit and records both its
52+
frozen base and the verified prior release ledger in candidate metadata.
53+
2. Review the exact candidate SHA, complete changelog, and CI. Regenerating or
54+
pushing the branch creates a new candidate and requires checks to run again.
55+
3. **Squash merge** the PR after all protected-branch checks pass. The merge is
56+
the human authorization event; an authorized owner/admin bypass is treated
57+
the same way. Unrelated changes reaching `main` do not invalidate the
58+
reviewed candidate.
59+
4. `auto-tag-on-release-pr-merge` verifies the closed event against GitHub's PR
60+
identity, validates candidate content, and proves every required check came
61+
from its trusted producer and was successful when the PR merged. It creates
62+
`desktop-v<version>` at the exact reviewed PR head—not the squash commit.
63+
Retries accept that tag only at the same SHA and never move it. GitHub does
64+
not expose when an individual check rerun was created, so an ordinary rerun
65+
after merge deliberately makes tag verification fail closed; inspect that
66+
run and create a new candidate version rather than retrying the blocked tag.
67+
5. The tag triggers `release.yml`. It builds and stages all platform artifacts,
68+
publishes the versioned release only after the complete set succeeds, then
69+
updates the rolling updater manifest last for stable versions.
70+
71+
Because squash merging leaves immutable candidate tags on side history, the next
72+
release uses validated prior candidate metadata as its ledger boundary. It
73+
includes unrelated commits after the prior frozen base and excludes exactly the
74+
prior release's recorded squash commit; tag ancestry is deliberately irrelevant.
7375

7476
### Relay
7577

‎scripts/desktop_release.py‎

Lines changed: 89 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,17 @@
55

66
import argparse
77
import json
8+
import os
89
import re
910
import subprocess
1011
import sys
1112
from pathlib import Path
1213

13-
ROOT = Path(__file__).resolve().parent.parent
14+
ROOT = Path(os.environ.get("DESKTOP_RELEASE_ROOT", Path(__file__).resolve().parent.parent))
1415
CHANGELOG = ROOT / "CHANGELOG.md"
1516
METADATA = ROOT / ".release" / "desktop-candidate.json"
1617
SEMVER = re.compile(r"^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?$")
18+
STABLE_TAG = re.compile(r"desktop-v([0-9]+)\.([0-9]+)\.([0-9]+)$")
1719
DESKTOP_PATHS = (
1820
"desktop/",
1921
"crates/buzz-core/",
@@ -54,30 +56,71 @@ def commit_list(range_spec: str, paths: tuple[str, ...] | None = None) -> list[d
5456
return [dict(zip(("sha", "subject"), line.split("\0", 1))) for line in out.splitlines()]
5557

5658

57-
def stable_tags(base_sha: str) -> list[tuple[int, str, str]]:
58-
tags: list[tuple[int, str, str]] = []
59-
for tag in git("tag", "--merged", base_sha, "--list").splitlines():
60-
if not re.fullmatch(r"(?:desktop-)?v[0-9]+\.[0-9]+\.[0-9]+", tag):
59+
def gh_json(endpoint: str) -> object:
60+
try:
61+
return json.loads(subprocess.check_output(
62+
["gh", "api", endpoint], cwd=ROOT, text=True
63+
))
64+
except (subprocess.CalledProcessError, json.JSONDecodeError) as error:
65+
raise SystemExit(f"cannot verify prior desktop release via GitHub: {error}") from error
66+
67+
68+
def stable_tags() -> list[tuple[tuple[int, int, int], str, str]]:
69+
tags: list[tuple[tuple[int, int, int], str, str]] = []
70+
aliases: dict[tuple[int, int, int], list[tuple[str, str]]] = {}
71+
for tag in git("tag", "--list", "desktop-v*").splitlines():
72+
match = STABLE_TAG.fullmatch(tag)
73+
if not match:
6174
continue
75+
version = tuple(map(int, match.groups()))
6276
sha = git("rev-list", "-n", "1", tag)
63-
distance = int(git("rev-list", "--count", f"{sha}..{base_sha}"))
64-
tags.append((distance, tag, sha))
77+
aliases.setdefault(version, []).append((tag, sha))
78+
for version, refs in aliases.items():
79+
if len(refs) != 1:
80+
detail = ", ".join(f"{tag}@{sha}" for tag, sha in refs)
81+
raise SystemExit(f"ambiguous desktop release version {version}: {detail}")
82+
tag, sha = refs[0]
83+
tags.append((version, tag, sha))
6584
return tags
6685

6786

68-
def previous_tag(base_sha: str) -> str:
69-
tags = stable_tags(base_sha)
70-
if not tags:
71-
return ""
72-
min_distance = min(item[0] for item in tags)
73-
nearest = [item for item in tags if item[0] == min_distance]
74-
commits = {item[2] for item in nearest}
75-
if len(commits) != 1:
76-
detail = ", ".join(f"{tag}@{sha}" for _, tag, sha in nearest)
77-
raise SystemExit(f"ambiguous previous desktop release tags: {detail}")
78-
# During migration, prefer the namespaced tag when aliases share a commit.
79-
nearest.sort(key=lambda item: (not item[1].startswith("desktop-v"), item[1]))
80-
return nearest[0][1]
87+
def previous_release(version: str, repo: str) -> dict[str, str] | None:
88+
target = tuple(map(int, version.split("-", 1)[0].split(".")))
89+
tags = stable_tags()
90+
newer = [item for item in tags if item[0] >= target]
91+
if newer:
92+
detail = ", ".join(item[1] for item in newer)
93+
raise SystemExit(f"desktop release version must increase beyond existing tags: {detail}")
94+
eligible = [item for item in tags if item[0] < target]
95+
if not eligible:
96+
return None
97+
prior_version, tag, candidate_sha = max(eligible)
98+
try:
99+
metadata = json.loads(git("show", f"{tag}:.release/desktop-candidate.json"))
100+
except (subprocess.CalledProcessError, json.JSONDecodeError) as error:
101+
raise SystemExit(f"prior release {tag} has invalid candidate metadata") from error
102+
expected = {
103+
"version": ".".join(map(str, prior_version)),
104+
"tag": tag,
105+
}
106+
if any(metadata.get(key) != value for key, value in expected.items()):
107+
raise SystemExit(f"prior release {tag} metadata does not match its tag")
108+
base_sha = metadata.get("base_sha")
109+
if not isinstance(base_sha, str) or not re.fullmatch(r"[0-9a-f]{40}", base_sha):
110+
raise SystemExit(f"prior release {tag} has invalid base_sha")
111+
pulls = gh_json(f"repos/{repo}/commits/{candidate_sha}/pulls")
112+
matches = [pr for pr in pulls if pr.get("merged_at") and (
113+
pr.get("head", {}).get("sha") == candidate_sha
114+
or pr.get("merge_commit_sha") == candidate_sha
115+
)]
116+
if len(matches) != 1 or not matches[0].get("merge_commit_sha"):
117+
raise SystemExit(f"prior release {tag} does not identify exactly one merged release PR")
118+
return {
119+
"tag": tag,
120+
"candidate_sha": candidate_sha,
121+
"base_sha": base_sha,
122+
"merge_sha": matches[0]["merge_commit_sha"],
123+
}
81124

82125

83126
def bullet(commit: dict[str, str], repo: str) -> str:
@@ -91,24 +134,27 @@ def bullet(commit: dict[str, str], repo: str) -> str:
91134
return f"- {subject} ([`{sha}`](https://github.com/{repo}/commit/{sha}))"
92135

93136

94-
def expected(base_sha: str, previous: str) -> tuple[list[dict[str, str]], list[dict[str, str]]]:
95-
# With no prior desktop tag, account for the repository's root commit too.
96-
# A ``root..base`` range silently drops that first commit.
97-
range_spec = f"{previous}..{base_sha}" if previous else base_sha
98-
all_commits = commit_list(range_spec)
99-
relevant_shas = {c["sha"] for c in commit_list(range_spec, DESKTOP_PATHS)}
137+
def expected(base_sha: str, previous_base: str, previous_merge: str) -> tuple[list[dict[str, str]], list[dict[str, str]]]:
138+
# Immutable candidate tags may live on side history after squash merge. The
139+
# prior candidate metadata is the ledger boundary; exclude only its known
140+
# squash commit so unrelated commits around that merge remain accounted for.
141+
range_spec = f"{previous_base}..{base_sha}" if previous_base else base_sha
142+
all_commits = [c for c in commit_list(range_spec) if c["sha"] != previous_merge]
143+
relevant_shas = {c["sha"] for c in commit_list(range_spec, DESKTOP_PATHS)} - {previous_merge}
100144
relevant = [c for c in all_commits if c["sha"] in relevant_shas]
101145
other = [c for c in all_commits if c["sha"] not in relevant_shas]
102146
return relevant, other
103147

104148

105-
def render(version: str, base_sha: str, previous: str, repo: str) -> tuple[str, list[str]]:
106-
relevant, other = expected(base_sha, previous)
149+
def render(version: str, base_sha: str, previous: dict[str, str] | None, repo: str) -> tuple[str, list[str]]:
150+
relevant, other = expected(
151+
base_sha, previous["base_sha"] if previous else "", previous["merge_sha"] if previous else ""
152+
)
107153
lines = [f"## v{version}", "", "### Desktop and shared changes", ""]
108154
lines += [bullet(c, repo) for c in relevant] or ["- None"]
109155
lines += ["", "### Other repository changes", ""]
110156
lines += [bullet(c, repo) for c in other] or ["- None"]
111-
compare_start = previous or git("rev-list", "--max-parents=0", base_sha).splitlines()[0]
157+
compare_start = previous["tag"] if previous else git("rev-list", "--max-parents=0", base_sha).splitlines()[0]
112158
lines += ["", f"[Compare {compare_start}...desktop-v{version}](https://github.com/{repo}/compare/{compare_start}...desktop-v{version})"]
113159
return "\n".join(lines) + "\n", [c["sha"] for c in relevant + other]
114160

@@ -117,8 +163,8 @@ def generate(args: argparse.Namespace) -> None:
117163
if not SEMVER.fullmatch(args.version):
118164
raise SystemExit(f"invalid semver: {args.version}")
119165
base_sha = git("rev-parse", args.base)
120-
previous = previous_tag(base_sha)
121166
repo = args.repo or re.sub(r".*github\.com[:/]", "", git("remote", "get-url", "origin")).removesuffix(".git")
167+
previous = previous_release(args.version, repo)
122168
block, commits = render(args.version, base_sha, previous, repo)
123169
old = CHANGELOG.read_text() if CHANGELOG.exists() else "# Changelog\n"
124170
if not old.startswith("# Changelog"):
@@ -127,10 +173,12 @@ def generate(args: argparse.Namespace) -> None:
127173
CHANGELOG.write_text(f"# Changelog\n\n{block}\n{remainder}")
128174
METADATA.parent.mkdir(parents=True, exist_ok=True)
129175
METADATA.write_text(json.dumps({
130-
"schema": 1,
176+
"schema": 2,
131177
"version": args.version,
132178
"base_sha": base_sha,
133-
"previous_tag": previous or None,
179+
"previous_tag": previous["tag"] if previous else None,
180+
"previous_base_sha": previous["base_sha"] if previous else None,
181+
"previous_merge_sha": previous["merge_sha"] if previous else None,
134182
"tag": f"desktop-v{args.version}",
135183
"commit_count": len(commits),
136184
}, indent=2) + "\n")
@@ -157,14 +205,16 @@ def validate(args: argparse.Namespace) -> None:
157205
if missing:
158206
detail.append(f"missing required files: {', '.join(sorted(missing))}")
159207
raise SystemExit("candidate is not version-only (" + "; ".join(detail) + ")")
160-
previous = data["previous_tag"] or ""
161-
actual_previous = previous_tag(data["base_sha"])
162-
if previous != actual_previous:
163-
raise SystemExit(
164-
f"recorded previous tag {previous or '<none>'} does not match "
165-
f"nearest release tag {actual_previous or '<none>'}"
166-
)
167208
repo = args.repo or "block/buzz"
209+
previous = previous_release(version, repo)
210+
recorded_previous = {
211+
"tag": data.get("previous_tag"),
212+
"base_sha": data.get("previous_base_sha"),
213+
"merge_sha": data.get("previous_merge_sha"),
214+
} if data.get("previous_tag") else None
215+
expected_previous = {key: previous[key] for key in ("tag", "base_sha", "merge_sha")} if previous else None
216+
if recorded_previous != expected_previous:
217+
raise SystemExit("recorded previous release ledger does not match immutable prior release")
168218
expected_block, shas = render(version, data["base_sha"], previous, repo)
169219
text = CHANGELOG.read_text()
170220
blocks = re.findall(rf"(?ms)^## v{re.escape(version)}\n.*?(?=^## v|\Z)", text)

‎scripts/prepare-desktop-release.sh‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,9 +71,9 @@ cat >"$body" <<EOF
7171
- **Previous desktop release:** \`$previous_tag\`
7272
- **Proposed immutable tag:** \`desktop-v$version\`
7373
74-
This PR must be **squash merged** only after the Desktop Release Candidate check passes. The branch must remain based directly on current \`main\`; stale base, payload drift, incomplete notes, or an unauthorized merge produce no tag.
74+
This PR may be **squash merged** after the Desktop Release Candidate check and all protected-branch checks pass. Merging authorizes publication of the exact reviewed candidate; later or unrelated changes on \`main\` cannot alter it.
7575
76-
The checked-in changelog accounts for every non-merge commit in the release range. Publication remains bound to the immutable candidate tag.
76+
The checked-in changelog accounts for every non-merge commit in the release range. The Desktop tag points to the reviewed candidate commit, not the later squash commit. Publication remains bound to that immutable candidate tag.
7777
EOF
7878
if existing="$(gh pr list --head "$branch" --state open --json number --jq '.[0].number')" && [[ -n "$existing" ]]; then
7979
gh pr edit "$existing" --title "chore(release): release Buzz Desktop version $version" --body-file "$body"

‎scripts/required-check-succeeded.jq‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,22 @@
1-
# GitHub treats success, skipped, and neutral as successful conclusions for
2-
# required checks. Evaluate the newest run so a stale pass cannot mask a rerun.
1+
# REST check runs do not expose per-attempt creation time. The endpoint is
2+
# intentionally queried with filter=latest; select the highest immutable run ID
3+
# for the trusted producer and require that returned attempt to have completed
4+
# successfully by merge. Any ordinary post-merge rerun therefore fails closed
5+
# and needs operator inspection. DCO alone has a bounded five-minute exception.
36
[
47
.[].check_runs[]
5-
| select(.name == $name)
8+
| select(.name == $name and .app.id == $integration_id)
69
]
7-
| sort_by(.started_at // .created_at // "")
10+
| sort_by(.id)
811
| last
12+
| select((.completed_at // null) != null)
13+
| select(
14+
(.completed_at | fromdateiso8601)
15+
<= (
16+
($merged_at | fromdateiso8601)
17+
+ (if $name == "DCO Check" then 300 else 0 end)
18+
)
19+
)
920
| .status == "completed"
1021
and (
1122
.conclusion == "success"

‎scripts/review-decision-approved.jq‎

Lines changed: 0 additions & 1 deletion
This file was deleted.

‎scripts/test-desktop-release-authorization.sh‎

Lines changed: 0 additions & 69 deletions
This file was deleted.

0 commit comments

Comments
 (0)